repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
jelly/patternfly-react
packages/react-core/src/components/Menu/MenuContent.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Menu/menu'; import { css } from '@patternfly/react-styles'; import { MenuContext } from './MenuContext'; export interface MenuContentProps extends React.HTMLProps<HTMLElement> { /** Items within group */ children?: React.ReactNode; /** Forwarded ref */ innerRef?: React.Ref<any>; /** Height of the menu content */ menuHeight?: string; /** Maximum height of menu content */ maxMenuHeight?: string; /** Callback to return the height of the menu content */ getHeight?: (height: string) => void; } export const MenuContent = React.forwardRef((props: MenuContentProps, ref: React.Ref<HTMLDivElement>) => { const { getHeight, children, menuHeight, maxMenuHeight, ...rest } = props; const menuContentRef = React.createRef<HTMLDivElement>(); const refCallback = (el: HTMLElement, menuId: string, onGetMenuHeight: (menuId: string, height: number) => void) => { if (el) { let clientHeight = el.clientHeight; // if this menu is a submenu, we need to account for the root menu list's padding and root menu content's border. let rootMenuList = null; let parentEl = el.closest(`.${styles.menuList}`); while (parentEl !== null && parentEl.nodeType === 1) { if (parentEl.classList.contains(styles.menuList)) { rootMenuList = parentEl; } parentEl = parentEl.parentElement; } if (rootMenuList) { const rootMenuListStyles = getComputedStyle(rootMenuList); const rootMenuListPaddingOffset = parseFloat(rootMenuListStyles.getPropertyValue('padding-top').replace(/px/g, '')) + parseFloat(rootMenuListStyles.getPropertyValue('padding-bottom').replace(/px/g, '')) + parseFloat( getComputedStyle(rootMenuList.parentElement) .getPropertyValue('border-bottom-width') .replace(/px/g, '') ); clientHeight = clientHeight + rootMenuListPaddingOffset; } onGetMenuHeight && onGetMenuHeight(menuId, clientHeight); getHeight && getHeight(clientHeight.toString()); } return ref || menuContentRef; }; return ( <MenuContext.Consumer> {({ menuId, onGetMenuHeight }) => ( <div {...rest} className={css(styles.menuContent, props.className)} ref={el => refCallback(el, menuId, onGetMenuHeight)} style={ { ...(menuHeight && { '--pf-c-menu__content--Height': menuHeight }), ...(maxMenuHeight && { '--pf-c-menu__content--MaxHeight': maxMenuHeight }) } as React.CSSProperties } > {children} </div> )} </MenuContext.Consumer> ); }); MenuContent.displayName = 'MenuContent';
jelly/patternfly-react
packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyBasic.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { ClipboardCopy } from '@patternfly/react-core'; export const ClipboardCopyBasic: React.FunctionComponent = () => ( <ClipboardCopy hoverTip="Copy" clickTip="Copied"> This is editable </ClipboardCopy> );
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TreeViewDemo/TreeViewDemo.tsx
<reponame>jelly/patternfly-react import { Button, Toolbar, ToolbarContent, ToolbarItem, TreeView, TreeViewDataItem, TreeViewSearch } from '@patternfly/react-core'; import FolderIcon from '@patternfly/react-icons/dist/esm/icons/folder-icon'; import FolderOpenIcon from '@patternfly/react-icons/dist/esm/icons/folder-open-icon'; import React, { Component } from 'react'; export class TreeViewDemo extends Component { componentDidMount() { window.scrollTo(0, 0); } options: TreeViewDataItem[] = [ { name: 'ApplicationLauncher', id: 'AppLaunch', children: [ { name: 'Application 1', id: 'App1', children: [ { name: 'Settings', id: 'App1Settings' }, { name: 'Current', id: 'App1Current' } ] }, { name: 'Application 2', id: 'App2', children: [ { name: 'Settings', id: 'App2Settings' }, { name: 'Loader', id: 'App2Loader', children: [ { name: 'Loading App 1', id: 'LoadApp1' }, { name: 'Loading App 2', id: 'LoadApp2' }, { name: 'Loading App 3', id: 'LoadApp3' } ] } ] } ], defaultExpanded: true }, { name: 'Cost Management', id: 'Cost', children: [ { name: 'Application 3', id: 'App3', children: [ { name: 'Settings', id: 'App3Settings' }, { name: 'Current', id: 'App3Current' } ] } ] }, { name: 'Sources', id: 'Sources', children: [{ name: 'Application 4', id: 'App4', children: [{ name: 'Settings', id: 'App4Settings' }] }] }, { name: 'Really really really long folder name that overflows the container it is in', id: 'Long', children: [{ name: 'Application 5', id: 'App5' }] } ]; compactOptions: TreeViewDataItem[] = [ { name: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value and may reject unrecognized values.', title: 'apiVersion', id: 'apiVersion' }, { name: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated is CamelCase. More info:', title: 'kind', id: 'kind' }, { name: 'Standard metadata object', title: 'metadata', id: 'metadata' }, { name: 'Standard metadata object', title: 'spec', id: 'spec', children: [ { name: 'Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Default to 0 (pod will be considered available as soon as it is ready).', title: 'minReadySeconds', id: 'minReadySeconds' }, { name: 'Indicates that the deployment is paused', title: 'paused', id: 'paused' }, { name: 'The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that the progress will not de estimated during the time a deployment is paused. Defaults to 600s.', title: 'progressDeadlineSeconds', id: 'progressDeadlineSeconds', children: [ { name: 'The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.', title: 'revisionHistoryLimit', id: 'revisionHistoryLimit', children: [ { name: 'Map of {key.value} pairs. A single {key.value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In" and the values array contains only "value". The requirements are ANDed.', title: 'matchLabels', id: 'matchLabels' } ] } ] } ] } ]; state = { allExpanded: null as boolean, activeItems: [] as TreeViewDataItem[], activeItems2: [] as TreeViewDataItem[], filteredItems: this.options }; onClick = (evt: React.MouseEvent, treeViewItem: TreeViewDataItem, parentItem: TreeViewDataItem) => { this.setState({ activeItems: [treeViewItem, parentItem] }); }; onClick2 = (evt: React.MouseEvent, treeViewItem: TreeViewDataItem, parentItem: TreeViewDataItem) => { this.setState({ activeItems2: [treeViewItem, parentItem] }); }; onChange = (evt: React.ChangeEvent<HTMLInputElement>) => { const input = evt.target.value; if (input === '') { this.setState({ filteredItems: this.options }); } else { const filtered: TreeViewDataItem[] = this.options .map(opt => Object.assign({}, opt)) .filter(item => this.filterItems(item, input)); this.setState({ filteredItems: filtered }); } }; filterItems = (item: TreeViewDataItem, input: string): boolean => { if ( item.name .toString() .toLowerCase() .includes(input.toLowerCase()) ) { return true; } if (item.children) { return ( (item.children = item.children .map(opt => Object.assign({}, opt)) .filter(child => this.filterItems(child, input))).length > 0 ); } }; onToggle = () => { const { allExpanded } = this.state; this.setState({ allExpanded: allExpanded !== undefined ? !allExpanded : true }); }; render() { const { activeItems, activeItems2, filteredItems, allExpanded } = this.state; const flagOptions: TreeViewDataItem[] = [ { name: 'ApplicationLauncher', id: 'FAppLaunch', hasCheck: true, icon: <FolderIcon />, expandedIcon: <FolderOpenIcon />, children: [ { name: 'Application 1', id: 'FApp1', children: [ { name: 'Settings', id: 'FApp1Settings' }, { name: 'Current', id: 'FApp1Current' } ] }, { name: 'Application 2', id: 'FApp2', hasBadge: true, children: [ { name: 'Settings', id: 'FApp2Settings', hasCheck: true }, { name: 'Loader', id: 'FApp2Loader', children: [ { name: 'Loading App 1', id: 'FLoadApp1' }, { name: 'Loading App 2', id: 'FLoadApp2' }, { name: 'Loading App 3', id: 'FLoadApp3' } ] } ] } ], defaultExpanded: true }, { name: 'Cost Management', id: 'FCost', hasBadge: true, customBadgeContent: 'custom badge', action: ( <Button variant="plain" aria-label="Folder action"> <FolderIcon /> </Button> ), children: [ { name: 'Application 3', id: 'FApp3', children: [ { name: 'Settings', id: 'FApp3Settings' }, { name: 'Current', id: 'FApp3Current' } ] } ] }, { name: 'Sources', id: 'FSources', children: [{ name: 'Application 4', id: 'FApp4', children: [{ name: 'Settings', id: 'FApp4Settings' }] }] }, { name: 'Really really really long folder name that overflows the container it is in', id: 'FLong', children: [{ name: 'Application 5', id: 'FApp5' }] } ]; const toolbar = ( <Toolbar style={{ padding: 0 }}> <ToolbarContent style={{ padding: 0 }}> <ToolbarItem widths={{ default: '100%' }}> <TreeViewSearch onSearch={this.onChange} id="input-search" name="search-input" aria-label="Search input example" /> </ToolbarItem> </ToolbarContent> </Toolbar> ); return ( <React.Fragment> <Button id="expand" variant="link" onClick={this.onToggle}> {allExpanded && 'Collapse all'} {!allExpanded && 'Expand all'} </Button> <TreeView id="basic" allExpanded={allExpanded} data={filteredItems} activeItems={activeItems} onSelect={this.onClick} toolbar={toolbar} hasGuides /> <br /> <TreeView id="mixed" data={flagOptions} activeItems={activeItems2} onSelect={this.onClick2} /> <br /> <TreeView id="compact" data={this.compactOptions} activeItems={activeItems2} onSelect={this.onClick2} variant="compact" /> <br /> <TreeView id="compactNoBackground" data={this.compactOptions} activeItems={activeItems2} onSelect={this.onClick2} variant="compactNoBackground" /> </React.Fragment> ); } }
jelly/patternfly-react
packages/react-core/src/components/Chip/examples/ChipDefault.tsx
import React from 'react'; import { Badge, Chip } from '@patternfly/react-core'; export const ChipDefault: React.FunctionComponent = () => { const [chips, setChips] = React.useState({ chip: { name: 'Chip 1' }, longchip: { name: 'Really long chip that goes on and on' }, badgechip: { name: 'Chip', isRead: true, count: 7 }, readonlychip: { name: 'Read-only chip' }, overflowchip: { name: 'Overflow chip' } }); const deleteItem = (id: string) => { setChips({ ...chips, [id]: null }); }; const { chip, longchip, badgechip, readonlychip, overflowchip } = chips; return ( <React.Fragment> {chip && ( <React.Fragment> <Chip key="chip1" onClick={() => deleteItem('chip')}> {chip.name} </Chip> <br /> <br /> </React.Fragment> )} {longchip && ( <React.Fragment> <Chip key="chip2" onClick={() => deleteItem('longchip')}> {longchip.name} </Chip> <br /> <br /> </React.Fragment> )} {badgechip && ( <React.Fragment> <Chip key="chip3" onClick={() => deleteItem('badgechip')}> {badgechip.name} <Badge isRead={badgechip.isRead}>{badgechip.count}</Badge> </Chip> <br /> <br /> </React.Fragment> )} <Chip key="chip4" onClick={() => deleteItem('readonlychip')} isReadOnly> {readonlychip.name} </Chip> <br /> <br /> {overflowchip && ( <Chip key="chip5" component="button" onClick={() => deleteItem('overflowchip')} isOverflowChip> {overflowchip.name} </Chip> )} </React.Fragment> ); };
jelly/patternfly-react
packages/react-core/src/components/Truncate/Truncate.tsx
<filename>packages/react-core/src/components/Truncate/Truncate.tsx import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Truncate/truncate'; import { css } from '@patternfly/react-styles'; import { Tooltip, TooltipPosition } from '../Tooltip'; export enum TruncatePosition { start = 'start', end = 'end', middle = 'middle' } const truncateStyles = { start: styles.truncateEnd, end: styles.truncateStart }; const minWidthCharacters: number = 12; interface TruncateProps extends React.HTMLProps<HTMLSpanElement> { /** Class to add to outer span */ className?: string; /** Text to truncate */ content: string; /** The number of characters displayed in the second half of the truncation */ trailingNumChars?: number; /** Where the text will be truncated */ position?: 'start' | 'middle' | 'end'; /** Tooltip position */ tooltipPosition?: | TooltipPosition | 'auto' | 'top' | 'bottom' | 'left' | 'right' | 'top-start' | 'top-end' | 'bottom-start' | 'bottom-end' | 'left-start' | 'left-end' | 'right-start' | 'right-end'; } const sliceContent = (str: string, slice: number) => [str.slice(0, str.length - slice), str.slice(-slice)]; export const Truncate: React.FunctionComponent<TruncateProps> = ({ className, position = 'end', tooltipPosition = 'top', trailingNumChars = 7, content, ...props }: TruncateProps) => ( <Tooltip position={tooltipPosition} content={content}> <span className={css(styles.truncate, className)} {...props}> {(position === TruncatePosition.end || position === TruncatePosition.start) && ( <span className={truncateStyles[position]}> {content} {position === TruncatePosition.start && <React.Fragment>&lrm;</React.Fragment>} </span> )} {position === TruncatePosition.middle && content.slice(0, content.length - trailingNumChars).length > minWidthCharacters && ( <React.Fragment> <span className={styles.truncateStart}>{sliceContent(content, trailingNumChars)[0]}</span> <span className={styles.truncateEnd}>{sliceContent(content, trailingNumChars)[1]}</span> </React.Fragment> )} {position === TruncatePosition.middle && content.slice(0, content.length - trailingNumChars).length <= minWidthCharacters && content} </span> </Tooltip> ); Truncate.displayName = 'Truncate';
jelly/patternfly-react
packages/react-topology/src/components/defs/__tests__/SVGDefs.spec.tsx
<filename>packages/react-topology/src/components/defs/__tests__/SVGDefs.spec.tsx import * as React from 'react'; import { render } from '@testing-library/react'; import SVGDefs, { SVGDefsSetterProps } from '../SVGDefs'; import SVGDefsContext, { SVGDefsContextProps } from '../SVGDefsContext'; import { SVGDefsSetter } from '../SVGDefsSetter'; describe('SVGDefs', () => { it('should get #addDef and #removeDef from context', () => { const contextProps: SVGDefsContextProps = { addDef: jest.fn(), removeDef: jest.fn() }; const props: React.ComponentProps<typeof SVGDefs> = { id: 'foo', children: <span /> }; const { unmount } = render( <SVGDefsContext.Provider value={contextProps}> <SVGDefs {...props} /> </SVGDefsContext.Provider> ); // addDef called on mount and removeDef on unmount being called // signifies the context props were passed into SVGDefs (and therefore SVGDefsSetter). expect(contextProps.addDef).toHaveBeenCalledWith("foo", <span />); unmount(); expect(contextProps.removeDef).toHaveBeenLastCalledWith("foo"); }); describe('SVGDefsSetter', () => { it('should callback #addDef and #removeDef on update', () => { const props: SVGDefsSetterProps = { id: 'foo', addDef: jest.fn(), removeDef: jest.fn(), children: <span />, }; const { unmount, rerender } = render(<SVGDefsSetter {...props} />); expect(props.addDef).toHaveBeenCalledWith(props.id, props.children); // test update const newChild = <span />; rerender(<SVGDefsSetter {...props}>{newChild}</SVGDefsSetter>) expect(props.addDef).toHaveBeenCalledTimes(2); expect(props.addDef).toHaveBeenLastCalledWith(props.id, newChild); // test unmount unmount(); expect(props.removeDef).toHaveBeenCalledTimes(1); expect(props.removeDef).toHaveBeenLastCalledWith(props.id); }); }); });
jelly/patternfly-react
packages/react-table/src/components/Table/HeaderCellInfoWrapper.tsx
import * as React from 'react'; import HelpIcon from '@patternfly/react-icons/dist/esm/icons/help-icon'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Table/table'; import { Button, Tooltip, Popover, TooltipProps, PopoverProps } from '@patternfly/react-core'; import { TableText } from './TableText'; export interface ColumnHelpWrapperProps { /** * The header cell that is wrapped */ children: React.ReactNode; /** * The information that is presented in the tooltip/popover */ info: React.ReactNode; /** * Optional classname to add to the tooltip/popover */ className?: string; /** * The info variant */ variant?: 'tooltip' | 'popover'; /** * Additional props forwarded to the Popover component */ popoverProps?: Omit<PopoverProps, 'bodyContent'>; /** * Additional props forwarded to the tooltip component */ tooltipProps?: Omit<TooltipProps, 'content'>; /** * Aria label of the info button */ ariaLabel?: string; } export const HeaderCellInfoWrapper: React.FunctionComponent<ColumnHelpWrapperProps> = ({ children, info, className, variant = 'tooltip', popoverProps, tooltipProps, ariaLabel }: ColumnHelpWrapperProps) => ( <div className={css(styles.tableColumnHelp, className)}> {typeof children === 'string' ? <TableText>{children}</TableText> : children} <span className={css(styles.tableColumnHelpAction)}> {variant === 'tooltip' ? ( <Tooltip content={info} {...tooltipProps}> <Button variant="plain" aria-label={ariaLabel || (typeof info === 'string' && info) || 'More info'}> <HelpIcon noVerticalAlign /> </Button> </Tooltip> ) : ( <Popover bodyContent={info} {...popoverProps}> <Button variant="plain" aria-label={ariaLabel || (typeof info === 'string' && info) || 'More info'}> <HelpIcon noVerticalAlign /> </Button> </Popover> )} </span> </div> ); HeaderCellInfoWrapper.displayName = 'HeaderCellInfoWrapper';
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/__tests__/MultipleFileUpload.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { MultipleFileUpload } from '../MultipleFileUpload'; describe('MultipleFileUpload', () => { test('renders with expected class names when not horizontal', () => { const { asFragment } = render(<MultipleFileUpload>Foo</MultipleFileUpload>); expect(asFragment()).toMatchSnapshot(); }); test('renders with expected class names when horizontal', () => { const { asFragment } = render(<MultipleFileUpload isHorizontal>Foo</MultipleFileUpload>); expect(asFragment()).toMatchSnapshot(); }); test('renders custom class names', () => { const { asFragment } = render(<MultipleFileUpload className="test">Foo</MultipleFileUpload>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/SelectDemo/SelectTypeaheadFooterDemo.tsx
<gh_stars>0 import React from 'react'; import { Select, SelectOption, SelectVariant, Button } from '@patternfly/react-core'; /* eslint-disable no-console */ export interface SelectTypeaheadFooterDemoState { isOpen: boolean; selected: string[]; } export class SelectTypeaheadFooterDemo extends React.Component<SelectTypeaheadFooterDemoState> { static displayName = 'SelectTypeaheadFooterDemo'; state = { isOpen: false, selected: [] as string[] }; options = [ <SelectOption key={0} value="Choose..." isPlaceholder id="Choose..." />, <SelectOption key={1} value="Mr" id="Mr" />, <SelectOption key={2} value="Miss" id="Miss" />, <SelectOption key={3} value="Mrs" id="Mrs" />, <SelectOption key={4} value="Ms" id="Ms" />, <SelectOption key={5} value="Dr" id="Dr" />, <SelectOption key={6} value="Other" id="Other" /> ]; onToggle = (isOpen: boolean) => { this.setState({ isOpen }); }; clearSelection = () => { this.setState({ selected: null, isOpen: false }); }; onSelect = (_event: React.MouseEvent | React.ChangeEvent, selection: string, isPlaceholder: boolean) => { if (isPlaceholder) { this.clearSelection(); } else { this.setState({ selected: selection, isOpen: false }); console.log('selected:', selection); } }; render() { const { isOpen, selected } = this.state; const titleId = 'footer-typeahead-select-id'; return ( <div> <span id={titleId} hidden> Select a state </span> <Select isInputValuePersisted variant={SelectVariant.typeahead} typeAheadAriaLabel="Select an option" onToggle={this.onToggle} onSelect={this.onSelect} onClear={this.clearSelection} selections={selected} isOpen={isOpen} aria-labelledby={titleId} placeholderText="Select a state" footer={ <Button tabIndex={1} variant="link" isInline> Action </Button> } > {this.options} </Select> </div> ); } }
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/Shapes.tsx
import React from 'react'; import { Model, ModelKind, withPanZoom, GraphComponent, withDragNode, useComponentFactory, useModel, ComponentFactory, NodeShape } from '@patternfly/react-topology'; import '@patternfly/react-styles/css/components/Topology/topology-components.css'; import defaultComponentFactory from './components/defaultComponentFactory'; import shapesComponentFactory from './components/shapesComponentFactory'; import DemoDefaultNode from './components/DemoDefaultNode'; import withTopologySetup from './utils/withTopologySetup'; export const SHAPE_TITLE = 'Shapes'; export const Shapes = withTopologySetup(() => { useComponentFactory(defaultComponentFactory); useComponentFactory(shapesComponentFactory); // support pan zoom and drag useComponentFactory( React.useCallback<ComponentFactory>((kind, type) => { if (kind === ModelKind.graph) { return withPanZoom()(GraphComponent); } if (type === 'node-drag') { return withDragNode()(DemoDefaultNode); } return undefined; }, []) ); useModel( React.useMemo( (): Model => ({ graph: { id: 'g1', type: 'graph', x: 25, y: 25 }, nodes: [ { id: 'gr1', type: 'group-hull', group: true, children: ['n2', 'n3'], style: { padding: 10 } }, { id: 'gr2', type: 'group-hull', group: true, children: ['n4', 'n5'], style: { padding: 10 } }, { id: 'n1', type: 'node-drag', x: 50, y: 50, width: 30, height: 30 }, { id: 'n2', type: 'node', x: 200, y: 20, shape: NodeShape.rect, width: 30, height: 50 }, { id: 'n3', type: 'node', shape: NodeShape.ellipse, x: 150, y: 100, width: 50, height: 30 }, { id: 'n4', type: 'node-path', x: 300, y: 250, width: 30, height: 30 }, { id: 'n5', type: 'node-polygon', x: 350, y: 370, width: 65, height: 65 }, { id: 'n6', type: 'node', shape: NodeShape.rect, x: 300, y: 200, width: 60, height: 20 } ], edges: [ { id: 'e1', type: 'edge', source: 'n1', target: 'n2' }, { id: 'e2', type: 'edge', source: 'n1', target: 'n3' }, { id: 'e3', type: 'edge', source: 'n1', target: 'n4' }, { id: 'e4', type: 'edge', source: 'n1', target: 'n5' }, { id: 'e5', type: 'edge', source: 'n1', target: 'n6' } ] }), [] ) ); return null; });
jelly/patternfly-react
packages/react-inline-edit-extension/src/components/CancelButton/CancelButton.tsx
import * as React from 'react'; import CloseIcon from '@patternfly/react-icons/dist/esm/icons/close-icon'; import { Button, ButtonProps } from '@patternfly/react-core'; export const CancelButton: React.FunctionComponent<ButtonProps> = ({ variant = 'plain', ...props }: ButtonProps) => ( <Button variant={variant} {...props}> <CloseIcon /> </Button> ); CancelButton.displayName = 'CancelButton';
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/utils/logos.ts
<filename>packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/utils/logos.ts import jenkinsImg from '@patternfly/react-integration/demo-app-ts/src/assets/images/logos/jenkins.svg'; import mongodbImg from '@patternfly/react-integration/demo-app-ts/src/assets/images/logos/mongodb.svg'; import nodejsImg from '@patternfly/react-integration/demo-app-ts/src/assets/images/logos/nodejs.svg'; import openjdkImg from '@patternfly/react-integration/demo-app-ts/src/assets/images/logos/openjdk.svg'; export const logos = new Map<string, any>() .set('icon-jenkins', jenkinsImg) .set('icon-mongodb', mongodbImg) .set('icon-nodejs', nodejsImg) .set('icon-openjdk', openjdkImg) .set('icon-java', openjdkImg);
jelly/patternfly-react
packages/react-core/src/components/ChipGroup/index.ts
export * from './ChipGroup';
jelly/patternfly-react
packages/react-core/src/demos/ComposableMenu/examples/ComposableDateSelect.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { MenuToggle, Menu, MenuContent, MenuList, MenuItem, Popper } from '@patternfly/react-core'; export const ComposableSimpleDropdown: React.FunctionComponent = () => { const [isOpen, setIsOpen] = React.useState(false); const toggleRef = React.useRef<HTMLButtonElement>(); const menuRef = React.useRef<HTMLDivElement>(); const [selected, setSelected] = React.useState<number>(0); const handleMenuKeys = (event: KeyboardEvent) => { if (!isOpen) { return; } if (menuRef.current.contains(event.target as Node) || toggleRef.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)) { 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 = (ev: React.MouseEvent) => { ev.stopPropagation(); // Stop handleClickOutside from handling setTimeout(() => { if (menuRef.current) { const firstElement = menuRef.current.querySelector('li > button:not(:disabled)'); firstElement && (firstElement as HTMLElement).focus(); } }, 0); setIsOpen(!isOpen); }; const monthStrings = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; const dateString = (date: Date) => `${monthStrings[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`; const date = new Date(); const toggleText = { 0: 'Today ', 1: 'Yesterday ', 2: 'Last 7 days ', 3: 'Last 14 days ' }; const dateText = { 0: <small className="pf-u-color-200">({dateString(date)})</small>, 1: ( <small className="pf-u-color-200"> ({dateString(new Date(new Date().setDate(date.getDate() - 1)))} - {dateString(date)}) </small> ), 2: ( <small className="pf-u-color-200"> ({dateString(new Date(new Date().setDate(date.getDate() - 7)))} - {dateString(date)}) </small> ), 3: ( <small className="pf-u-color-200"> ({dateString(new Date(new Date().setDate(date.getDate() - 14)))} - {dateString(date)}) </small> ) }; const toggle = ( <MenuToggle ref={toggleRef} onClick={onToggleClick} isExpanded={isOpen} style={{ minWidth: '250px' }}> <span style={{ verticalAlign: 'middle', marginRight: '8px' }}>{toggleText[selected]}</span> {dateText[selected]} </MenuToggle> ); const menu = ( // eslint-disable-next-line no-console <Menu ref={menuRef} onSelect={(_ev, itemId) => setSelected(itemId as number)} selected={selected}> <MenuContent> <MenuList> <MenuItem itemId={0}>Today</MenuItem> <MenuItem itemId={1}>Yesterday</MenuItem> <MenuItem itemId={2}>Last 7 days</MenuItem> <MenuItem itemId={3}>Last 14 days</MenuItem> </MenuList> </MenuContent> </Menu> ); return <Popper trigger={toggle} popper={menu} isVisible={isOpen} popperMatchesTriggerWidth={false} />; };
jelly/patternfly-react
packages/react-core/src/components/ClipboardCopy/ClipboardCopy.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/ClipboardCopy/clipboard-copy'; import { css } from '@patternfly/react-styles'; import { PickOptional } from '../../helpers/typeUtils'; import { PopoverPosition } from '../Popover'; import { TooltipPosition } from '../Tooltip'; import { TextInput } from '../TextInput'; import { GenerateId } from '../../helpers/GenerateId/GenerateId'; import { ClipboardCopyButton } from './ClipboardCopyButton'; import { ClipboardCopyToggle } from './ClipboardCopyToggle'; import { ClipboardCopyExpanded } from './ClipboardCopyExpanded'; export const clipboardCopyFunc = (event: React.ClipboardEvent<HTMLDivElement>, text?: React.ReactNode) => { const clipboard = event.currentTarget.parentElement; const el = document.createElement('textarea'); el.value = text.toString(); clipboard.appendChild(el); el.select(); document.execCommand('copy'); clipboard.removeChild(el); }; export enum ClipboardCopyVariant { inline = 'inline', expansion = 'expansion', inlineCompact = 'inline-compact' } export interface ClipboardCopyState { text: string | number; expanded: boolean; copied: boolean; } export interface ClipboardCopyProps extends Omit<React.HTMLProps<HTMLDivElement>, 'onChange'> { /** Additional classes added to the clipboard copy container. */ className?: string; /** Tooltip message to display when hover the copy button */ hoverTip?: string; /** Tooltip message to display when clicking the copy button */ clickTip?: string; /** Aria-label to use on the TextInput. */ textAriaLabel?: string; /** Aria-label to use on the ClipboardCopyToggle. */ toggleAriaLabel?: string; /** Flag to show if the input is read only. */ isReadOnly?: boolean; /** Flag to determine if clipboard copy is in the expanded state initially */ isExpanded?: boolean; /** Flag to determine if clipboard copy content includes code */ isCode?: boolean; /** Flag to determine if inline clipboard copy should be block styling */ isBlock?: boolean; /** Adds Clipboard Copy variant styles. */ variant?: typeof ClipboardCopyVariant | 'inline' | 'expansion' | 'inline-compact'; /** Copy button popover position. */ position?: | PopoverPosition | TooltipPosition | 'auto' | 'top' | 'bottom' | 'left' | 'right' | 'top-start' | 'top-end' | 'bottom-start' | 'bottom-end' | 'left-start' | 'left-end' | 'right-start' | 'right-end'; /** Maximum width of the tooltip (default 150px). */ maxWidth?: string; /** Delay in ms before the tooltip disappears. */ exitDelay?: number; /** Delay in ms before the tooltip appears. */ entryDelay?: number; /** Delay in ms before the tooltip message switch to hover tip. */ switchDelay?: number; /** A function that is triggered on clicking the copy button. */ onCopy?: (event: React.ClipboardEvent<HTMLDivElement>, text?: React.ReactNode) => void; /** A function that is triggered on changing the text. */ onChange?: (text?: string | number) => void; /** The text which is copied. */ children: React.ReactNode; /** Additional actions for inline clipboard copy. Should be wrapped with ClipboardCopyAction. */ additionalActions?: React.ReactNode; } export class ClipboardCopy extends React.Component<ClipboardCopyProps, ClipboardCopyState> { static displayName = 'ClipboardCopy'; timer = null as number; constructor(props: ClipboardCopyProps) { super(props); this.state = { text: Array.isArray(this.props.children) ? this.props.children.join('') : (this.props.children as string | number), expanded: this.props.isExpanded, copied: false }; } static defaultProps: PickOptional<ClipboardCopyProps> = { hoverTip: 'Copy to clipboard', clickTip: 'Successfully copied to clipboard!', isReadOnly: false, isExpanded: false, isCode: false, variant: 'inline', position: PopoverPosition.top, maxWidth: '150px', exitDelay: 1600, entryDelay: 300, switchDelay: 2000, onCopy: clipboardCopyFunc, onChange: (): any => undefined, textAriaLabel: 'Copyable input', toggleAriaLabel: 'Show content', additionalActions: null }; // eslint-disable-next-line @typescript-eslint/no-unused-vars componentDidUpdate = (prevProps: ClipboardCopyProps, prevState: ClipboardCopyState) => { if (prevProps.children !== this.props.children) { this.updateText(this.props.children as string | number); } }; componentWillUnmount = () => { if (this.timer) { window.clearTimeout(this.timer); } }; // eslint-disable-next-line @typescript-eslint/no-unused-vars expandContent = (_event: React.MouseEvent<Element, MouseEvent>) => { this.setState(prevState => ({ expanded: !prevState.expanded })); }; updateText = (text: string | number) => { this.setState({ text }); this.props.onChange(text); }; render = () => { const { /* eslint-disable @typescript-eslint/no-unused-vars */ isExpanded, onChange, // Don't pass to <div> /* eslint-enable @typescript-eslint/no-unused-vars */ isReadOnly, isCode, isBlock, exitDelay, maxWidth, entryDelay, switchDelay, onCopy, hoverTip, clickTip, textAriaLabel, toggleAriaLabel, variant, position, className, additionalActions, ...divProps } = this.props; const textIdPrefix = 'text-input-'; const toggleIdPrefix = 'toggle-'; const contentIdPrefix = 'content-'; return ( <div className={css( styles.clipboardCopy, variant === 'inline-compact' && styles.modifiers.inline, isBlock && styles.modifiers.block, this.state.expanded && styles.modifiers.expanded, className )} {...divProps} > {variant === 'inline-compact' && ( <GenerateId prefix=""> {id => ( <React.Fragment> {!isCode && ( <span className={css(styles.clipboardCopyText)} id={`${textIdPrefix}${id}`}> {this.state.text} </span> )} {isCode && ( <code className={css(styles.clipboardCopyText, styles.modifiers.code)} id={`${textIdPrefix}${id}`}> {this.state.text} </code> )} <span className={css(styles.clipboardCopyActions)}> <span className={css(styles.clipboardCopyActionsItem)}> <ClipboardCopyButton variant="plain" exitDelay={exitDelay} entryDelay={entryDelay} maxWidth={maxWidth} position={position} id={`copy-button-${id}`} textId={`text-input-${id}`} aria-label={hoverTip} onClick={(event: any) => { if (this.timer) { window.clearTimeout(this.timer); this.setState({ copied: false }); } onCopy(event, this.state.text); this.setState({ copied: true }, () => { this.timer = window.setTimeout(() => { this.setState({ copied: false }); this.timer = null; }, switchDelay); }); }} > {this.state.copied ? clickTip : hoverTip} </ClipboardCopyButton> </span> {additionalActions && additionalActions} </span> </React.Fragment> )} </GenerateId> )} {variant !== 'inline-compact' && ( <GenerateId prefix=""> {id => ( <React.Fragment> <div className={css(styles.clipboardCopyGroup)}> {variant === 'expansion' && ( <ClipboardCopyToggle isExpanded={this.state.expanded} onClick={this.expandContent} id={`${toggleIdPrefix}${id}`} textId={`${textIdPrefix}${id}`} contentId={`${contentIdPrefix}${id}`} aria-label={toggleAriaLabel} /> )} <TextInput isReadOnly={isReadOnly || this.state.expanded} onChange={this.updateText} value={this.state.text as string | number} id={`text-input-${id}`} aria-label={textAriaLabel} /> <ClipboardCopyButton exitDelay={exitDelay} entryDelay={entryDelay} maxWidth={maxWidth} position={position} id={`copy-button-${id}`} textId={`text-input-${id}`} aria-label={hoverTip} onClick={(event: any) => { if (this.timer) { window.clearTimeout(this.timer); this.setState({ copied: false }); } onCopy(event, this.state.text); this.setState({ copied: true }, () => { this.timer = window.setTimeout(() => { this.setState({ copied: false }); this.timer = null; }, switchDelay); }); }} > {this.state.copied ? clickTip : hoverTip} </ClipboardCopyButton> </div> {this.state.expanded && ( <ClipboardCopyExpanded isReadOnly={isReadOnly} isCode={isCode} id={`content-${id}`} onChange={this.updateText} > {this.state.text} </ClipboardCopyExpanded> )} </React.Fragment> )} </GenerateId> )} </div> ); }; }
jelly/patternfly-react
packages/react-core/src/components/Divider/examples/DividerInsetMedium.tsx
import React from 'react'; import { Divider } from '@patternfly/react-core'; export const DividerInsetMedium: React.FunctionComponent = () => <Divider inset={{ default: 'insetMd' }} />;
jelly/patternfly-react
packages/react-core/src/components/Accordion/AccordionExpandedContentBody.tsx
<filename>packages/react-core/src/components/Accordion/AccordionExpandedContentBody.tsx import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Accordion/accordion'; export interface AccordionExpandedContentBodyProps { /** Content rendered inside the accordion content body */ children?: React.ReactNode; } export const AccordionExpandedContentBody: React.FunctionComponent<AccordionExpandedContentBodyProps> = ({ children = null }: AccordionExpandedContentBodyProps) => <div className={css(styles.accordionExpandedContentBody)}>{children}</div>; AccordionExpandedContentBody.displayName = 'AccordionExpandedContentBody';
jelly/patternfly-react
packages/react-core/src/components/Masthead/index.ts
export * from './Masthead'; export * from './MastheadBrand'; export * from './MastheadContent'; export * from './MastheadMain'; export * from './MastheadToggle';
jelly/patternfly-react
packages/react-table/src/components/TableComposable/examples/ComposableTableBasic.tsx
import React from 'react'; import { ToggleGroup, ToggleGroupItem, ToggleGroupItemProps } from '@patternfly/react-core'; import { TableComposable, Caption, Thead, Tr, Th, Tbody, Td } from '@patternfly/react-table'; interface Repository { name: string; branches: string | null; prs: string | null; workspaces: string; lastCommit: string; } type ExampleType = 'default' | 'compact' | 'compactBorderless'; export const ComposableTableBasic: React.FunctionComponent = () => { // In real usage, this data would come from some external source like an API via props. const repositories: Repository[] = [ { name: 'one', branches: 'two', prs: 'three', workspaces: 'four', lastCommit: 'five' }, { name: 'one - 2', branches: null, prs: null, workspaces: 'four - 2', lastCommit: 'five - 2' }, { name: 'one - 3', branches: 'two - 3', prs: 'three - 3', workspaces: 'four - 3', lastCommit: 'five - 3' } ]; const columnNames = { name: 'Repositories', branches: 'Branches', prs: 'Pull requests', workspaces: 'Workspaces', lastCommit: 'Last commit' }; // This state is just for the ToggleGroup in this example and isn't necessary for TableComposable usage. const [exampleChoice, setExampleChoice] = React.useState<ExampleType>('default'); const onExampleTypeChange: ToggleGroupItemProps['onChange'] = (_isSelected, event) => { const id = event.currentTarget.id; setExampleChoice(id as ExampleType); }; return ( <React.Fragment> <ToggleGroup aria-label="Default with single selectable"> <ToggleGroupItem text="Default" buttonId="default" isSelected={exampleChoice === 'default'} onChange={onExampleTypeChange} /> <ToggleGroupItem text="Compact" buttonId="compact" isSelected={exampleChoice === 'compact'} onChange={onExampleTypeChange} /> <ToggleGroupItem text="Compact borderless" buttonId="compactBorderless" isSelected={exampleChoice === 'compactBorderless'} onChange={onExampleTypeChange} /> </ToggleGroup> <TableComposable aria-label="Simple table" variant={exampleChoice !== 'default' ? 'compact' : undefined} borders={exampleChoice !== 'compactBorderless'} > <Caption>Simple table using composable components</Caption> <Thead> <Tr> <Th>{columnNames.name}</Th> <Th>{columnNames.branches}</Th> <Th>{columnNames.prs}</Th> <Th>{columnNames.workspaces}</Th> <Th>{columnNames.lastCommit}</Th> </Tr> </Thead> <Tbody> {repositories.map(repo => ( <Tr key={repo.name}> <Td dataLabel={columnNames.name}>{repo.name}</Td> <Td dataLabel={columnNames.branches}>{repo.branches}</Td> <Td dataLabel={columnNames.prs}>{repo.prs}</Td> <Td dataLabel={columnNames.workspaces}>{repo.workspaces}</Td> <Td dataLabel={columnNames.lastCommit}>{repo.lastCommit}</Td> </Tr> ))} </Tbody> </TableComposable> </React.Fragment> ); };
jelly/patternfly-react
packages/react-core/src/components/Modal/__tests__/Modal.test.tsx
<filename>packages/react-core/src/components/Modal/__tests__/Modal.test.tsx import * as React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { css } from '../../../../../react-styles/dist/js'; import styles from '@patternfly/react-styles/css/components/Backdrop/backdrop'; import { Modal } from '../Modal'; jest.spyOn(document, 'createElement'); jest.spyOn(document.body, 'addEventListener'); const props = { title: 'Modal', onClose: jest.fn(), isOpen: false, children: 'modal content' }; describe('Modal', () => { test('Modal creates a container element once for div', () => { render(<Modal {...props} />); expect(document.createElement).toHaveBeenCalledWith('div'); }); test('modal closes with escape', () => { render(<Modal {...props} isOpen appendTo={document.body} />); userEvent.type(screen.getByText(props.title), '{esc}'); expect(props.onClose).toHaveBeenCalled(); }); test('modal does not call onClose for esc key if it is not open', () => { render(<Modal {...props} />); expect(screen.queryByRole('dialog')).toBeNull(); expect(props.onClose).not.toHaveBeenCalled(); }); test('modal has body backdropOpen class when open', () => { render(<Modal {...props} isOpen />); expect(document.body).toHaveClass(css(styles.backdropOpen)); }); test('modal has no body backdropOpen class when not open', () => { render(<Modal {...props} />); expect(document.body).not.toHaveClass(css(styles.backdropOpen)); }); test('modal shows the close button when showClose is true (true by default)', () => { render(<Modal {...props} isOpen />); expect(screen.getByRole('button', { name: 'Close' })).toBeInTheDocument(); }); test('modal does not show the close button when showClose is false', () => { render(<Modal {...props} isOpen showClose={false} tabIndex={0} />); expect(screen.queryByRole('button', { name: 'Close' })).toBeNull(); }); test('modal generates console error when no accessible name is provided', () => { const props = { onClose: jest.fn(), isOpen: true, children: 'modal content' }; const consoleErrorMock = jest.fn(); global.console = { error: consoleErrorMock } as any; render(<Modal {...props} />); expect(consoleErrorMock).toHaveBeenCalled(); }); test('modal generates console warning when conflicting accessible name strategies are provided', () => { const props = { hasNoBodyWrapper: true, onClose: jest.fn(), isOpen: true, children: 'modal content' }; const consoleErrorMock = jest.fn(); global.console = { error: consoleErrorMock } as any; render(<Modal {...props} />); expect(consoleErrorMock).toHaveBeenCalled(); }); });
jelly/patternfly-react
packages/react-core/src/components/ApplicationLauncher/examples/ApplicationLauncherBasic.tsx
<gh_stars>0 import React from 'react'; import { ApplicationLauncher, ApplicationLauncherItem } from '@patternfly/react-core'; const appLauncherItems: React.ReactElement[] = [ <ApplicationLauncherItem key="application_1a" href="#"> Application 1 (anchor link) </ApplicationLauncherItem>, <ApplicationLauncherItem key="application_2a" component="button" onClick={() => alert('Clicked item 2')}> Application 2 (button with onClick) </ApplicationLauncherItem>, <ApplicationLauncherItem key="disabled_application_4a" isDisabled> Unavailable application </ApplicationLauncherItem> ]; export const ApplicationLauncherBasic: React.FunctionComponent = () => { const [isOpen, setIsOpen] = React.useState(false); const onToggle = (isOpen: boolean) => setIsOpen(isOpen); const onSelect = (_event: any) => setIsOpen(prevIsOpen => !prevIsOpen); return <ApplicationLauncher onSelect={onSelect} onToggle={onToggle} isOpen={isOpen} items={appLauncherItems} />; };
jelly/patternfly-react
packages/react-core/src/components/EmptyState/EmptyState.tsx
import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/EmptyState/empty-state'; export enum EmptyStateVariant { 'xs' = 'xs', small = 'small', large = 'large', 'xl' = 'xl', full = 'full' } export interface EmptyStateProps extends React.HTMLProps<HTMLDivElement> { /** Additional classes added to the EmptyState */ className?: string; /** Content rendered inside the EmptyState */ children: React.ReactNode; /** Modifies EmptyState max-width */ variant?: 'xs' | 'small' | 'large' | 'xl' | 'full'; /** Cause component to consume the available height of its container */ isFullHeight?: boolean; } export const EmptyState: React.FunctionComponent<EmptyStateProps> = ({ children, className = '', variant = EmptyStateVariant.full, isFullHeight, ...props }: EmptyStateProps) => ( <div className={css( styles.emptyState, variant === 'xs' && styles.modifiers.xs, variant === 'small' && styles.modifiers.sm, variant === 'large' && styles.modifiers.lg, variant === 'xl' && styles.modifiers.xl, isFullHeight && styles.modifiers.fullHeight, className )} {...props} > <div className={css(styles.emptyStateContent)}>{children}</div> </div> ); EmptyState.displayName = 'EmptyState';
jelly/patternfly-react
packages/react-charts/src/components/ChartUtils/chart-container.tsx
<reponame>jelly/patternfly-react<filename>packages/react-charts/src/components/ChartUtils/chart-container.tsx<gh_stars>0 /* eslint-disable camelcase */ import chart_global_label_Fill from '@patternfly/react-tokens/dist/esm/chart_global_label_Fill'; import * as React from 'react'; import { ContainerType, createContainer as victoryCreateContainer } from 'victory-create-container'; import { ChartCursorTooltip } from '../ChartCursorTooltip'; import { ChartLabel } from '../ChartLabel'; import { LineSegment } from 'victory-core'; /** * Makes a container component with multiple behaviors. It allows you to effectively combine any two * containers of type 'brush', 'cursor', 'selection', 'voronoi', or 'zoom'. Default container props are applied to * support the PatternFly theme. * * Each behavior must be one of the following strings: 'brush', 'cursor', 'selection', 'voronoi', and 'zoom'. The * resulting container uses the events from both behaviors. For example, if both behaviors use the click event (like * zoom and selection) the combined container will trigger both behaviors' events on each click. * * Note: Order of the behaviors matters in a few cases. It is recommended to use 'zoom' before any other behaviors: for * example, createContainer('zoom', 'voronoi') instead of createContainer('voronoi', 'zoom'). * * See https://formidable.com/open-source/victory/docs/create-container * * @param {string} behaviorA 'brush', 'cursor', 'selection', 'voronoi', or 'zoom' * @param {string} behaviorB 'brush', 'cursor', 'selection', 'voronoi', or 'zoom' */ export const createContainer = (behaviorA: ContainerType, behaviorB: ContainerType) => { const container: any = victoryCreateContainer(behaviorA, behaviorB); const isCursor = behaviorA === 'cursor' || behaviorB === 'cursor'; const isVoronoi = behaviorA === 'voronoi' || behaviorB === 'voronoi'; if (isCursor) { container.defaultProps.cursorLabelComponent = <ChartLabel textAnchor="start" />; container.defaultProps.cursorComponent = ( <LineSegment style={{ stroke: chart_global_label_Fill.value }} /> ); } if (isVoronoi) { container.defaultProps.labelComponent = <ChartCursorTooltip />; } return container; };
jelly/patternfly-react
packages/react-topology/src/layouts/GridLayout.ts
import { Edge, Graph, Layout, Node } from '../types'; import { BaseLayout } from './BaseLayout'; import { LayoutOptions } from './LayoutOptions'; import { LayoutNode } from './LayoutNode'; import { LayoutLink } from './LayoutLink'; import { GridNode } from './GridNode'; import { GridLink } from './GridLink'; import { GridGroup } from './GridGroup'; export type GridLayoutOptions = LayoutOptions; export class GridLayout extends BaseLayout implements Layout { private gridOptions: GridLayoutOptions; constructor(graph: Graph, options?: Partial<GridLayoutOptions>) { super(graph, options); this.gridOptions = { ...this.options, ...options }; } protected createLayoutNode(node: Node, nodeDistance: number, index: number) { return new GridNode(node, nodeDistance, index); } protected createLayoutLink(edge: Edge, source: LayoutNode, target: LayoutNode, isFalse: boolean): LayoutLink { return new GridLink(edge, source, target, isFalse); } protected createLayoutGroup(node: Node, padding: number, index: number) { return new GridGroup(node, padding, index); } public startLayout(graph: Graph, initialRun: boolean, addingNodes: boolean): void { if (initialRun || addingNodes) { this.nodes.sort((a, b) => a.id.localeCompare(b.id)); const totalNodes = this.nodes.length; const maxPerRow = Math.round(Math.sqrt(totalNodes)); let x = 0; let y = 0; let rowI = 0; let padX = 0; let padY = 0; for (let i = 0; i < totalNodes; i++) { const node = this.nodes[i]; if (padX < node.width) { padX = node.width; } if (padY < node.height) { padY = node.height; } } for (let i = 0; i < totalNodes; i++) { const node = this.nodes[i]; node.x = x; node.y = y; node.update(); if (rowI < maxPerRow) { x += padX; rowI++; } else { rowI = 0; x = 0; y += padY; } } } } }
jelly/patternfly-react
packages/react-catalog-view-extension/src/components/CatalogTile/CatalogTile.tsx
<reponame>jelly/patternfly-react<gh_stars>100-1000 import * as React from 'react'; import { Card, CardActions, CardHeader, CardTitle, CardBody, CardFooter } from '@patternfly/react-core'; import { css } from '@patternfly/react-styles'; export interface CatalogTileProps extends Omit<React.HTMLProps<HTMLElement>, 'title'> { /** Id */ id?: any; /** Additional css classes */ className?: string; /** Flag if the tile is 'featured' */ featured: boolean; /** Callback for a click on the tile */ onClick?: (event: React.SyntheticEvent<HTMLElement>) => void; /** href for the tile if used as a link */ href: string; /** URL of an image for the item's icon */ iconImg?: string; /** Alternate text for the item's icon */ iconAlt?: string; /** Class for the image when an icon is to be used (exclusive from iconImg) */ iconClass?: string; /** Alternatively provided JSX for the icon */ icon?: React.ReactNode; /** Array of badges */ badges?: React.ReactNode[]; /** Tile for the catalog item */ title: string | React.ReactNode; /** Vendor for the catalog item */ vendor?: string | React.ReactNode; /** Description of the catalog item */ description?: string | React.ReactNode; /** Footer for the tile */ footer?: string | React.ReactNode; /** Body content that isn't truncated */ children?: React.ReactNode; } export class CatalogTile extends React.Component<CatalogTileProps> { static displayName = 'CatalogTile'; static defaultProps = { id: null as any, className: '', featured: false, onClick: null as (event: React.SyntheticEvent<HTMLElement>) => void, href: null as string, iconImg: null as string, iconAlt: '', iconClass: '', icon: null as React.ReactNode, badges: [] as React.ReactNode[], vendor: null as string | React.ReactNode, description: null as string | React.ReactNode, footer: null as string | React.ReactNode, children: null as React.ReactNode }; private handleClick = (e: React.SyntheticEvent<HTMLElement>) => { const { onClick, href } = this.props; if (!href) { e.preventDefault(); } if (onClick) { onClick(e); } }; private renderBadges = (badges: React.ReactNode[]) => { if (!badges || !badges.length) { return null; } return ( <div className="catalog-tile-pf-badge-container"> {badges.map((badge, index) => ( <span key={`badge-${index}`}>{badge}</span> ))} </div> ); }; render() { const { id, className, featured, onClick, href, icon, iconImg, iconAlt, iconClass, badges, title, vendor, description, footer, // eslint-disable-next-line @typescript-eslint/no-unused-vars ref, children, ...props } = this.props; return ( <Card component={href || onClick ? 'a' : 'div'} id={id} href={href || '#'} className={css('catalog-tile-pf', { featured }, className)} onClick={e => this.handleClick(e)} isSelectable {...props} > {(badges.length > 0 || iconImg || iconClass || icon) && ( <CardHeader> {iconImg && <img className="catalog-tile-pf-icon" src={iconImg} alt={iconAlt} />} {!iconImg && (iconClass || icon) && <span className={`catalog-tile-pf-icon ${iconClass}`}>{icon}</span>} {badges.length > 0 && <CardActions>{this.renderBadges(badges)}</CardActions>} </CardHeader> )} <CardTitle className="catalog-tile-pf-header"> <div className="catalog-tile-pf-title">{title}</div> {vendor && <div className="catalog-tile-pf-subtitle">{vendor}</div>} </CardTitle> {(description || children) && ( <CardBody className="catalog-tile-pf-body"> {description && ( <div className="catalog-tile-pf-description"> <span className={css({ 'has-footer': footer })}>{description}</span> </div> )} {children} </CardBody> )} {footer && <CardFooter className="catalog-tile-pf-footer">{footer}</CardFooter>} </Card> ); } }
jelly/patternfly-react
packages/react-topology/src/components/nodes/labels/LabelIcon.tsx
<reponame>jelly/patternfly-react<gh_stars>0 import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; interface LabelIconProps { className?: string; x: number; y: number; width: number; height: number; padding?: number; iconClass?: string; icon?: React.ReactNode; } const LabelIcon = React.forwardRef<SVGCircleElement, LabelIconProps>( ({ className, x, y, width, height, iconClass, icon, padding = 4 }, circleRef) => { const radius = width / 2; const cx = x - radius; const cy = y + height / 2; const innerX = x - width + padding + 1; const innerY = y + padding + 1; const innerWidth = width - padding * 2 - 2; // -2 for 1px border on each side const innerHeight = height - padding * 2 - 2; // -2 for 1px border on each side return ( <g className={css(styles.topologyNodeLabelIcon, className)}> <circle className={css(styles.topologyNodeLabelIconBackground)} ref={circleRef} cx={cx} cy={cy} r={radius} /> {icon ? ( <foreignObject className={css(styles.topologyNodeLabelIcon)} x={innerX} y={innerY} width={innerWidth} height={innerHeight} > {icon} </foreignObject> ) : ( <image x={innerX} y={innerY} width={innerWidth} height={innerHeight} xlinkHref={iconClass} /> )} </g> ); } ); export default LabelIcon;
jelly/patternfly-react
packages/react-core/src/components/LoginPage/__tests__/LoginMainFooterBandItem.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import { LoginMainFooterBandItem } from '../LoginMainFooterBandItem'; describe('LoginMainFooterBandItem', () => { test('renders with PatternFly Core styles', () => { const { asFragment } = render(<LoginMainFooterBandItem />); expect(asFragment()).toMatchSnapshot(); }); test('className is added to the root element', () => { render(<LoginMainFooterBandItem className="extra-class">test</LoginMainFooterBandItem>); expect(screen.getByText('test')).toHaveClass('extra-class'); }); test('with custom node', () => { const CustomNode = () => <div>My custom node</div>; render( <LoginMainFooterBandItem> <CustomNode /> </LoginMainFooterBandItem> ); expect(screen.getByText('My custom node')).toBeInTheDocument(); }); });
jelly/patternfly-react
packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyJSONObject.tsx
<reponame>jelly/patternfly-react<gh_stars>0 import React from 'react'; import { ClipboardCopy, ClipboardCopyVariant } from '@patternfly/react-core'; export const ClipboardCopyJSONObject: React.FunctionComponent = () => ( <ClipboardCopy isCode hoverTip="Copy" clickTip="Copied" variant={ClipboardCopyVariant.expansion}> {`{ "menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }} `} </ClipboardCopy> );
jelly/patternfly-react
packages/react-core/src/components/DragDrop/DragDrop.tsx
<filename>packages/react-core/src/components/DragDrop/DragDrop.tsx import * as React from 'react'; interface DraggableItemPosition { /** Parent droppableId */ droppableId: string; /** Index of item in parent Droppable */ index: number; } export const DragDropContext = React.createContext({ onDrag: (_source: DraggableItemPosition) => true as boolean, onDragMove: (_source: DraggableItemPosition, _dest?: DraggableItemPosition) => {}, onDrop: (_source: DraggableItemPosition, _dest?: DraggableItemPosition) => false as boolean }); interface DragDropProps { /** Potentially Droppable and Draggable children */ children?: React.ReactNode; /** Callback for drag event. Return true to allow drag, false to disallow. */ onDrag?: (source: DraggableItemPosition) => boolean; /** Callback on mouse move while dragging. */ onDragMove?: (source: DraggableItemPosition, dest?: DraggableItemPosition) => void; /** Callback for drop event. Return true to allow drop, false to disallow. */ onDrop?: (source: DraggableItemPosition, dest?: DraggableItemPosition) => boolean; } export const DragDrop: React.FunctionComponent<DragDropProps> = ({ children, onDrag = () => true, onDragMove = () => {}, onDrop = () => false }: DragDropProps) => ( <DragDropContext.Provider value={{ onDrag, onDragMove, onDrop }}>{children}</DragDropContext.Provider> ); DragDrop.displayName = 'DragDrop';
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/MultipleFileUploadMain.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/MultipleFileUpload/multiple-file-upload'; import { css } from '@patternfly/react-styles'; import { MultipleFileUploadTitle } from './MultipleFileUploadTitle'; import { MultipleFileUploadButton } from './MultipleFileUploadButton'; import { MultipleFileUploadInfo } from './MultipleFileUploadInfo'; export interface MultipleFileUploadMainProps extends React.HTMLProps<HTMLDivElement> { /** Class to add to outer div */ className?: string; /** Content rendered inside the title icon div */ titleIcon?: React.ReactNode; /** Content rendered inside the title text div */ titleText?: React.ReactNode; /** Content rendered inside the title text separator div */ titleTextSeparator?: React.ReactNode; /** Content rendered inside the info div */ infoText?: React.ReactNode; /** Flag to prevent the upload button from being rendered */ isUploadButtonHidden?: boolean; } export const MultipleFileUploadMain: React.FunctionComponent<MultipleFileUploadMainProps> = ({ className, titleIcon, titleText, titleTextSeparator, infoText, isUploadButtonHidden, ...props }: MultipleFileUploadMainProps) => { const showTitle = !!titleIcon || !!titleText || !!titleTextSeparator; return ( <div className={css(styles.multipleFileUploadMain, className)} {...props}> {showTitle && <MultipleFileUploadTitle icon={titleIcon} text={titleText} textSeparator={titleTextSeparator} />} {isUploadButtonHidden || <MultipleFileUploadButton />} {!!infoText && <MultipleFileUploadInfo>{infoText}</MultipleFileUploadInfo>} </div> ); }; MultipleFileUploadMain.displayName = 'MultipleFileUploadMain';
jelly/patternfly-react
packages/react-core/src/components/Modal/__tests__/ModalContent.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import { ModalContent } from '../ModalContent'; const modalContentProps = { boxId: 'boxId', labelId: 'labelId', descriptorId: 'descriptorId' }; test('Modal Content Test only body', () => { const { asFragment } = render( <ModalContent title="Test Modal Content title" isOpen {...modalContentProps}> This is a ModalBox header </ModalContent> ); expect(asFragment()).toMatchSnapshot(); }); test('Modal Content Test isOpen', () => { const { asFragment } = render( <ModalContent title="Test Modal Content title" isOpen {...modalContentProps}> This is a ModalBox header </ModalContent> ); expect(asFragment()).toMatchSnapshot(); }); test('Modal Content Test description', () => { const { asFragment } = render( <ModalContent title="Test Modal Content title" isOpen description="This is a test description." {...modalContentProps} > This is a ModalBox header </ModalContent> ); expect(asFragment()).toMatchSnapshot(); }); test('Modal Content Test with footer', () => { const { asFragment } = render( <ModalContent title="Test Modal Content title" isOpen actions={['Testing']} {...modalContentProps}> This is a ModalBox header </ModalContent> ); expect(asFragment()).toMatchSnapshot(); }); test('Modal Content test without footer', () => { const { asFragment } = render( <ModalContent title="Test Modal Content title" isOpen {...modalContentProps}> This is a ModalBox header </ModalContent> ); expect(asFragment()).toMatchSnapshot(); }); test('Modal Content Test with onclose', () => { const { asFragment } = render( <ModalContent title="Test Modal Content title" actions={['Testing footer']} variant="large" onClose={() => undefined} isOpen {...modalContentProps} > This is a ModalBox header </ModalContent> ); expect(asFragment()).toMatchSnapshot(); }); test('Modal Test with custom header', () => { const header = <span id="test-custom-header">TEST</span>; const { asFragment } = render( <ModalContent header={header} title="test-custom-header-modal" actions={['Testing footer']} variant="large" onClose={() => undefined} isOpen {...modalContentProps} > This is a ModalBox header </ModalContent> ); expect(asFragment()).toMatchSnapshot(); }); test('Modal Test with custom footer', () => { const footer = <span id="test-custom-footer">TEST</span>; const { asFragment } = render( <ModalContent footer={footer} title="Test Modal Custom Footer" variant="large" onClose={() => undefined} isOpen {...modalContentProps} > This is a ModalBox header </ModalContent> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-topology/src/components/groups/types.ts
<filename>packages/react-topology/src/components/groups/types.ts import { Node } from '../../types'; import * as React from 'react'; import { ShapeProps } from '../nodes'; export interface CollapsibleGroupProps { collapsible?: boolean; collapsedWidth?: number; collapsedHeight?: number; onCollapseChange?: (group: Node, collapsed: boolean) => void; getCollapsedShape?: (node: Node) => React.FunctionComponent<ShapeProps>; collapsedShadowOffset?: number; // defaults to 10 }
jelly/patternfly-react
packages/react-core/src/components/Pagination/OptionsToggle.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/OptionsMenu/options-menu'; import { css } from '@patternfly/react-styles'; import { fillTemplate } from '../../helpers'; import { ToggleTemplateProps } from './ToggleTemplate'; import { DropdownToggle } from '../Dropdown'; export interface OptionsToggleProps extends React.HTMLProps<HTMLDivElement> { /** The type or title of the items being paginated */ itemsTitle?: string; /** Accessible label for the options toggle */ optionsToggle?: string; /** The title of the pagination options menu */ itemsPerPageTitle?: string; /** The first index of the items being paginated */ firstIndex?: number; /** The last index of the items being paginated */ lastIndex?: number; /** The total number of items being paginated */ itemCount?: number; /** Id added to the title of the pagination options menu */ widgetId?: string; /** showToggle */ showToggle?: boolean; /** Event function that fires when user clicks the options menu toggle */ onToggle?: (isOpen: boolean) => void; /** Flag indicating if the options menu dropdown is open or not */ isOpen?: boolean; /** Flag indicating if the options menu is disabled */ isDisabled?: boolean; /** */ parentRef?: HTMLElement; /** This will be shown in pagination toggle span. You can use firstIndex, lastIndex, itemCount, itemsTitle props. */ toggleTemplate?: ((props: ToggleTemplateProps) => React.ReactElement) | string; /** Callback for toggle open on keyboard entry */ onEnter?: () => void; /** Label for the English word "of" */ ofWord?: string; /** Component to be used for wrapping the toggle contents. Use 'button' when you want * all of the toggle text to be clickable. */ perPageComponent?: 'div' | 'button'; } let toggleId = 0; export const OptionsToggle: React.FunctionComponent<OptionsToggleProps> = ({ itemsTitle = 'items', optionsToggle, // eslint-disable-next-line @typescript-eslint/no-unused-vars itemsPerPageTitle = 'Items per page', ofWord = 'of', firstIndex = 0, lastIndex = 0, itemCount, widgetId = '', showToggle = true, // eslint-disable-next-line @typescript-eslint/no-unused-vars onToggle = (_isOpen: boolean) => undefined as any, isOpen = false, isDisabled = false, parentRef = null, toggleTemplate: ToggleTemplate, onEnter = null, perPageComponent = 'div' }: OptionsToggleProps) => { const isDiv = perPageComponent === 'div'; const toggleClasses = css( styles.optionsMenuToggle, isDisabled && styles.modifiers.disabled, styles.modifiers.plain, styles.modifiers.text ); const template = typeof ToggleTemplate === 'string' ? ( fillTemplate(ToggleTemplate, { firstIndex, lastIndex, ofWord, itemCount, itemsTitle }) ) : ( <ToggleTemplate firstIndex={firstIndex} lastIndex={lastIndex} ofWord={ofWord} itemCount={itemCount} itemsTitle={itemsTitle} /> ); const dropdown = showToggle && ( <React.Fragment> {isDiv && <span className={css(styles.optionsMenuToggleText)}>{template}</span>} <DropdownToggle onEnter={onEnter} aria-label={isDiv ? optionsToggle || 'Items per page' : optionsToggle} onToggle={onToggle} isDisabled={isDisabled || (itemCount && itemCount <= 0)} isOpen={isOpen} id={`${widgetId}-toggle-${toggleId++}`} className={isDiv ? styles.optionsMenuToggleButton : toggleClasses} parentRef={parentRef} aria-haspopup="listbox" > {!isDiv && template} </DropdownToggle> </React.Fragment> ); return isDiv ? <div className={toggleClasses}>{dropdown}</div> : dropdown; }; OptionsToggle.displayName = 'OptionsToggle';
jelly/patternfly-react
packages/react-topology/src/components/nodes/labels/LabelBadge.tsx
/* eslint patternfly-react/import-tokens-icons: 0 */ import * as React from 'react'; import { css } from '@patternfly/react-styles'; import { global_palette_blue_50 as defaultBadgeFill } from '@patternfly/react-tokens/dist/js/global_palette_blue_50'; import { global_palette_blue_300 as defaultBadgeBorder } from '@patternfly/react-tokens/dist/js/global_palette_blue_300'; import { global_palette_blue_300 as defaultBadgeTextColor } from '@patternfly/react-tokens/dist/js/global_palette_blue_300'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; import { useSize } from '../../../utils'; import { BadgeLocation } from '../../../types'; interface LabelBadgeProps { className?: string; x: number; y: number; badge?: string; badgeColor?: string; badgeTextColor?: string; badgeBorderColor?: string; badgeClassName?: string; badgeLocation?: BadgeLocation; } const LabelBadge = React.forwardRef<SVGRectElement, LabelBadgeProps>( ({ badge, badgeTextColor, badgeColor, badgeBorderColor, badgeClassName, className, x, y }, iconRef) => { const [textSize, textRef] = useSize([]); const classes = css(styles.topologyNodeLabelBadge, badgeClassName && badgeClassName, className && className); let rect = null; let paddingX = 0; let paddingY = 0; let width = 0; let height = 0; if (textSize) { ({ height, width } = textSize); paddingX = height / 2; paddingY = height / 14; height += paddingY * 2; rect = ( <rect fill={badgeColor || (badgeClassName ? undefined : defaultBadgeFill.value)} stroke={badgeBorderColor || (badgeClassName ? undefined : defaultBadgeBorder.value)} ref={iconRef} x={0} width={width + paddingX * 2} y={0} height={height} rx={height / 2} ry={height / 2} /> ); } return ( <g className={classes} transform={`translate(${x}, ${y})`}> {rect} <text fill={badgeTextColor || badgeClassName ? undefined : defaultBadgeTextColor.value} ref={textRef} x={width / 2 + paddingX} y={height / 2} textAnchor="middle" dy="0.35em" > {badge} </text> </g> ); } ); export default LabelBadge;
jelly/patternfly-react
packages/react-core/src/components/DataList/examples/DataListWidthModifiers.tsx
import React from 'react'; import { DataList, DataListItem, DataListCell, DataListCheck, DataListAction, DataListToggle, DataListContent, DataListItemCells, DataListItemRow, Dropdown, DropdownItem, KebabToggle, DropdownPosition, Text, TextVariants, TextContent } from '@patternfly/react-core'; export const DataListWidthModifiers: React.FunctionComponent = () => { const [show, setShow] = React.useState(true); const [isOpen1, setIsOpen1] = React.useState(false); const [isOpen2, setIsOpen2] = React.useState(false); const onToggle1 = isOpen1 => { setIsOpen1(isOpen1); }; const onSelect1 = () => { setIsOpen1(!isOpen1); }; const onToggle2 = isOpen2 => { setIsOpen2(isOpen2); }; const onSelect2 = () => { setIsOpen2(!isOpen2); }; const previewPlaceholder = { display: 'block', width: '100%', padding: '.25rem .5rem', color: '#004e8a', backgroundColor: '#def3ff', border: '1px solid rgba(0,0,0,.1)', borderRadius: '4px' }; return ( <> <div key="example-1"> <TextContent> <Text component={TextVariants.h4}>Default fitting - example 1</Text> </TextContent> <DataList aria-label="Width modifier data list example 1"> <DataListItem aria-labelledby="width-ex1-item1"> <DataListItemRow> <DataListCheck aria-labelledby="width-ex1-item1" name="width-ex1-item1" /> <DataListItemCells dataListCells={[ <DataListCell key="default"> <div style={previewPlaceholder}> <b id="width-ex1-item1">default</b> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </div> </DataListCell>, <DataListCell key="default2"> <div style={previewPlaceholder}> <b>default</b> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </div> </DataListCell> ]} /> </DataListItemRow> </DataListItem> </DataList> </div> <div key="example-2"> <TextContent> <Text component={TextVariants.h4}>Flex modifiers - example 2</Text> </TextContent> <DataList aria-label="Width modifier data list example 2"> <DataListItem aria-labelledby="width-ex2-item1"> <DataListItemRow> <DataListCheck aria-labelledby="width-ex2-item1" name="width-ex2-item1" /> <DataListItemCells dataListCells={[ <DataListCell width={2} key="width 2"> <div style={previewPlaceholder}> <b id="width-ex2-item1">width 2</b> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.</p> </div> </DataListCell>, <DataListCell width={4} key="width 4"> <div style={previewPlaceholder}> <b>width 4</b> <p>Lorem ipsum dolor sit amet.</p> </div> </DataListCell> ]} /> <DataListAction aria-labelledby="width-ex2-item1 width-ex2-action1" id="width-ex2-action1" aria-label="Actions" isPlainButtonAction > <Dropdown isPlain position={DropdownPosition.right} isOpen={isOpen1} onSelect={onSelect1} toggle={<KebabToggle onToggle={onToggle1} />} dropdownItems={[ <DropdownItem key="link">Link</DropdownItem>, <DropdownItem key="action" component="button"> Action </DropdownItem>, <DropdownItem key="disabled link" isDisabled> Disabled Link </DropdownItem> ]} /> </DataListAction> </DataListItemRow> </DataListItem> </DataList> </div> <div key="example-3"> <TextContent> <Text component={TextVariants.h4}>Flex modifiers - example 3</Text> </TextContent> <DataList aria-label="Width modifier data list example 3"> <DataListItem aria-labelledby="width-ex3-item1" isExpanded={show}> <DataListItemRow> <DataListToggle isExpanded={show} id="width-ex3-toggle1" aria-controls="width-ex3-expand1" onClick={() => setShow(!show)} /> <DataListCheck aria-labelledby="width-ex3-item1" name="width-ex3-item1" /> <DataListItemCells dataListCells={[ <DataListCell width={5} key="width 5"> <div style={previewPlaceholder}> <b id="width-ex3-item1">width 5</b> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </div> </DataListCell>, <DataListCell width={2} key="width 2"> <div style={previewPlaceholder}> <b>width 2</b> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </div> </DataListCell>, <DataListCell key="default"> <div style={previewPlaceholder}>default</div> </DataListCell> ]} /> <DataListAction aria-labelledby="width-ex3-item1 width-ex3-action1" id="width-ex3-action1" aria-label="Actions" isPlainButtonAction > <Dropdown isPlain position={DropdownPosition.right} isOpen={isOpen2} onSelect={onSelect2} toggle={<KebabToggle onToggle={onToggle2} />} dropdownItems={[ <DropdownItem key="link">Link</DropdownItem>, <DropdownItem key="action" component="button"> Action </DropdownItem>, <DropdownItem key="disabled link" isDisabled> Disabled Link </DropdownItem> ]} /> </DataListAction> </DataListItemRow> <DataListContent aria-label="Primary Content Details" id="width-ex3-expand1" isHidden={!show}> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </DataListContent> </DataListItem> </DataList> </div> </> ); };
jelly/patternfly-react
packages/react-catalog-view-extension/src/components/FilterSidePanel/FilterSidePanelCategory.tsx
import * as React from 'react'; import { Button } from '@patternfly/react-core'; import formStyles from '@patternfly/react-styles/css/components/Form/form'; import { css } from '@patternfly/react-styles'; import { childrenToArray } from '../../helpers/util'; export interface FilterSidePanelCategoryProps extends Omit<React.HTMLProps<HTMLFormElement>, 'title'> { /** Children nodes */ children?: React.ReactNode; /** Additional css classes for the Filter Side Panel Category */ className?: string; /** Title for the category */ title?: string | React.ReactNode; /** Number of items (max) to show before adding Show More link button */ maxShowCount?: number; /** Leeway to add to maxShowCount, minimum X for the 'Show X more' */ leeway?: number; /** Flag to show all items (ie. set to true after Show X more link is clicked) */ showAll?: boolean; /** Callback function when the Show/Hide link button is clicked */ onShowAllToggle?: (event: React.SyntheticEvent<HTMLElement>) => void; /** Text for the link to show all items, default 'Show <x> more' */ showText?: string; /** Text for the link to hide overflow items, default 'Show less' */ hideText?: string; } export const FilterSidePanelCategory: React.FunctionComponent<FilterSidePanelCategoryProps> = ({ children = null, className = '', title = null, maxShowCount = 5, leeway = 2, showAll = false, onShowAllToggle = () => null, showText = null, hideText = null, ...props }: FilterSidePanelCategoryProps) => { const classes = css('filter-panel-pf-category', className); const childrenArray = childrenToArray(children); const itemCount = childrenArray.length; const hiddenCount = itemCount - maxShowCount; let shownChildren; let showAllToggle = null; if (hiddenCount <= leeway || showAll) { shownChildren = children; if (hiddenCount > leeway) { showAllToggle = ( <Button variant="link" onClick={onShowAllToggle}> {hideText || 'Show less'} </Button> ); } } else { shownChildren = childrenArray.slice(0, maxShowCount); if (hiddenCount > leeway) { showAllToggle = ( <Button variant="link" isInline onClick={onShowAllToggle}> {showText || `Show ${hiddenCount} more`} </Button> ); } } return ( <form className={classes} {...props}> <fieldset className={`${css(formStyles.formFieldset)} filter-panel-pf-category-items`}> {title && <legend className="filter-panel-pf-category-title">{title}</legend>} {shownChildren} {showAllToggle} </fieldset> </form> ); }; FilterSidePanelCategory.displayName = 'FilterSidePanelCategory'; export default FilterSidePanelCategory;
jelly/patternfly-react
packages/react-core/src/components/Menu/examples/MenuDrilldownSubmenuFunctions.tsx
import React from 'react'; import { Menu, MenuContent, MenuList, MenuItem, Divider, DrilldownMenu } from '@patternfly/react-core'; import StorageDomainIcon from '@patternfly/react-icons/dist/esm/icons/storage-domain-icon'; import CodeBranchIcon from '@patternfly/react-icons/dist/esm/icons/code-branch-icon'; import LayerGroupIcon from '@patternfly/react-icons/dist/esm/icons/layer-group-icon'; import CubeIcon from '@patternfly/react-icons/dist/esm/icons/cube-icon'; export const MenuDrilldownSubmenuFunctions: React.FunctionComponent = () => { const [menuDrilledIn, setMenuDrilledIn] = React.useState<string[]>([]); const [drilldownPath, setDrilldownPath] = React.useState<string[]>([]); const [menuHeights, setMenuHeights] = React.useState<any>({}); const [activeMenu, setActiveMenu] = React.useState<string>('rootMenu'); const drillIn = (fromMenuId: string, toMenuId: string, pathId: string) => { setMenuDrilledIn([...menuDrilledIn, fromMenuId]); setDrilldownPath([...drilldownPath, pathId]); setActiveMenu(toMenuId); }; const drillOut = (toMenuId: string) => { const menuDrilledInSansLast = menuDrilledIn.slice(0, menuDrilledIn.length - 1); const pathSansLast = drilldownPath.slice(0, drilldownPath.length - 1); setMenuDrilledIn(menuDrilledInSansLast); setDrilldownPath(pathSansLast); setActiveMenu(toMenuId); }; const setHeight = (menuId: string, height: number) => { if (menuHeights[menuId] === undefined) { setMenuHeights({ ...menuHeights, [menuId]: height }); } }; return ( <Menu id="rootMenu" containsDrilldown drilldownItemPath={drilldownPath} drilledInMenus={menuDrilledIn} activeMenu={activeMenu} onDrillIn={drillIn} onDrillOut={drillOut} onGetMenuHeight={setHeight} > <MenuContent menuHeight={`${menuHeights[activeMenu]}px`}> <MenuList> <MenuItem itemId="group:start_rollout" direction="down" drilldownMenu={() => ( <DrilldownMenu id="drilldownMenuStart"> <MenuItem itemId="group:start_rollout_breadcrumb" direction="up"> Start rollout </MenuItem> <Divider component="li" /> <MenuItem itemId="group:app_grouping" description="Groups A-C" direction="down" drilldownMenu={() => ( <DrilldownMenu id="drilldownMenuStartGrouping"> <MenuItem itemId="group:app_grouping_breadcrumb" direction="up"> Application grouping </MenuItem> <Divider component="li" /> <MenuItem itemId="group_a">Group A</MenuItem> <MenuItem itemId="group_b">Group B</MenuItem> <MenuItem itemId="group_c">Group C</MenuItem> </DrilldownMenu> )} > Application grouping </MenuItem> <MenuItem itemId="count">Count</MenuItem> <MenuItem itemId="group:labels" direction="down" drilldownMenu={() => ( <DrilldownMenu id="drilldownMenuStartLabels"> <MenuItem itemId="group:labels_breadcrumb" direction="up"> Labels </MenuItem> <Divider component="li" /> <MenuItem itemId="label_1">Label 1</MenuItem> <MenuItem itemId="label_2">Label 2</MenuItem> <MenuItem itemId="label_3">Label 3</MenuItem> </DrilldownMenu> )} > Labels </MenuItem> <MenuItem itemId="annotations">Annotations</MenuItem> </DrilldownMenu> )} > Start rollout </MenuItem> <MenuItem itemId="group:pause_rollout" direction="down" drilldownMenu={() => ( <DrilldownMenu id="drilldownMenuPause"> <MenuItem itemId="group:pause_rollout_breadcrumb" direction="up"> Pause rollouts </MenuItem> <Divider component="li" /> <MenuItem itemId="group:app_grouping" description="Groups A-C" direction="down" drilldownMenu={() => ( <DrilldownMenu id="drilldownMenuGrouping"> <MenuItem itemId="group:app_grouping_breadcrumb" direction="up"> Application grouping </MenuItem> <Divider component="li" /> <MenuItem itemId="group_a">Group A</MenuItem> <MenuItem itemId="group_b">Group B</MenuItem> <MenuItem itemId="group_c">Group C</MenuItem> </DrilldownMenu> )} > Application grouping </MenuItem> <MenuItem itemId="count">Count</MenuItem> <MenuItem itemId="group:labels" direction="down" drilldownMenu={() => ( <DrilldownMenu id="drilldownMenuLabels"> <MenuItem itemId="group:labels_breadcrumb" direction="up"> Labels </MenuItem> <Divider component="li" /> <MenuItem itemId="label_1">Label 1</MenuItem> <MenuItem itemId="label_2">Label 2</MenuItem> <MenuItem itemId="label_3">Label 3</MenuItem> </DrilldownMenu> )} > Labels </MenuItem> <MenuItem itemId="annotations">Annotations</MenuItem> </DrilldownMenu> )} > Pause rollouts </MenuItem> <MenuItem itemId="group:storage" icon={<StorageDomainIcon aria-hidden />} direction="down" drilldownMenu={() => ( <DrilldownMenu id="drilldownMenuStorage"> <MenuItem itemId="group:storage_breadcrumb" icon={<StorageDomainIcon aria-hidden />} direction="up"> Add storage </MenuItem> <Divider component="li" /> <MenuItem icon={<CodeBranchIcon aria-hidden />} itemId="git"> From git </MenuItem> <MenuItem icon={<LayerGroupIcon aria-hidden />} itemId="container"> Container image </MenuItem> <MenuItem icon={<CubeIcon aria-hidden />} itemId="docker"> Docker file </MenuItem> </DrilldownMenu> )} > Add storage </MenuItem> <MenuItem itemId="edit">Edit</MenuItem> <MenuItem itemId="delete_deployment">Delete deployment config</MenuItem> </MenuList> </MenuContent> </Menu> ); };
jelly/patternfly-react
packages/react-topology/src/components/edges/terminals/ConnectorArrowAlt.tsx
import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; import Point from '../../../geom/Point'; import { ConnectDragSource } from '../../../behavior/dnd-types'; import ConnectorArrow from './ConnectorArrow'; interface ConnectorArrowAltProps { startPoint: Point; endPoint: Point; className?: string; isTarget?: boolean; size?: number; dragRef?: ConnectDragSource; } const ConnectorArrowAlt: React.FunctionComponent<ConnectorArrowAltProps> = ({ startPoint, endPoint, className = '', size, dragRef }) => { const classes = css( styles.topologyConnectorArrow, styles.modifiers.altConnectorArrow, className, dragRef && 'pf-m-draggable' ); return ( <ConnectorArrow startPoint={startPoint} endPoint={endPoint} className={classes} size={size} dragRef={dragRef} /> ); }; export default ConnectorArrowAlt;
jelly/patternfly-react
packages/react-core/src/components/Banner/examples/BannerBasic.tsx
<filename>packages/react-core/src/components/Banner/examples/BannerBasic.tsx import React from 'react'; import { Banner } from '@patternfly/react-core'; export const BannerBasic: React.FunctionComponent = () => ( <React.Fragment> <Banner>Default banner</Banner> <br /> <Banner variant="info">Info banner</Banner> <br /> <Banner variant="danger">Danger banner</Banner> <br /> <Banner variant="success">Success banner</Banner> <br /> <Banner variant="warning">Warning banner</Banner> </React.Fragment> );
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/ToggleGroupDemo/ToggleGroupDemo.tsx
import React from 'react'; import { ToggleGroup, ToggleGroupItem, ToggleGroupProps } from '@patternfly/react-core'; import UndoIcon from '@patternfly/react-icons/dist/esm/icons/undo-icon'; import CopyIcon from '@patternfly/react-icons/dist/esm/icons/copy-icon'; import ShareSquareIcon from '@patternfly/react-icons/dist/esm/icons/share-square-icon'; interface ToggleGroupState { isSelected: { first: boolean; second: boolean; third: boolean; fourth: boolean; fifth: boolean; sixth: boolean; seventh: boolean; }; } export class ToggleGroupDemo extends React.Component<ToggleGroupProps, ToggleGroupState> { static displayName = 'ToggleGroupDemo'; constructor(props: ToggleGroupProps) { super(props); this.state = { isSelected: { first: false, second: false, third: false, fourth: false, fifth: false, sixth: false, seventh: false } }; } handleItemClick = (isSelected: boolean, event: any) => { const id = event.currentTarget.id as 'first' | 'second' | 'third' | 'fourth' | 'fifth' | 'sixth' | 'seventh'; this.setState(prevState => { prevState.isSelected[id] = isSelected; return { isSelected: prevState.isSelected }; }); }; render() { const { isSelected } = this.state; return ( <> <ToggleGroup> <ToggleGroupItem text="Option 1" key={0} buttonId="first" isSelected={isSelected.first} onChange={this.handleItemClick} /> <ToggleGroupItem text="Option 2" key={1} buttonId="second" isSelected={isSelected.second} onChange={this.handleItemClick} /> <ToggleGroupItem text="Option 3" key={2} buttonId="disabled" isDisabled /> </ToggleGroup> <ToggleGroup> <ToggleGroupItem icon={<CopyIcon />} key={3} buttonId="third" isSelected={isSelected.third} onChange={this.handleItemClick} aria-label="copy icon button" /> <ToggleGroupItem icon={<UndoIcon />} key={4} buttonId="fourth" isSelected={isSelected.fourth} onChange={this.handleItemClick} aria-label="undo icon button" /> <ToggleGroupItem icon={<ShareSquareIcon />} text="Share" key={5} buttonId="fifth" isSelected={isSelected.fifth} onChange={this.handleItemClick} aria-label="share square icon button" /> </ToggleGroup> <ToggleGroup isCompact> <ToggleGroupItem text="Option 1" key={6} buttonId="sixth" isSelected={isSelected.sixth} onChange={this.handleItemClick} /> <ToggleGroupItem text="Option 2" key={7} buttonId="seventh" isSelected={isSelected.seventh} onChange={this.handleItemClick} /> <ToggleGroupItem icon={<CopyIcon />} text="Option 3" key={8} isDisabled /> </ToggleGroup> </> ); } }
jelly/patternfly-react
packages/react-table/src/components/Table/examples/LegacyTableStripedCustomTr.tsx
import React from 'react'; import { Table, TableHeader, TableBody, TableProps } from '@patternfly/react-table'; import { css } from '@patternfly/react-styles'; interface Repository { name: string; branches: string | null; prs: string | null; workspaces: string; lastCommit: string; } export const LegacyTableStripedCustomTr: React.FunctionComponent = () => { // In real usage, this data would come from some external source like an API via props. const repositories: Repository[] = [ { name: 'one', branches: 'two', prs: 'three', workspaces: 'four', lastCommit: 'five' }, { name: 'one - 2', branches: null, prs: null, workspaces: 'four - 2', lastCommit: 'five - 2' }, { name: 'one - 3', branches: 'two - 3', prs: 'three - 3', workspaces: 'four - 3', lastCommit: 'five - 3' } ]; const columns: TableProps['cells'] = ['Repositories', 'Branches', 'Pull requests', 'Workspaces', 'Last commit']; const rows: TableProps['rows'] = repositories.map(repo => [ repo.name, repo.branches || '', repo.prs || '', repo.workspaces, repo.lastCommit ]); const customRowWrapper: TableProps['rowWrapper'] = ({ trRef, className, rowProps, row: _row, ...props }) => { const isOddRow = rowProps ? !!((rowProps.rowIndex + 1) % 2) : true; return ( <tr {...props} ref={trRef as React.LegacyRef<HTMLTableRowElement>} className={css(className, isOddRow && 'pf-m-striped')} /> ); }; return ( <Table caption="Table with custom row wrapper that stripes odd rows" cells={columns} rows={rows} rowWrapper={customRowWrapper} > <TableHeader /> <TableBody /> </Table> ); };
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/utils/styleUtils.ts
import * as React from 'react'; import { BadgeLocation, EdgeAnimationSpeed, EdgeModel, EdgeStyle, EdgeTerminalType, LabelPosition, NodeModel, NodeShape, NodeStatus } from '@patternfly/react-topology'; import { DataTypes } from '../components/StyleNode'; import { logos } from './logos'; export const ROW_HEIGHT = 140; export const BOTTOM_LABEL_ROW_HEIGHT = 165; export const COLUMN_WIDTH = 100; export const RIGHT_LABEL_COLUMN_WIDTH = 200; export const DEFAULT_NODE_SIZE = 75; export const NODE_STATUSES = [ NodeStatus.danger, NodeStatus.success, NodeStatus.warning, NodeStatus.info, NodeStatus.default ]; export const NODE_SHAPES = [ NodeShape.ellipse, NodeShape.rect, NodeShape.rhombus, NodeShape.trapezoid, NodeShape.hexagon, NodeShape.octagon, NodeShape.stadium ]; export const STATUS_VALUES = Object.values(NodeStatus); export const STATUS_COUNT = STATUS_VALUES.length; export const SHAPE_COUNT = Object.keys(NodeShape).length; export const ICON_STATUS_VALUES = [NodeStatus.success, NodeStatus.warning, NodeStatus.danger]; export const EDGE_STYLES = [ EdgeStyle.dashed, EdgeStyle.dashedMd, EdgeStyle.dotted, EdgeStyle.dashedLg, EdgeStyle.dashedXl, EdgeStyle.solid ]; export const EDGE_STYLE_COUNT = EDGE_STYLES.length; export const EDGE_ANIMATION_SPEEDS = [ EdgeAnimationSpeed.medium, EdgeAnimationSpeed.mediumFast, EdgeAnimationSpeed.mediumSlow, EdgeAnimationSpeed.fast, EdgeAnimationSpeed.none, EdgeAnimationSpeed.slow ]; export const EDGE_ANIMATION_SPEED_COUNT = EDGE_ANIMATION_SPEEDS.length; export const EDGE_TERMINAL_TYPES = [ EdgeTerminalType.directionalAlt, EdgeTerminalType.circle, EdgeTerminalType.square, EdgeTerminalType.cross, EdgeTerminalType.none, EdgeTerminalType.directional ]; export const EDGE_TERMINAL_TYPES_COUNT = EDGE_TERMINAL_TYPES.length; export const AlternateTerminalTypes = [EdgeTerminalType.circle, EdgeTerminalType.square, EdgeTerminalType.cross]; export const createNode = (options: { id: string; type?: string; label?: string; secondaryLabel?: string; labelPosition?: LabelPosition; badge?: string; badgeColor?: string; badgeTextColor?: string; badgeBorderColor?: string; badgeClassName?: string; badgeLocation?: BadgeLocation; row?: number; column?: number; width?: number; height?: number; shape?: NodeShape; status?: NodeStatus; showStatusDecorator?: boolean; statusDecoratorTooltip?: React.ReactNode; showDecorators?: boolean; selected?: boolean; hover?: boolean; x?: number; y?: number; showContextMenu?: boolean; labelIconClass?: string; marginX?: number; truncateLength?: number; setLocation?: boolean; dataType?: DataTypes; }): NodeModel => { const shape = options.shape || NodeShape.ellipse; const width = options.width || DEFAULT_NODE_SIZE; let height = options.height; if (!height) { height = DEFAULT_NODE_SIZE; if (shape === NodeShape.trapezoid) { height *= 0.75; } else if (shape === NodeShape.stadium) { height *= 0.5; } } const nodeModel: NodeModel = { id: options.id, type: options.type || 'node', label: options.label, width, height, shape, status: options.status || NodeStatus.default, labelPosition: options.labelPosition, data: { dataType: 'Default', ...options } }; if (options.setLocation !== false) { nodeModel.x = (options.marginX || 60) + (options.x ?? (options.column - 1) * (options.label && options.labelPosition === LabelPosition.right ? RIGHT_LABEL_COLUMN_WIDTH : COLUMN_WIDTH)); nodeModel.y = 20 + (width - height) / 2 + (options.y ?? (options.row - 1) * (!options.label || options.labelPosition === LabelPosition.right ? ROW_HEIGHT : BOTTOM_LABEL_ROW_HEIGHT)); } return nodeModel; }; export const createEdge = ( sourceId: string, targetId: string, options: { style?: EdgeStyle; animation?: EdgeAnimationSpeed; terminalType?: EdgeTerminalType; terminalStatus?: NodeStatus; tag?: string; tagStatus?: string; } ): EdgeModel => ({ id: `edge-${sourceId}-${targetId}`, type: 'edge', source: sourceId, target: targetId, edgeStyle: options.style, animationSpeed: options.animation, data: { endTerminalType: options.terminalType, endTerminalStatus: options.terminalStatus, tag: options.tag, tagStatus: options.tagStatus } }); const createStatusNodes = ( shape: NodeShape, column: number, statusPerRow = 1, label: string = '', selected?: boolean, hover?: boolean, labelPosition?: LabelPosition, showStatusDecorator?: boolean, statusDecoratorTooltip?: React.ReactNode ): NodeModel[] => (showStatusDecorator ? ICON_STATUS_VALUES : STATUS_VALUES).map((status, index) => createNode({ id: `${shape}-${status}`, shape, label, labelPosition, status, row: Math.ceil((index + 1) / statusPerRow), column: column + ((index * STATUS_COUNT) % statusPerRow) * SHAPE_COUNT, selected, hover, showStatusDecorator, statusDecoratorTooltip }) ); export const createStatusNodeShapes = ( statusPerRow = 1, label: string = '', selected?: boolean, hover?: boolean, labelPosition: LabelPosition = LabelPosition.bottom, showStatusDecorator?: boolean, statusDecoratorTooltip?: React.ReactNode ): NodeModel[] => NODE_SHAPES.reduce((nodes: NodeModel[], shape: string | NodeShape, index) => { nodes.push( ...createStatusNodes( shape as NodeShape, index + 1, statusPerRow, label, selected, hover, labelPosition, showStatusDecorator, statusDecoratorTooltip ) ); return nodes; }, []); export const createBadgeNodes = (options: { row: number; badge?: string; badgeLocation?: BadgeLocation; hover?: boolean; selected?: boolean; showContextMenu?: boolean; showIconClass?: boolean; marginX?: number; }): NodeModel[] => { const nodes: NodeModel[] = []; const columnWidth = COLUMN_WIDTH + (options.badge ? 65 : 0) + (options.showIconClass ? 35 : 0) + (options.showContextMenu ? 24 : 0); nodes.push( createNode({ id: `badged-${options.row}-1`, label: 'Label Bottom', column: 1, labelIconClass: options.showIconClass ? logos.get('icon-java') : undefined, truncateLength: 13, ...options }) ); nodes.push( createNode({ id: `badged-${options.row}-2`, label: 'Label Right', column: 2, shape: NodeShape.rect, x: columnWidth, y: (options.row - 1) * ROW_HEIGHT, labelIconClass: options.showIconClass ? logos.get('icon-mongodb') : undefined, truncateLength: 13, ...options }) ); nodes.push( createNode({ id: `badged-${options.row}-3`, label: 'Long Truncated Node Title', column: 3, shape: NodeShape.rhombus, x: columnWidth * 2, y: (options.row - 1) * BOTTOM_LABEL_ROW_HEIGHT, badgeColor: '#ace12e', badgeTextColor: '#0f280d', badgeBorderColor: '#486b00', labelIconClass: options.showIconClass ? logos.get('icon-nodejs') : undefined, truncateLength: 13, ...options }) ); nodes.push( createNode({ id: `badged-${options.row}-4`, label: 'Long Truncated Node Title', column: 3, shape: NodeShape.trapezoid, x: columnWidth * 3, y: (options.row - 1) * BOTTOM_LABEL_ROW_HEIGHT, badgeColor: '#ace12e', badgeTextColor: '#0f280d', badgeBorderColor: '#486b00', labelIconClass: options.showIconClass ? logos.get('icon-nodejs') : undefined, truncateLength: 13, ...options }) ); nodes.push( createNode({ id: `badged-${options.row}-5`, label: 'Long Truncated Node Title', column: 4, shape: NodeShape.hexagon, x: columnWidth * 4, y: (options.row - 1) * BOTTOM_LABEL_ROW_HEIGHT, badgeColor: '#ace12e', badgeTextColor: '#0f280d', badgeBorderColor: '#486b00', labelIconClass: options.showIconClass ? logos.get('icon-jenkins') : undefined, truncateLength: 13, ...options }) ); nodes.push( createNode({ id: `badged-${options.row}-6`, label: 'Long Truncated Node Title', column: 4, shape: NodeShape.octagon, x: columnWidth * 5, y: (options.row - 1) * BOTTOM_LABEL_ROW_HEIGHT, badgeColor: '#ace12e', badgeTextColor: '#0f280d', badgeBorderColor: '#486b00', labelIconClass: options.showIconClass ? logos.get('icon-jenkins') : undefined, truncateLength: 13, ...options }) ); nodes.push( createNode({ id: `badged-${options.row}-7`, label: 'Label Right', column: 2, shape: NodeShape.stadium, x: columnWidth * 6, y: (options.row - 1) * ROW_HEIGHT, labelIconClass: options.showIconClass ? logos.get('icon-mongodb') : undefined, truncateLength: 13, ...options }) ); return nodes; }; export const createGroupNodes = (groupId = 'group1', x = 0): NodeModel[] => { const nodes: NodeModel[] = []; nodes.push( createNode({ id: `${groupId}-1`, shape: NodeShape.trapezoid, label: 'Node 1', labelPosition: LabelPosition.right, row: 0, column: 0, x: x + 200, y: 50 }) ); nodes.push( createNode({ id: `${groupId}-2`, shape: NodeShape.rect, label: 'Node 2', labelPosition: LabelPosition.right, row: 0, column: 0, x, y: 150 }) ); nodes.push( createNode({ id: `${groupId}-3`, shape: NodeShape.octagon, label: 'Node 3', labelPosition: LabelPosition.right, row: 0, column: 0, x, y: 350 }) ); nodes.push( createNode({ id: `${groupId}-4`, shape: NodeShape.stadium, label: 'Node 4', labelPosition: LabelPosition.right, row: 0, column: 0, x: x + 200, y: 450 }) ); nodes.push( createNode({ id: `${groupId}-5`, shape: NodeShape.hexagon, label: 'Node 5', labelPosition: LabelPosition.right, row: 0, column: 0, x: x + 400, y: 350 }) ); nodes.push( createNode({ id: `${groupId}-6`, shape: NodeShape.rhombus, label: 'Node 6', labelPosition: LabelPosition.right, row: 0, column: 0, x: x + 400, y: 150 }) ); nodes.push( createNode({ id: `${groupId}-7`, shape: NodeShape.ellipse, label: 'Node 7', labelPosition: LabelPosition.right, row: 0, column: 0, x: x + 200, y: 250 }) ); return nodes; }; export const createGroupedGroupNodes = ( groupId: string, x = 0, y = 100, hover: boolean = undefined, selected: boolean = undefined ): NodeModel[] => { const nodes: NodeModel[] = []; nodes.push( createNode({ id: `${groupId}-Grouped-1`, shape: NodeShape.ellipse, label: 'Grouped Node 1', labelPosition: LabelPosition.bottom, row: 0, column: 0, x: x + 75, y, dataType: DataTypes.Alternate }) ); nodes.push( createNode({ id: `${groupId}-Grouped-2`, shape: NodeShape.ellipse, label: 'Grouped Node 2', labelPosition: LabelPosition.bottom, row: 0, column: 0, x: x + 225, y, dataType: DataTypes.Alternate }) ); const groupNode = { id: groupId, type: 'group', label: 'Grouped Group Title', children: nodes.map(n => n.id), group: true, style: { padding: 17 }, data: { badge: 'Label', badgeColor: '#F2F0FC', badgeTextColor: '#5752d1', badgeBorderColor: '#CBC1FF', hover, selected, collapsedWidth: 75, collapsedHeight: 75 } }; return [...nodes, groupNode]; }; export const createUnGroupedGroupNodes = (groupId: string, x = 0, y = 325): NodeModel[] => { const nodes: NodeModel[] = []; nodes.push( createNode({ id: `${groupId}-UnGrouped-A`, shape: NodeShape.ellipse, label: 'Grouped Node A', labelPosition: LabelPosition.bottom, row: 0, column: 0, x, y }) ); nodes.push( createNode({ id: `${groupId}-UnGrouped-B`, shape: NodeShape.ellipse, label: 'Grouped Node B', labelPosition: LabelPosition.bottom, row: 0, column: 0, x: x + 150, y }) ); nodes.push( createNode({ id: `${groupId}-UnGrouped-C`, shape: NodeShape.ellipse, label: 'Grouped Node C', labelPosition: LabelPosition.bottom, row: 0, column: 0, x: x + 300, y }) ); return nodes; };
jelly/patternfly-react
packages/react-topology/src/components/nodes/shapes/Rhombus.tsx
<gh_stars>0 import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; import { PointTuple } from '../../../types'; import { getHullPath, RHOMBUS_CORNER_RADIUS, ShapeProps } from './shapeUtils'; import { useSvgAnchor } from '../../../behavior'; import { useCombineRefs } from '../../../utils'; type RhombusProps = ShapeProps & { cornerRadius?: number; }; const getRhombusPoints = (width: number, height: number, padding: number): PointTuple[] => [ [width / 2, -padding], [width + padding, height / 2], [width / 2, height + padding], [-padding, height / 2] ]; const Rhombus: React.FunctionComponent<RhombusProps> = ({ className = css(styles.topologyNodeBackground), width, height, filter, cornerRadius = RHOMBUS_CORNER_RADIUS, dndDropRef }) => { const anchorRef = useSvgAnchor(); const refs = useCombineRefs(dndDropRef, anchorRef); const points = React.useMemo(() => { const polygonPoints: PointTuple[] = getRhombusPoints(width, height, cornerRadius / 2); return cornerRadius ? getHullPath(getRhombusPoints(width, height, -cornerRadius), cornerRadius) : polygonPoints.map(p => `${p[0]},${p[1]}`).join(' '); }, [cornerRadius, height, width]); return cornerRadius ? ( <path className={className} ref={refs} d={points} filter={filter} /> ) : ( <polygon className={className} ref={refs} points={points} filter={filter} /> ); }; export default Rhombus;
jelly/patternfly-react
packages/react-charts/src/components/ChartLabel/ChartLabel.test.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import { render } from '@testing-library/react'; import { ChartLabel } from './ChartLabel'; Object.values([true, false]).forEach(() => { test('ChartLabel', () => { const { asFragment } = render(<ChartLabel />); expect(asFragment()).toMatchSnapshot(); }); }); test('renders component text', () => { const { asFragment } = render(<ChartLabel text="This is a test" />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-topology/src/components/factories/components/index.ts
export * from './componentUtils';
jelly/patternfly-react
packages/react-core/src/demos/ComposableMenu/examples/ComposableActionsMenu.tsx
import React from 'react'; import { MenuToggle, Menu, MenuList, MenuItem, MenuGroup, MenuItemAction, Popper } from '@patternfly/react-core'; import BarsIcon from '@patternfly/react-icons/dist/esm/icons/bars-icon'; import ClipboardIcon from '@patternfly/react-icons/dist/esm/icons/clipboard-icon'; import CodeBranchIcon from '@patternfly/react-icons/dist/esm/icons/code-branch-icon'; import BellIcon from '@patternfly/react-icons/dist/esm/icons/bell-icon'; export const ComposableActionsMenu: React.FunctionComponent = () => { const [isOpen, setIsOpen] = React.useState<boolean>(false); const [selectedItems, setSelectedItems] = React.useState<number[]>([]); const toggleRef = React.useRef<HTMLButtonElement>(); const menuRef = React.useRef<HTMLDivElement>(); 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)) { setIsOpen(false); } }; React.useEffect(() => { window.addEventListener('keydown', handleMenuKeys); window.addEventListener('click', handleClickOutside); return () => { window.removeEventListener('keydown', handleMenuKeys); window.removeEventListener('click', handleClickOutside); }; }, [isOpen, menuRef]); const onSelect = (ev: React.MouseEvent<Element, MouseEvent>, itemId: number) => { if (selectedItems.includes(itemId)) { setSelectedItems(selectedItems.filter(id => id !== itemId)); } else { setSelectedItems([...selectedItems, itemId]); } }; const onToggleClick = (ev: React.MouseEvent) => { ev.stopPropagation(); // Stop handleClickOutside from handling setTimeout(() => { if (menuRef.current) { const firstElement = menuRef.current.querySelector('li > button:not(:disabled)'); firstElement && (firstElement as HTMLElement).focus(); } }, 0); setIsOpen(!isOpen); }; const toggle = ( <MenuToggle ref={toggleRef} onClick={onToggleClick} isExpanded={isOpen}> {isOpen ? 'Expanded' : 'Collapsed'} </MenuToggle> ); const menu = ( <Menu ref={menuRef} // eslint-disable-next-line no-console onActionClick={(event, itemId, actionId) => console.log(`clicked on ${itemId} - ${actionId}`)} onSelect={onSelect} style={ { '--pf-c-menu--Width': '300px' } as React.CSSProperties } > <MenuGroup label="Actions"> <MenuList> <MenuItem isSelected={selectedItems.includes(0)} actions={ <MenuItemAction icon={<CodeBranchIcon aria-hidden />} actionId="code" // eslint-disable-next-line no-console onClick={() => console.log('clicked on code icon')} aria-label="Code" /> } description="This is a description" itemId={0} > Item 1 </MenuItem> <MenuItem isDisabled isSelected={selectedItems.includes(1)} actions={<MenuItemAction icon={<BellIcon aria-hidden />} actionId="alert" aria-label="Alert" />} description="This is a description" itemId={1} > Item 2 </MenuItem> <MenuItem isSelected={selectedItems.includes(2)} actions={<MenuItemAction icon={<ClipboardIcon aria-hidden />} actionId="copy" aria-label="Copy" />} itemId={2} > Item 3 </MenuItem> <MenuItem isSelected={selectedItems.includes(3)} actions={<MenuItemAction icon={<BarsIcon aria-hidden />} actionId="expand" aria-label="Expand" />} description="This is a description" itemId={3} > Item 4 </MenuItem> </MenuList> </MenuGroup> </Menu> ); return <Popper trigger={toggle} popper={menu} isVisible={isOpen} popperMatchesTriggerWidth={false} />; };
jelly/patternfly-react
packages/react-virtualized-extension/src/components/Virtualized/utils/maxElementSize.ts
const DEFAULT_MAX_ELEMENT_SIZE = 1500000; const CHROME_MAX_ELEMENT_SIZE = 1.67771e7; const isBrowser = () => typeof window !== 'undefined'; const isChrome = () => !!(window as any).chrome && !!(window as any).chrome.webstore; export const getMaxElementSize = (): number => { if (isBrowser()) { if (isChrome()) { return CHROME_MAX_ELEMENT_SIZE; } } return DEFAULT_MAX_ELEMENT_SIZE; };
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/MultipleFileUploadStatus.tsx
<filename>packages/react-core/src/components/MultipleFileUpload/MultipleFileUploadStatus.tsx import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/MultipleFileUpload/multiple-file-upload'; import { css } from '@patternfly/react-styles'; import { ExpandableSection } from '../ExpandableSection'; import InProgressIcon from '@patternfly/react-icons/dist/esm/icons/in-progress-icon'; import CheckCircleIcon from '@patternfly/react-icons/dist/esm/icons/check-circle-icon'; import TimesCircleIcon from '@patternfly/react-icons/dist/esm/icons/times-circle-icon'; export interface MultipleFileUploadStatusProps extends React.HTMLProps<HTMLDivElement> { /** Content rendered inside multi file upload status list */ children?: React.ReactNode; /** Class to add to outer div */ className?: string; /** String to show in the status toggle */ statusToggleText?: string; /** Icon to show in the status toggle */ statusToggleIcon?: 'danger' | 'success' | 'inProgress' | React.ReactNode; } export const MultipleFileUploadStatus: React.FunctionComponent<MultipleFileUploadStatusProps> = ({ children, className, statusToggleText, statusToggleIcon, ...props }: MultipleFileUploadStatusProps) => { const [icon, setIcon] = React.useState<React.ReactNode>(); const [isOpen, setIsOpen] = React.useState(true); React.useEffect(() => { switch (statusToggleIcon) { case 'danger': setIcon(<TimesCircleIcon />); break; case 'success': setIcon(<CheckCircleIcon />); break; case 'inProgress': setIcon(<InProgressIcon />); break; default: setIcon(statusToggleIcon); } }, [statusToggleIcon]); const toggle = ( <div className={styles.multipleFileUploadStatusProgress}> <div className={styles.multipleFileUploadStatusProgressIcon}>{icon}</div> <div className={styles.multipleFileUploadStatusItemProgressText}>{statusToggleText}</div> </div> ); const toggleExpandableSection = () => { setIsOpen(!isOpen); }; return ( <div className={css(styles.multipleFileUploadStatus, className)} {...props}> <ExpandableSection toggleContent={toggle} isExpanded={isOpen} onToggle={toggleExpandableSection}> <ul className="pf-c-multiple-file-upload__status-list">{children}</ul> </ExpandableSection> </div> ); }; MultipleFileUploadStatus.displayName = 'MultipleFileUploadStatus';
jelly/patternfly-react
packages/react-core/src/components/AboutModal/__tests__/AboutModalBox.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import { AboutModalBox } from '../AboutModalBox'; test('AboutModalBox Test', () => { const { asFragment } = render( <AboutModalBox aria-labelledby="id" aria-describedby="id2"> This is a AboutModalBox </AboutModalBox> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/Toolbar/__tests__/ToolbarToggleGroup.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { ToolbarToggleGroup } from '../ToolbarToggleGroup'; import { ToolbarContentContext } from '../ToolbarUtils'; describe('ToolbarToggleGroup', () => { it('should warn on bad props', () => { const myMock = jest.fn() as any; global.console = { error: myMock } as any; render( <ToolbarContentContext.Provider value={{ expandableContentId: 'some-id', expandableContentRef: { current: undefined }, chipContainerRef: { current: undefined } }} > <ToolbarToggleGroup breakpoint={undefined as 'xl'} toggleIcon={null} /> </ToolbarContentContext.Provider> ); expect(myMock).toHaveBeenCalled(); }); });
jelly/patternfly-react
packages/react-core/src/components/Form/__tests__/FormAlert.test.tsx
import { render } from '@testing-library/react'; import { FormAlert } from '../FormAlert'; import React from 'react'; describe('Form Alert component', () => { test('should render form group required variant', () => { const { asFragment } = render(<FormAlert></FormAlert>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/layouts/Grid/__tests__/GridItem.test.tsx
import * as React from 'react'; import { GridItem } from '../GridItem'; import { render } from '@testing-library/react'; import { DeviceSizes } from '../../../styles/sizes'; test('adds span class', () => { const { asFragment } = render(<GridItem span={4} />); expect(asFragment()).toMatchSnapshot(); }); test('adds offset class', () => { const { asFragment } = render(<GridItem offset={4} />); expect(asFragment()).toMatchSnapshot(); }); test('adds row class', () => { const { asFragment } = render(<GridItem rowSpan={4} />); expect(asFragment()).toMatchSnapshot(); }); Object.keys(DeviceSizes).forEach(size => { test(`adds ${size} span class`, () => { const props = { [size]: 4 }; const { asFragment } = render(<GridItem {...props} />); expect(asFragment()).toMatchSnapshot(); }); test(`adds ${size} offset classes`, () => { const props = { [`${size}Offset`]: 1 }; const { asFragment } = render(<GridItem {...props} />); expect(asFragment()).toMatchSnapshot(); }); test(`adds ${size} row classes`, () => { const props = { [`${size}RowSpan`]: 1 }; const { asFragment } = render(<GridItem {...props} />); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/LoginPage/__tests__/LoginMainFooterLinksItem.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import { LoginMainFooterLinksItem } from '../LoginMainFooterLinksItem'; describe('LoginMainFooterLinksItem', () => { test('renders with PatternFly Core styles', () => { const { asFragment } = render(<LoginMainFooterLinksItem href="#" target="" />); expect(asFragment()).toMatchSnapshot(); }); test('className is added to the root element', () => { const { asFragment } = render(<LoginMainFooterLinksItem className="extra-class" />); expect(asFragment()).toMatchSnapshot(); }); test('with custom node', () => { const CustomNode = () => <div>My custom node</div>; const { asFragment } = render( <LoginMainFooterLinksItem> <CustomNode /> </LoginMainFooterLinksItem> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/Divider/examples/DividerOrientationVariousBreakpoints.tsx
<filename>packages/react-core/src/components/Divider/examples/DividerOrientationVariousBreakpoints.tsx<gh_stars>0 import React from 'react'; import { Divider, Flex, FlexItem } from '@patternfly/react-core'; export const DividerOrientationVariousBreakpoints: React.FunctionComponent = () => ( <Flex> <FlexItem>first item</FlexItem> <Divider orientation={{ default: 'vertical', sm: 'horizontal', md: 'vertical', lg: 'horizontal', xl: 'vertical', '2xl': 'horizontal' }} /> <FlexItem>second item</FlexItem> </Flex> );
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/MultipleFileUploadInfo.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/MultipleFileUpload/multiple-file-upload'; import { css } from '@patternfly/react-styles'; export interface MultipleFileUploadInfoProps extends React.HTMLProps<HTMLDivElement> { /** Content rendered inside multiple file upload info */ children?: React.ReactNode; /** Class to add to outer div */ className?: string; } export const MultipleFileUploadInfo: React.FunctionComponent<MultipleFileUploadInfoProps> = ({ className, children, ...props }: MultipleFileUploadInfoProps) => ( <div className={css(styles.multipleFileUploadInfo, className)} {...props}> {children} </div> ); MultipleFileUploadInfo.displayName = 'MultipleFileUploadInfo';
jelly/patternfly-react
packages/react-integration/cypress/integration/labelgroupvertical.spec.ts
describe('Label Group Default Is Open Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/labelgroup-vertical-demo-nav-link'); }); it('Verify label default text', () => { cy.get('.pf-c-label__content') .first() .contains('Lemons'); }); it('Verify labelgroup is vertical', () => { const labelgroup = cy.get('.pf-c-label-group.pf-m-vertical'); labelgroup.should('exist'); }); it('Verify one label shown', () => { cy.get('.pf-c-label-group') .find('.pf-c-label') .not('.pf-m-overflow') .should('have.length', 1); }); it('Verify custom overflow text', () => { const overflowButton = cy.get('.pf-m-overflow'); const overflowLabel = overflowButton.get('.pf-c-label__content'); overflowLabel.contains('Expand labels'); overflowButton.click(); overflowLabel.contains('Collapse labels'); }); it('Verify aria-label works', () => { cy.get('.pf-c-label-group__list').should('have.attr', 'aria-label', 'Vertical fruit labels'); }); });
jelly/patternfly-react
packages/react-core/src/components/Hint/__tests__/Hint.test.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import { render } from '@testing-library/react'; import { Hint } from '../Hint'; import { HintBody } from '../HintBody'; import { HintTitle } from '../HintTitle'; import { HintFooter } from '../HintFooter'; test('simple hint', () => { const { asFragment } = render( <Hint> <HintTitle>Title</HintTitle> <HintBody>Body</HintBody> <HintFooter>Footer</HintFooter> </Hint> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/TreeView/TreeViewListItem.tsx
<reponame>jelly/patternfly-react import React, { useState, useEffect } from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/TreeView/tree-view'; import AngleRightIcon from '@patternfly/react-icons/dist/esm/icons/angle-right-icon'; import { TreeViewDataItem } from './TreeView'; import { Badge } from '../Badge'; import { GenerateId } from '../../helpers/GenerateId/GenerateId'; export interface TreeViewCheckProps extends Partial<React.InputHTMLAttributes<HTMLInputElement>> { checked?: boolean | null; } export interface TreeViewListItemProps { /** Internal content of a tree view item */ name: React.ReactNode; /** Title a tree view item */ title: React.ReactNode; /** ID of a tree view item */ id?: string; /** Flag indicating if the node is expanded, overrides internal state */ isExpanded?: boolean; /** Flag indicating if node is expanded by default */ defaultExpanded?: boolean; /** Child nodes of a tree view item */ children?: React.ReactNode; /** Callback for item selection. Note: calling event.preventDefault() will prevent the node from toggling. */ onSelect?: (event: React.MouseEvent, item: TreeViewDataItem, parent: TreeViewDataItem) => void; /** Callback for item checkbox selection */ onCheck?: (event: React.ChangeEvent, item: TreeViewDataItem, parent: TreeViewDataItem) => void; /** Flag indicating if a tree view item has a checkbox */ hasCheck?: boolean; /** Additional properties of the tree view item checkbox */ checkProps?: TreeViewCheckProps; /** Flag indicating if a tree view item has a badge */ hasBadge?: boolean; /** Optional prop for custom badge */ customBadgeContent?: React.ReactNode; /** Additional properties of the tree view item badge */ badgeProps?: any; /** Flag indicating if the tree view is using a compact variation. */ isCompact?: boolean; /** Active items of tree view */ activeItems?: TreeViewDataItem[]; /** Data structure of tree view item */ itemData?: TreeViewDataItem; /** Parent item of tree view item */ parentItem?: TreeViewDataItem; /** Default icon of a tree view item */ icon?: React.ReactNode; /** Expanded icon of a tree view item */ expandedIcon?: React.ReactNode; /** Action of a tree view item, can be a Button or Dropdown */ action?: React.ReactNode; /** Callback for item comparison function */ compareItems?: (item: TreeViewDataItem, itemToCheck: TreeViewDataItem) => boolean; /** Flag indicating the TreeView should utilize memoization to help render large data sets. Setting this property requires that `activeItems` pass in an array containing every node in the selected item's path. */ useMemo?: boolean; } const TreeViewListItemBase: React.FunctionComponent<TreeViewListItemProps> = ({ name, title, id, isExpanded, defaultExpanded = false, children = null, onSelect, onCheck, hasCheck = false, checkProps = { checked: false }, hasBadge = false, customBadgeContent, badgeProps = { isRead: true }, isCompact, activeItems = [], itemData, parentItem, icon, expandedIcon, action, compareItems, // eslint-disable-next-line @typescript-eslint/no-unused-vars useMemo }: TreeViewListItemProps) => { const [internalIsExpanded, setIsExpanded] = useState(defaultExpanded); useEffect(() => { if (isExpanded !== undefined && isExpanded !== null) { setIsExpanded(isExpanded); } else if (defaultExpanded !== undefined && defaultExpanded !== null) { setIsExpanded(internalIsExpanded || defaultExpanded); } }, [isExpanded, defaultExpanded]); const Component = hasCheck ? 'div' : 'button'; const ToggleComponent = hasCheck ? 'button' : 'div'; const renderToggle = (randomId: string) => ( <ToggleComponent className={css(styles.treeViewNodeToggle)} onClick={() => { if (hasCheck) { setIsExpanded(!internalIsExpanded); } }} {...(hasCheck && { 'aria-labelledby': `label-${randomId}` })} tabIndex={-1} > <span className={css(styles.treeViewNodeToggleIcon)}> <AngleRightIcon aria-hidden="true" /> </span> </ToggleComponent> ); const renderCheck = (randomId: string) => ( <span className={css(styles.treeViewNodeCheck)}> <input type="checkbox" onChange={(evt: React.ChangeEvent) => onCheck && onCheck(evt, itemData, parentItem)} onClick={(evt: React.MouseEvent) => evt.stopPropagation()} ref={elem => elem && (elem.indeterminate = checkProps.checked === null)} {...checkProps} checked={checkProps.checked === null ? false : checkProps.checked} id={randomId} tabIndex={-1} /> </span> ); const iconRendered = ( <span className={css(styles.treeViewNodeIcon)}> {!internalIsExpanded && icon} {internalIsExpanded && (expandedIcon || icon)} </span> ); const renderNodeContent = (randomId: string) => { const content = ( <> {isCompact && title && <span className={css(styles.treeViewNodeTitle)}>{title}</span>} {hasCheck ? ( <label className={css(styles.treeViewNodeText)} htmlFor={randomId} id={`label-${randomId}`}> {name} </label> ) : ( <span className={css(styles.treeViewNodeText)}>{name}</span> )} </> ); return isCompact ? <div className={css(styles.treeViewNodeContent)}>{content}</div> : content; }; const badgeRendered = ( <> {hasBadge && children && ( <span className={css(styles.treeViewNodeCount)}> <Badge {...badgeProps}> {customBadgeContent ? customBadgeContent : (children as React.ReactElement).props.data.length} </Badge> </span> )} {hasBadge && !children && customBadgeContent !== undefined && ( <span className={css(styles.treeViewNodeCount)}> <Badge {...badgeProps}>{customBadgeContent}</Badge> </span> )} </> ); return ( <li id={id} className={css(styles.treeViewListItem, internalIsExpanded && styles.modifiers.expanded)} {...(internalIsExpanded && { 'aria-expanded': 'true' })} role="treeitem" tabIndex={-1} > <div className={css(styles.treeViewContent)}> <GenerateId prefix="checkbox-id"> {randomId => ( <Component className={css( styles.treeViewNode, !children && activeItems && activeItems.length > 0 && activeItems.some(item => compareItems && item && compareItems(item, itemData)) ? styles.modifiers.current : '' )} onClick={(evt: React.MouseEvent) => { if (!hasCheck) { onSelect && onSelect(evt, itemData, parentItem); if (children && evt.isDefaultPrevented() !== true) { setIsExpanded(!internalIsExpanded); } } }} tabIndex={-1} > <div className={css(styles.treeViewNodeContainer)}> {children && renderToggle(randomId)} {hasCheck && renderCheck(randomId)} {icon && iconRendered} {renderNodeContent(randomId)} {badgeRendered} </div> </Component> )} </GenerateId> {action && <div className={css(styles.treeViewAction)}>{action}</div>} </div> {internalIsExpanded && children} </li> ); }; export const TreeViewListItem = React.memo(TreeViewListItemBase, (prevProps, nextProps) => { if (!nextProps.useMemo) { return false; } const prevIncludes = prevProps.activeItems && prevProps.activeItems.length > 0 && prevProps.activeItems.some( item => prevProps.compareItems && item && prevProps.compareItems(item, prevProps.itemData) ); const nextIncludes = nextProps.activeItems && nextProps.activeItems.length > 0 && nextProps.activeItems.some( item => nextProps.compareItems && item && nextProps.compareItems(item, nextProps.itemData) ); if (prevIncludes || nextIncludes) { return false; } if ( prevProps.name !== nextProps.name || prevProps.title !== nextProps.title || prevProps.id !== nextProps.id || prevProps.isExpanded !== nextProps.isExpanded || prevProps.defaultExpanded !== nextProps.defaultExpanded || prevProps.onSelect !== nextProps.onSelect || prevProps.onCheck !== nextProps.onCheck || prevProps.hasCheck !== nextProps.hasCheck || prevProps.checkProps !== nextProps.checkProps || prevProps.hasBadge !== nextProps.hasBadge || prevProps.customBadgeContent !== nextProps.customBadgeContent || prevProps.badgeProps !== nextProps.badgeProps || prevProps.isCompact !== nextProps.isCompact || prevProps.icon !== nextProps.icon || prevProps.expandedIcon !== nextProps.expandedIcon || prevProps.action !== nextProps.action || prevProps.parentItem !== nextProps.parentItem || prevProps.itemData !== nextProps.itemData ) { return false; } return true; }); TreeViewListItem.displayName = 'TreeViewListItem';
jelly/patternfly-react
packages/react-topology/src/components/nodes/shapes/Stadium.tsx
import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; import * as React from 'react'; import { useSvgAnchor } from '../../../behavior'; import { getHullPath, ShapeProps } from './shapeUtils'; import { PointTuple } from '../../../types'; import { useCombineRefs } from '../../../utils'; const getStadiumPoints = (width: number, radius: number): PointTuple[] => [ [radius, radius], [width - radius, radius], [width - radius, radius], [radius, radius] ]; const Stadium: React.FunctionComponent<ShapeProps> = ({ className = css(styles.topologyNodeBackground), width, height, filter, dndDropRef }) => { const anchorRef = useSvgAnchor(); const refs = useCombineRefs(dndDropRef, anchorRef); const points = React.useMemo(() => getHullPath(getStadiumPoints(width, height / 2), height / 2), [height, width]); return <path className={className} ref={refs} d={points} filter={filter} />; }; export default Stadium;
jelly/patternfly-react
packages/react-core/src/components/Card/examples/CardWithOnlyBodySection.tsx
<reponame>jelly/patternfly-react<gh_stars>0 import React from 'react'; import { Card, CardBody } from '@patternfly/react-core'; export const CardWithOnlyBodySection: React.FunctionComponent = () => ( <Card> <CardBody>Body</CardBody> </Card> );
jelly/patternfly-react
packages/react-table/src/components/Table/utils/decorators/info.tsx
import * as React from 'react'; import { ThInfoType } from '../../base/types'; import { HeaderCellInfoWrapper } from '../../HeaderCellInfoWrapper'; import { IFormatterValueType, ITransform } from '../../TableTypes'; import styles from '@patternfly/react-styles/css/components/Table/table'; export const info = ({ tooltip, tooltipProps, popover, popoverProps, className, ariaLabel }: ThInfoType) => { const infoObj: ITransform = (value: IFormatterValueType) => ({ className: styles.modifiers.help, children: tooltip ? ( <HeaderCellInfoWrapper variant="tooltip" info={tooltip} tooltipProps={tooltipProps} ariaLabel={ariaLabel} className={className} > {value} </HeaderCellInfoWrapper> ) : ( <HeaderCellInfoWrapper variant="popover" info={popover} popoverProps={popoverProps} ariaLabel={ariaLabel} className={className} > {value} </HeaderCellInfoWrapper> ) }); return infoObj; };
jelly/patternfly-react
packages/react-core/src/demos/examples/Tabs/NestedUnindentedTabs.tsx
import React from 'react'; import { Card, CardHeader, CardBody, Grid, GridItem, PageSection, Tabs, Tab, TabContent, TabContentBody, TabTitleText, Title, Text, TextContent, TitleSizes } from '@patternfly/react-core'; import DashboardWrapper from '../DashboardWrapper'; export const NestedUnindentedTabs: React.FunctionComponent = () => { const [activeTabKey, setActiveTabKey] = React.useState(1); const [activeNestedTabKey, setActiveNestedTabKey] = React.useState(10); // Toggle currently active tab const handleTabClick = (tabIndex: number) => setActiveTabKey(tabIndex); // Toggle currently active nested tab const handleNestedTabClick = (tabIndex: number) => setActiveNestedTabKey(tabIndex); const tabContent = ( <Grid hasGutter> <GridItem> <CardHeader> <Title headingLevel="h1" size={TitleSizes['2xl']}> Get started with Red Hat Enterprise Linux </Title> </CardHeader> </GridItem> <GridItem> <Tabs activeKey={activeNestedTabKey} isSecondary onSelect={(_event, tabIndex) => handleNestedTabClick(Number(tabIndex))} id="nested-tabs-example-nested-tabs-list" > <Tab eventKey={10} title={<TabTitleText>x86 architecture</TabTitleText>} tabContentId={`tabContent${10}`} /> <Tab eventKey={11} title={<TabTitleText>Additional Architectures</TabTitleText>} tabContentId={`tabContent${11}`} /> </Tabs> </GridItem> <GridItem> <TabContent key={10} eventKey={10} id={`tabContent${10}`} activeKey={activeNestedTabKey} hidden={10 !== activeNestedTabKey} > <TabContentBody> <Grid hasGutter> <GridItem> <TextContent> <Text>To perform a standard x86_64 installation using the GUI, you'll need to:</Text> </TextContent> </GridItem> <Grid md={6} xl2={3} hasGutter> <GridItem> <Card isFullHeight> <CardHeader>Check system requirements</CardHeader> <CardBody> Your physical or virtual machine should meet the <a href="#">system requirement</a>. </CardBody> </Card> </GridItem> <GridItem> <Card isFullHeight> <CardHeader>Download an installation ISO image</CardHeader> <CardBody> {' '} <a href="#">Download</a> the binary DVD ISO. </CardBody> </Card> </GridItem> <GridItem> <Card isFullHeight> <CardHeader>Create a bootable installation media</CardHeader> <CardBody> {' '} <a href="#">Create</a> a bootable installation media, for example a USB flash drive. </CardBody> </Card> </GridItem> <GridItem> <Card isFullHeight> <CardHeader>Install and register your system</CardHeader> <CardBody> Boot the installation, register your system, attach RHEL subscriptions, and install RHEL from the Red Hat Content Delivery Network (CDN) using the GUI. </CardBody> </Card> </GridItem> </Grid> </Grid> </TabContentBody> </TabContent> <TabContent key={11} eventKey={11} id={`tabContent${11}`} activeKey={activeNestedTabKey} hidden={11 !== activeNestedTabKey} > <TabContentBody>Additional architectures panel</TabContentBody> </TabContent> <TabContent key={12} eventKey={12} id={`tabContent${12}`} activeKey={activeNestedTabKey} hidden={12 !== activeNestedTabKey} > <TabContentBody>Operators panel</TabContentBody> </TabContent> <TabContent key={13} eventKey={13} id={`tabContent${13}`} activeKey={activeNestedTabKey} hidden={13 !== activeNestedTabKey} > <TabContentBody>Virtualization panel</TabContentBody> </TabContent> </GridItem> </Grid> ); return ( <DashboardWrapper hasPageTemplateTitle> <PageSection type="tabs" isWidthLimited variant="light"> <Tabs isBox activeKey={activeTabKey} onSelect={(_event, tabIndex) => handleTabClick(Number(tabIndex))} usePageInsets id="nested-tabs-example-tabs-list" > <Tab eventKey={0} title={<TabTitleText>What's new</TabTitleText>} tabContentId={`tabContent${0}`} /> <Tab eventKey={1} title={<TabTitleText>Get started</TabTitleText>} tabContentId={`tabContent${1}`} /> <Tab eventKey={2} title={<TabTitleText>Knowledge</TabTitleText>} tabContentId={`tabContent${2}`} /> <Tab eventKey={3} title={<TabTitleText>Support</TabTitleText>} tabContentId={`tabContent${3}`} /> </Tabs> </PageSection> <PageSection variant="light"> <TabContent key={0} eventKey={0} id={`tabContent${0}`} activeKey={activeTabKey} hidden={0 !== activeTabKey}> <TabContentBody>What's new panel</TabContentBody> </TabContent> <TabContent key={1} eventKey={1} id={`tabContent${1}`} activeKey={activeTabKey} hidden={1 !== activeTabKey}> <TabContentBody>{tabContent}</TabContentBody> </TabContent> <TabContent key={2} eventKey={2} id={`tabContent${2}`} activeKey={activeTabKey} hidden={2 !== activeTabKey}> <TabContentBody>Knowledge panel</TabContentBody> </TabContent> <TabContent key={3} eventKey={3} id={`tabContent${3}`} activeKey={activeTabKey} hidden={3 !== activeTabKey}> <TabContentBody>Support Panel</TabContentBody> </TabContent> </PageSection> </DashboardWrapper> ); };
jelly/patternfly-react
packages/react-topology/src/components/nodes/labels/LabelActionIcon.tsx
<filename>packages/react-topology/src/components/nodes/labels/LabelActionIcon.tsx import * as React from 'react'; import { useSize } from '../../../utils'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; interface LabelActionIconProps { className?: string; icon: React.ReactElement; onClick: (e: React.MouseEvent) => void; iconOffsetX?: number; iconOffsetY?: number; x: number; y: number; height: number; paddingX: number; paddingY: number; } const LabelActionIcon = React.forwardRef<SVGRectElement, LabelActionIconProps>( ({ icon, onClick, className, x, y, paddingX, height, iconOffsetX = 0, iconOffsetY = 0 }, actionRef) => { const [iconSize, iconRef] = useSize([icon, paddingX]); const iconWidth = iconSize?.width ?? 0; const iconHeight = iconSize?.height ?? 0; const iconY = (height - iconHeight) / 2; const classes = css(styles.topologyNodeActionIcon, className); const handleClick = (e: React.MouseEvent) => { if (onClick) { e.stopPropagation(); onClick(e); } }; return ( <g className={classes} onClick={handleClick}> {iconSize && ( <rect ref={actionRef} className={css(styles.topologyNodeActionIconBackground)} x={x} y={y} width={iconWidth + paddingX * 2} height={height} /> )} <g className={css(styles.topologyNodeActionIconIcon)} transform={`translate(${x + paddingX + iconOffsetX}, ${y + iconY + iconOffsetY})`} ref={iconRef} > {icon} </g> </g> ); } ); export default LabelActionIcon;
jelly/patternfly-react
packages/react-table/src/components/Table/examples/LegacyTableCellWidth.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { Table, TableHeader, TableBody, classNames, cellWidth, Visibility, TableProps } from '@patternfly/react-table'; interface Repository { name: string; branches: string; prs: string; workspaces: string; lastCommit: string; } export const LegacyTableCellWidth: React.FunctionComponent = () => { // In real usage, this data would come from some external source like an API via props. const repositories: Repository[] = [ { name: 'one - 1', branches: 'two - 1 (visible only on md)', prs: 'three - 1 (hidden only on md)', workspaces: 'four - 1 (hidden on xs)', lastCommit: 'five - 1' }, { name: 'one - 2', branches: 'two - 2 (visible only on md)', prs: 'three - 2 (hidden only on md)', workspaces: 'four - 2 (hidden on xs)', lastCommit: 'five - 2' } ]; const columns: TableProps['cells'] = [ { title: 'Header cell', transforms: [cellWidth(10)] }, { title: 'Branches (visible only on md and 2Xl)', columnTransforms: [ classNames(Visibility.hidden, Visibility.visibleOnMd, Visibility.hiddenOnLg, Visibility.visibleOn2Xl) ] }, { title: 'Pull requests (hidden only on md)', columnTransforms: [classNames(Visibility.hiddenOnMd, Visibility.visibleOnLg)] }, { title: 'Workspaces (hidden on xs)', columnTransforms: [classNames(Visibility.hidden, Visibility.visibleOnSm)] }, { title: 'Last commit', transforms: [cellWidth(30)] } ]; const rows: TableProps['rows'] = repositories.map(repo => [ repo.name, repo.branches, repo.prs, repo.workspaces, repo.lastCommit ]); return ( <Table aria-label="Table with width and breakpoint visibility modifiers" cells={columns} rows={rows}> <TableHeader /> <TableBody /> </Table> ); };
jelly/patternfly-react
packages/react-core/src/components/BackToTop/__tests__/BackToTop.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { BackToTop } from '../BackToTop'; describe('BackToTop', () => { test('verify basic', () => { const { asFragment } = render(<BackToTop />); expect(asFragment()).toMatchSnapshot(); }); test('verify custom class', () => { const { asFragment } = render(<BackToTop className="custom-css">test</BackToTop>); expect(asFragment()).toMatchSnapshot(); }); test('verify always show', () => { const { asFragment } = render(<BackToTop isAlwaysVisible>test</BackToTop>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-code-editor/src/components/CodeEditor/CodeEditorUtils.ts
<filename>packages/react-code-editor/src/components/CodeEditor/CodeEditorUtils.ts import * as React from 'react'; interface CodeEditorContext { code: string; } export const CodeEditorContext = React.createContext<CodeEditorContext>(null);
jelly/patternfly-react
packages/react-core/src/components/AlertGroup/examples/AlertGroupAsync.tsx
<filename>packages/react-core/src/components/AlertGroup/examples/AlertGroupAsync.tsx import React from 'react'; import { Alert, AlertProps, AlertGroup, AlertActionCloseButton, AlertVariant, InputGroup, useInterval } from '@patternfly/react-core'; export const AlertGroupAsync: React.FunctionComponent = () => { const [alerts, setAlerts] = React.useState<Partial<AlertProps>[]>([]); const [isRunning, setIsRunning] = React.useState(false); const btnClasses = ['pf-c-button', 'pf-m-secondary'].join(' '); const getUniqueId = () => new Date().getTime(); const addAlert = () => { setAlerts(prevAlerts => [ ...prevAlerts, { title: `Async notification ${prevAlerts.length + 1} was added to the queue.`, variant: 'danger', key: getUniqueId() } ]); }; const removeAlert = (key: React.Key) => { setAlerts(prevAlerts => [...prevAlerts.filter(alert => alert.key !== key)]); }; const startAsyncAlerts = () => { setIsRunning(true); }; const stopAsyncAlerts = () => { setIsRunning(false); }; useInterval(addAlert, isRunning ? 4500 : null); return ( <React.Fragment> <InputGroup style={{ marginBottom: '16px' }}> <button onClick={startAsyncAlerts} type="button" className={btnClasses}> Start async alerts </button> <button onClick={stopAsyncAlerts} type="button" className={btnClasses}> Stop async alerts </button> </InputGroup> <AlertGroup isToast isLiveRegion aria-live="assertive"> {alerts.map(({ title, variant, key }) => ( <Alert variant={AlertVariant[variant]} title={title} key={key} actionClose={ <AlertActionCloseButton title={title as string} variantLabel={`${variant} alert`} onClose={() => removeAlert(key)} /> } /> ))} </AlertGroup> </React.Fragment> ); };
jelly/patternfly-react
packages/react-topology/src/behavior/usePolygonAnchor.tsx
<filename>packages/react-topology/src/behavior/usePolygonAnchor.tsx import * as React from 'react'; import { runInAction } from 'mobx'; import { isNode, AnchorEnd, PointTuple, Node } from '../types'; import ElementContext from '../utils/ElementContext'; import PolygonAnchor from '../anchors/PolygonAnchor'; export const usePolygonAnchor = (points: PointTuple[], end: AnchorEnd = AnchorEnd.both, type: string = ''): void => { const element = React.useContext(ElementContext); if (!isNode(element)) { throw new Error('usePolygonAnchor must be used within the scope of a Node'); } React.useEffect(() => { runInAction(() => { if (points) { const anchor = new PolygonAnchor(element); anchor.setPoints(points); element.setAnchor(anchor, end, type); } }); }, [points, end, type, element]); }; export interface WithPolygonAnchorProps { setAnchorPoints: (points: PointTuple[]) => void; } export const withPolygonAnchor = <P extends {} = {}>( getPoints: (element: Node) => PointTuple[], end?: AnchorEnd, type?: string ) => (WrappedComponent: React.ComponentType<P>) => { const element = React.useContext(ElementContext); const Component: React.FunctionComponent<P> = props => { usePolygonAnchor(getPoints(element as Node), end, type); return <WrappedComponent {...props} />; }; Component.displayName = `withPolygonAnchor(${WrappedComponent.displayName || WrappedComponent.name})`; return Component; };
jelly/patternfly-react
packages/react-topology/src/components/groups/index.ts
<filename>packages/react-topology/src/components/groups/index.ts export * from './types'; export { default as DefaultGroup } from './DefaultGroup';
jelly/patternfly-react
packages/react-topology/src/behavior/useDragNode.tsx
import * as React from 'react'; import { action } from 'mobx'; import { observer } from 'mobx-react'; import ElementContext from '../utils/ElementContext'; import { Controller, EventListener, isNode, Node } from '../types'; import { useDndDrag, WithDndDragProps, Modifiers } from './useDndDrag'; import { DragSourceSpec, DragEvent, ConnectDragSource, DragObjectWithType, DragSpecOperationType, DragOperationWithType, DragSourceMonitor } from './dnd-types'; import { useDndManager } from './useDndManager'; export const DRAG_NODE_EVENT = 'drag_node'; export const DRAG_NODE_START_EVENT = `${DRAG_NODE_EVENT}_start`; export const DRAG_NODE_END_EVENT = `${DRAG_NODE_EVENT}_end`; export type DragNodeEventListener = EventListener<[Node, DragEvent, DragOperationWithType]>; export const DRAG_MOVE_OPERATION = 'move.useDragNode'; const defaultOperation = { [Modifiers.DEFAULT]: { type: DRAG_MOVE_OPERATION } }; export const useDragNode = < DragObject extends DragObjectWithType = DragObjectWithType, DropResult = any, CollectedProps extends {} = {}, Props extends {} = {} >( spec?: Omit< DragSourceSpec<DragObject, DragSpecOperationType<DragOperationWithType>, DropResult, CollectedProps, Props>, 'item' > & { item?: DragObject; }, props?: Props ): [CollectedProps, ConnectDragSource] => { const element = React.useContext(ElementContext); if (!isNode(element)) { throw new Error('useDragNode must be used within the scope of a Node'); } const elementRef = React.useRef(element); elementRef.current = element; const dndManager = useDndManager(); return useDndDrag( React.useMemo(() => { const sourceSpec: DragSourceSpec<any, any, any, any, Props> = { item: (spec && spec.item) || { type: '#useDragNode#' }, operation: (monitor: DragSourceMonitor, p: Props) => { if (spec) { const operation = typeof spec.operation === 'function' ? spec.operation(monitor, p) : spec.operation; if (typeof operation === 'object' && Object.keys(operation).length > 0) { return { ...defaultOperation, ...operation }; } } return defaultOperation; }, begin: (monitor, p) => { elementRef.current.raise(); if (elementRef.current.isGroup()) { elementRef.current.getChildren().forEach(c => { c.raise(); }); } const result = spec && spec.begin && spec.begin(monitor, p); elementRef.current .getController() .fireEvent(DRAG_NODE_START_EVENT, elementRef.current, monitor.getDragEvent(), monitor.getOperation()); return result || elementRef.current; }, drag: (event, monitor, p) => { const { dx, dy } = event; /** * @param e */ function moveElement(e: Node) { let moved = true; if (e.isGroup()) { const nodeChildren = e.getChildren().filter(isNode); if (nodeChildren.length) { moved = false; nodeChildren.forEach(moveElement); } } if (moved) { e.setPosition( e .getPosition() .clone() .translate(dx, dy) ); } } moveElement(elementRef.current); spec && spec.drag && spec.drag(event, monitor, p); elementRef.current .getController() .fireEvent(DRAG_NODE_EVENT, elementRef.current, event, monitor.getOperation()); }, canDrag: spec ? spec.canDrag : undefined, end: async (dropResult, monitor, p) => { // FIXME: Get the controller up front due it issues with model updates during dnd operations let controller: Controller; try { controller = elementRef.current.getController(); } catch (e) { return; } if (spec && spec.end) { try { await spec.end(dropResult, monitor, p); } catch { dndManager.cancel(); } } action(() => { controller.fireEvent( DRAG_NODE_END_EVENT, elementRef.current, monitor.getDragEvent(), monitor.getOperation() ); })(); }, collect: spec ? spec.collect : undefined, canCancel: spec ? spec.canCancel : true }; return sourceSpec; }, [spec, dndManager]), props ); }; export interface WithDragNodeProps { dragNodeRef?: WithDndDragProps['dndDragRef']; } export const withDragNode = < DragObject extends DragObjectWithType = DragObjectWithType, DropResult = any, CollectedProps extends {} = {}, Props extends {} = {} >( spec?: Omit< DragSourceSpec<DragObject, DragSpecOperationType<DragOperationWithType>, DropResult, CollectedProps, Props>, 'item' > & { item?: DragObject; } ) => <P extends WithDragNodeProps & CollectedProps & Props>(WrappedComponent: React.ComponentType<P>) => { const Component: React.FunctionComponent<Omit<P, keyof WithDragNodeProps>> = props => { // TODO fix cast to any const [dragNodeProps, dragNodeRef] = useDragNode(spec, props as any); return <WrappedComponent {...(props as any)} dragNodeRef={dragNodeRef} {...dragNodeProps} />; }; Component.displayName = `withDragNode(${WrappedComponent.displayName || WrappedComponent.name})`; return observer(Component); };
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/dom-utils/instanceOf.ts
<filename>packages/react-core/src/helpers/Popper/thirdparty/popper-core/dom-utils/instanceOf.ts // @ts-nocheck import getWindow from './getWindow'; /* :: declare function isElement(node: mixed): boolean %checks(node instanceof Element); */ /** * @param node */ function isElement(node) { const OwnElement = getWindow(node).Element; return node instanceof OwnElement || node instanceof Element; } /* :: declare function isHTMLElement(node: mixed): boolean %checks(node instanceof HTMLElement); */ /** * @param node */ function isHTMLElement(node) { const OwnElement = getWindow(node).HTMLElement; return node instanceof OwnElement || node instanceof HTMLElement; } export { isElement, isHTMLElement };
jelly/patternfly-react
packages/react-core/src/components/Popover/PopoverHeaderText.tsx
<filename>packages/react-core/src/components/Popover/PopoverHeaderText.tsx<gh_stars>100-1000 import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Popover/popover'; export interface PopoverHeaderTextProps extends React.HTMLProps<HTMLDivElement> { /** Content of the header text */ children: React.ReactNode; /** Class to be applied to the header text */ className?: string; } export const PopoverHeaderText: React.FunctionComponent<PopoverHeaderTextProps> = ({ children, className, ...props }: PopoverHeaderTextProps) => ( <span className={css(styles.popoverTitleText, className)} {...props}> {children} </span> ); PopoverHeaderText.displayName = 'PopoverHeaderText';
jelly/patternfly-react
packages/react-core/src/components/ClipboardCopy/__tests__/ClipboardCopyButton.test.tsx
<filename>packages/react-core/src/components/ClipboardCopy/__tests__/ClipboardCopyButton.test.tsx import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { ClipboardCopyButton } from '../ClipboardCopyButton'; const props = { id: 'my-id', textId: 'my-text-id', className: 'fancy-copy-button', onClick: jest.fn(), exitDelay: 1000, entryDelay: 2000, maxWidth: '500px', position: 'right' as 'right', 'aria-label': 'click this button to copy text' }; test('copy button render', () => { const { asFragment } = render(<ClipboardCopyButton {...props}>Copy Me</ClipboardCopyButton>); expect(asFragment()).toMatchSnapshot(); }); test('copy button onClick', () => { const onclick = jest.fn(); render( <ClipboardCopyButton {...props} onClick={onclick}> Copy to Clipboard </ClipboardCopyButton> ); userEvent.click(screen.getByRole('button')); expect(onclick).toHaveBeenCalled(); });
jelly/patternfly-react
packages/react-integration/cypress/integration/tableeditablecompoundexpandable.spec.ts
describe('Table Compound Expandable Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/table-editable-compound-expandable-demo-nav-link'); }); it('Test expandable/collapsible', () => { cy.get('button.pf-c-table__button') .first() .click(); cy.get('button.pf-c-table__button') .first() .click(); // should not have changed the url cy.url().should('eq', 'http://localhost:3000/table-editable-compound-expandable-demo-nav-link'); }); });
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/utils/debounce.ts
<filename>packages/react-core/src/helpers/Popper/thirdparty/popper-core/utils/debounce.ts<gh_stars>100-1000 // @ts-nocheck /** * @param fn */ export default function debounce<T>(fn: Function): () => Promise<T> { let pending; return () => { if (!pending) { pending = new Promise<T>(resolve => { Promise.resolve().then(() => { pending = undefined; resolve(fn()); }); }); } return pending; }; }
jelly/patternfly-react
packages/react-core/src/components/ContextSelector/__tests__/ContextSelectorFooter.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { ContextSelectorFooter } from '../ContextSelectorFooter'; test('Renders ContextSelectorFooter', () => { const { asFragment } = render(<ContextSelectorFooter>testing text</ContextSelectorFooter>); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/NotificationDrawer/__tests__/NotificationDrawerGroup.test.tsx
<gh_stars>0 import React from 'react'; import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import { NotificationDrawerGroup } from '../NotificationDrawerGroup'; describe('NotificationDrawerGroup', () => { test('renders with PatternFly Core styles', () => { const { asFragment } = render(<NotificationDrawerGroup count={2} isExpanded={false} title="Critical Alerts" />); expect(asFragment()).toMatchSnapshot(); }); test('className is added to the root element', () => { render( <NotificationDrawerGroup count={2} isExpanded={false} title="Critical Alerts" className="extra-class" data-testid="test-id" /> ); expect(screen.getByTestId('test-id')).toHaveClass('extra-class'); }); test('drawer group with isExpanded applied ', () => { const { asFragment } = render(<NotificationDrawerGroup count={2} isExpanded title="Critical Alerts" />); expect(asFragment()).toMatchSnapshot(); }); test('drawer group with isRead applied ', () => { const { asFragment } = render( <NotificationDrawerGroup count={2} isExpanded={false} isRead={true} title="Critical Alerts" /> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/DataList/examples/DataListDraggable.tsx
<filename>packages/react-core/src/components/DataList/examples/DataListDraggable.tsx import React from 'react'; import { DataList, DataListItem, DataListCell, DataListItemRow, DataListCheck, DataListControl, DataListDragButton, DataListItemCells, DragDrop, Draggable, Droppable } from '@patternfly/react-core'; interface ItemType { id: string; content: string; } const getItems = (count: number) => Array.from({ length: count }, (_, idx) => idx).map(idx => ({ id: `item-${idx}`, content: `item ${idx} `.repeat(idx === 4 ? 20 : 1) })); const reorder = (list: ItemType[], startIndex: number, endIndex: number) => { const result = list; const [removed] = result.splice(startIndex, 1); result.splice(endIndex, 0, removed); return result; }; export const DataListDraggable: React.FunctionComponent = () => { const [items, setItems] = React.useState(getItems(10)); const [liveText, setLiveText] = React.useState(''); function onDrag(source) { setLiveText(`Started dragging ${items[source.index].content}`); // Return true to allow drag return true; } function onDragMove(source, dest) { const newText = dest ? `Move ${items[source.index].content} to ${items[dest.index].content}` : 'Invalid drop zone'; if (newText !== liveText) { setLiveText(newText); } } function onDrop(source, dest) { if (dest) { const newItems = reorder(items, source.index, dest.index); setItems(newItems); setLiveText('Dragging finished.'); return true; // Signal that this is a valid drop and not to animate the item returning home. } else { setLiveText('Dragging cancelled. List unchanged.'); } } return ( <DragDrop onDrag={onDrag} onDragMove={onDragMove} onDrop={onDrop}> <Droppable hasNoWrapper> <DataList aria-label="draggable data list example" isCompact> {items.map(({ id, content }) => ( <Draggable key={id} hasNoWrapper> <DataListItem aria-labelledby={id} ref={React.createRef()}> <DataListItemRow> <DataListControl> <DataListDragButton aria-label="Reorder" aria-labelledby={id} aria-describedby="Press space or enter to begin dragging, and use the arrow keys to navigate up or down. Press enter to confirm the drag, or any other key to cancel the drag operation." aria-pressed="false" /> <DataListCheck aria-labelledby={id} name={id} otherControls /> </DataListControl> <DataListItemCells dataListCells={[ <DataListCell key={id}> <span id={id}>{content}</span> </DataListCell> ]} /> </DataListItemRow> </DataListItem> </Draggable> ))} </DataList> </Droppable> <div className="pf-screen-reader" aria-live="assertive"> {liveText} </div> </DragDrop> ); };
jelly/patternfly-react
packages/react-topology/src/components/groups/DefaultGroupExpanded.tsx
import * as React from 'react'; import { observer } from 'mobx-react'; import { polygonHull } from 'd3-polygon'; import * as _ from 'lodash'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; import CollapseIcon from '@patternfly/react-icons/dist/esm/icons/compress-alt-icon'; import NodeLabel from '../nodes/labels/NodeLabel'; import { Layer } from '../layers'; import { GROUPS_LAYER } from '../../const'; import { hullPath, maxPadding, useCombineRefs, useHover } from '../../utils'; import { BadgeLocation, isGraph, Node, NodeShape, NodeStyle, PointTuple } from '../../types'; import { useDragNode, useSvgAnchor, WithContextMenuProps, WithDndDropProps, WithDragNodeProps, WithSelectionProps } from '../../behavior'; import { CollapsibleGroupProps } from './types'; type DefaultGroupExpandedProps = { className?: string; element: Node; droppable?: boolean; canDrop?: boolean; dropTarget?: boolean; dragging?: boolean; hover?: boolean; label?: string; // Defaults to element.getLabel() secondaryLabel?: string; showLabel?: boolean; // Defaults to true truncateLength?: number; // Defaults to 13 badge?: string; badgeColor?: string; badgeTextColor?: string; badgeBorderColor?: string; badgeClassName?: string; badgeLocation?: BadgeLocation; labelIconClass?: string; // Icon to show in label labelIcon?: string; labelIconPadding?: number; } & Partial<CollapsibleGroupProps & WithDragNodeProps & WithSelectionProps & WithDndDropProps & WithContextMenuProps>; type PointWithSize = [number, number, number]; // Return the point whose Y is the largest value. // If multiple points are found, compute the center X between them // export for testing only export function computeLabelLocation(points: PointWithSize[]): PointWithSize { let lowPoints: PointWithSize[]; const threshold = 5; _.forEach(points, p => { const delta = !lowPoints ? Infinity : Math.round(p[1]) - Math.round(lowPoints[0][1]); if (delta > threshold) { lowPoints = [p]; } else if (Math.abs(delta) <= threshold) { lowPoints.push(p); } }); return [ (_.minBy(lowPoints, p => p[0])[0] + _.maxBy(lowPoints, p => p[0])[0]) / 2, lowPoints[0][1], // use the max size value _.maxBy(lowPoints, p => p[2])[2] ]; } const DefaultGroupExpanded: React.FunctionComponent<DefaultGroupExpandedProps> = ({ className, element, collapsible, selected, onSelect, hover, label, secondaryLabel, showLabel = true, truncateLength, dndDropRef, droppable, canDrop, dropTarget, onContextMenu, contextMenuOpen, dragging, dragNodeRef, badge, badgeColor, badgeTextColor, badgeBorderColor, badgeClassName, badgeLocation, labelIconClass, labelIcon, labelIconPadding, onCollapseChange }) => { const [hovered, hoverRef] = useHover(); const [labelHover, labelHoverRef] = useHover(); const dragLabelRef = useDragNode()[1]; const refs = useCombineRefs<SVGPathElement>(hoverRef, dragNodeRef); const isHover = hover !== undefined ? hover : hovered; const anchorRef = useSvgAnchor(); const outlineRef = useCombineRefs(dndDropRef, anchorRef); const labelLocation = React.useRef<PointWithSize>(); const pathRef = React.useRef<string>(); let parent = element.getParent(); let altGroup = false; while (!isGraph(parent)) { altGroup = !altGroup; parent = parent.getParent(); } // cast to number and coerce const padding = maxPadding(element.getStyle<NodeStyle>().padding ?? 17); const hullPadding = (point: PointWithSize | PointTuple) => (point[2] || 0) + padding; if (!droppable || !pathRef.current || !labelLocation.current) { const children = element.getNodes().filter(c => c.isVisible()); if (children.length === 0) { return null; } const points: (PointWithSize | PointTuple)[] = []; _.forEach(children, c => { if (c.getNodeShape() === NodeShape.circle) { const bounds = c.getBounds(); const { width, height } = bounds; const { x, y } = bounds.getCenter(); const radius = Math.max(width, height) / 2; points.push([x, y, radius] as PointWithSize); } else { // add all 4 corners const { width, height, x, y } = c.getBounds(); points.push([x, y, 0] as PointWithSize); points.push([x + width, y, 0] as PointWithSize); points.push([x, y + height, 0] as PointWithSize); points.push([x + width, y + height, 0] as PointWithSize); } }); const hullPoints: (PointWithSize | PointTuple)[] = points.length > 2 ? polygonHull(points as PointTuple[]) : (points as PointTuple[]); if (!hullPoints) { return null; } // change the box only when not dragging pathRef.current = hullPath(hullPoints as PointTuple[], hullPadding); // Compute the location of the group label. labelLocation.current = computeLabelLocation(hullPoints as PointWithSize[]); } const groupClassName = css( styles.topologyGroup, className, altGroup && 'pf-m-alt-group', canDrop && 'pf-m-highlight', dragging && 'pf-m-dragging', selected && 'pf-m-selected' ); const innerGroupClassName = css( styles.topologyGroup, className, altGroup && 'pf-m-alt-group', canDrop && 'pf-m-highlight', dragging && 'pf-m-dragging', selected && 'pf-m-selected', (isHover || labelHover) && 'pf-m-hover', canDrop && dropTarget && 'pf-m-drop-target' ); return ( <g ref={labelHoverRef} onContextMenu={onContextMenu} onClick={onSelect} className={groupClassName}> <Layer id={GROUPS_LAYER}> <g ref={refs} onContextMenu={onContextMenu} onClick={onSelect} className={innerGroupClassName}> <path ref={outlineRef} className={styles.topologyGroupBackground} d={pathRef.current} /> </g> </Layer> {showLabel && ( <NodeLabel className={styles.topologyGroupLabel} x={labelLocation.current[0]} y={labelLocation.current[1] + hullPadding(labelLocation.current) + 24} paddingX={8} paddingY={5} dragRef={dragNodeRef ? dragLabelRef : undefined} status={element.getNodeStatus()} secondaryLabel={secondaryLabel} truncateLength={truncateLength} badge={badge} badgeColor={badgeColor} badgeTextColor={badgeTextColor} badgeBorderColor={badgeBorderColor} badgeClassName={badgeClassName} badgeLocation={badgeLocation} labelIconClass={labelIconClass} labelIcon={labelIcon} labelIconPadding={labelIconPadding} onContextMenu={onContextMenu} contextMenuOpen={contextMenuOpen} hover={isHover || labelHover} actionIcon={collapsible ? <CollapseIcon /> : undefined} onActionIconClick={() => onCollapseChange(element, true)} > {label || element.getLabel()} </NodeLabel> )} </g> ); }; export default observer(DefaultGroupExpanded);
jelly/patternfly-react
packages/react-core/src/components/ContextSelector/ContextSelectorFooter.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/ContextSelector/context-selector'; export interface ContextSelectorFooterProps extends React.HTMLProps<HTMLDivElement> { /** Content rendered inside the ContextSelectorFooter */ children?: React.ReactNode; /** Additional classes added to the ContextSelectorFooter */ className?: string; } export const ContextSelectorFooter: React.FunctionComponent<ContextSelectorFooterProps> = ({ children = null, className = '', ...props }: ContextSelectorFooterProps) => ( <div {...props} className={css(styles.contextSelectorMenuFooter, className)}> {children} </div> ); ContextSelectorFooter.displayName = 'ContextSelectorFooter';
jelly/patternfly-react
packages/react-core/src/components/Divider/examples/DividerVerticalFlexInsetVariousBreakpoints.tsx
<reponame>jelly/patternfly-react<filename>packages/react-core/src/components/Divider/examples/DividerVerticalFlexInsetVariousBreakpoints.tsx import React from 'react'; import { Divider, Flex, FlexItem } from '@patternfly/react-core'; export const DividerVerticalFlexInsetVariousBreakpoints: React.FunctionComponent = () => ( <Flex> <FlexItem>first item</FlexItem> <Divider orientation={{ default: 'vertical' }} inset={{ default: 'insetMd', md: 'insetNone', lg: 'insetSm', xl: 'insetXs' }} /> <FlexItem>second item</FlexItem> </Flex> );
jelly/patternfly-react
packages/react-core/src/components/Toolbar/__tests__/ToolbarItem.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { ToolbarItem } from '../ToolbarItem'; describe('ToolbarItem', () => { it('should map width breakpoints', () => { const widths = { default: '100px', sm: '80px', md: '150px', lg: '200px', xl: '250px', '2xl': '300px' }; const { asFragment } = render(<ToolbarItem widths={widths}>Test</ToolbarItem>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/demos/examples/Tabs/TabsAndTable.tsx
<gh_stars>0 /* eslint-disable no-console */ import React from 'react'; import { Button, Divider, Drawer, DrawerContent, DrawerContentBody, DrawerPanelContent, DrawerHead, DrawerActions, DrawerCloseButton, DrawerPanelBody, Dropdown, Flex, FlexItem, KebabToggle, Label, LabelGroup, OptionsMenu, OptionsMenuToggle, OverflowMenu, OverflowMenuContent, OverflowMenuControl, OverflowMenuGroup, OverflowMenuItem, PageSection, PageSectionVariants, Pagination, PaginationVariant, Progress, ProgressSize, Select, SelectVariant, Tabs, Tab, TabContent, TabContentBody, TabTitleText, Title, Toolbar, ToolbarItem, ToolbarContent, ToolbarToggleGroup } from '@patternfly/react-core'; import { TableComposable, Thead, Tbody, Tr, Th, Td, IAction, ActionsColumn, CustomActionsToggleProps } from '@patternfly/react-table'; import DashboardWrapper from '../DashboardWrapper'; import CodeIcon from '@patternfly/react-icons/dist/esm/icons/code-icon'; import CodeBranchIcon from '@patternfly/react-icons/dist/esm/icons/code-branch-icon'; import CubeIcon from '@patternfly/react-icons/dist/esm/icons/cube-icon'; import FilterIcon from '@patternfly/react-icons/dist/esm/icons/filter-icon'; import SortAmountDownIcon from '@patternfly/react-icons/dist/esm/icons/sort-amount-down-icon'; interface Repository { name: string; branches: number | null; prs: number | null; workspaces: number; lastCommit: string; } export const TablesAndTabs = () => { // tab properties const [activeTabKey, setActiveTabKey] = React.useState<number>(0); // Toggle currently active tab const handleTabClick = (tabIndex: number) => { setActiveTabKey(tabIndex); }; // secondary tab properties const [secondaryActiveTabKey, setSecondaryActiveTabKey] = React.useState<number>(10); const handleSecondaryTabClick = (tabIndex: number) => { setSecondaryActiveTabKey(tabIndex); }; // drawer properties const [isExpanded, setIsExpanded] = React.useState<boolean>(false); // table properties // In real usage, this data would come from some external source like an API via props. const repositories: Repository[] = [ { name: 'Node 1', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' }, { name: 'Node 2', branches: 8, prs: 30, workspaces: 2, lastCommit: '2 days ago' }, { name: 'Node 3', branches: 12, prs: 48, workspaces: 13, lastCommit: '30 days ago' }, { name: 'Node 4', branches: 3, prs: 8, workspaces: 20, lastCommit: '8 days ago' }, { name: 'Node 5', branches: 33, prs: 21, workspaces: 2, lastCommit: '26 days ago' } ]; const columnNames = { name: 'Repositories', branches: 'Branches', prs: 'Pull requests', workspaces: 'Workspaces', lastCommit: 'Last commit' }; const [selectedRepoNames, setSelectedRepoNames] = React.useState<string[]>([]); const setRepoSelected = (event: React.FormEvent<HTMLInputElement>, repo: Repository, isSelecting = true) => { setSelectedRepoNames(prevSelected => { const otherSelectedRepoNames = prevSelected.filter(r => r !== repo.name); return isSelecting ? [...otherSelectedRepoNames, repo.name] : otherSelectedRepoNames; }); event.stopPropagation(); }; const onSelectAll = (isSelecting = true) => setSelectedRepoNames(isSelecting ? repositories.map(r => r.name) : []); const allRowsSelected = selectedRepoNames.length === repositories.length; const isRepoSelected = (repo: Repository) => selectedRepoNames.includes(repo.name); const [rowClicked, setRowClicked] = React.useState<string>(null); const isRowClicked = (repo: Repository) => rowClicked === repo.name; const defaultActions: IAction[] = [ { title: 'Some action', onClick: event => { event.stopPropagation(); console.log('clicked on Some action'); } }, { title: <a href="https://www.patternfly.org">Link action</a>, onClick: event => { event.stopPropagation(); console.log('clicked on Link action'); } }, { isSeparator: true }, { title: 'Third action', onClick: event => { event.stopPropagation(); console.log('clicked on Third action'); } } ]; const customActionsToggle = (props: CustomActionsToggleProps) => ( <KebabToggle isDisabled={props.isDisabled} onToggle={(value, event) => { props.onToggle(value); event.stopPropagation(); }} /> ); const toolbar = ( <Toolbar id="page-layout-table-column-management-action-toolbar-top" usePageInsets> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="xl"> <ToolbarItem> <Select onToggle={() => {}} variant={SelectVariant.single} aria-label="Select Input" placeholderText="Name" /> </ToolbarItem> </ToolbarToggleGroup> <ToolbarItem> <OptionsMenu id="page-layout-table-column-management-action-toolbar-top-options-menu-toggle" isPlain menuItems={[]} toggle={ <OptionsMenuToggle toggleTemplate={<SortAmountDownIcon aria-hidden="true" />} aria-label="Sort" hideCaret /> } /> </ToolbarItem> <OverflowMenu breakpoint="md"> <OverflowMenuContent className="pf-u-display-none pf-u-display-block-on-lg"> <OverflowMenuGroup groupType="button" isPersistent> <OverflowMenuItem isPersistent> <Button variant="primary">Generate</Button> </OverflowMenuItem> <OverflowMenuItem isPersistent> <Button variant="secondary">Deploy</Button> </OverflowMenuItem> </OverflowMenuGroup> </OverflowMenuContent> <OverflowMenuControl hasAdditionalOptions> <Dropdown onSelect={() => {}} toggle={<KebabToggle onToggle={() => {}} />} isOpen={false} isPlain dropdownItems={[]} /> </OverflowMenuControl> </OverflowMenu> <ToolbarItem variant="pagination"> <Pagination itemCount={36} widgetId="pagination-options-menu-bottom" page={1} variant={PaginationVariant.top} isCompact /> </ToolbarItem> </ToolbarContent> </Toolbar> ); const tableComposable = ( <TableComposable aria-label="`Composable` table"> <Thead noWrap> <Tr> <Th select={{ onSelect: (_event, isSelecting) => onSelectAll(isSelecting), isSelected: allRowsSelected }} /> <Th>{columnNames.name}</Th> <Th>{columnNames.branches}</Th> <Th>{columnNames.prs}</Th> <Th>{columnNames.workspaces}</Th> <Th>{columnNames.lastCommit}</Th> </Tr> </Thead> <Tbody> {repositories.map((repo, rowIndex) => ( <Tr key={repo.name} onRowClick={event => { if ((event.target as HTMLInputElement).type !== 'checkbox') { setRowClicked(rowClicked === repo.name ? null : repo.name); setIsExpanded(!isRowClicked(repo)); } }} isHoverable isRowSelected={repo.name === rowClicked} > <Td key={`${rowIndex}_0`} select={{ rowIndex, onSelect: (event, isSelected) => setRepoSelected(event, repo, isSelected), isSelected: isRepoSelected(repo) }} /> <Td dataLabel={columnNames.name}> {repo.name} <div> <a href="#">siemur/test-space</a> </div> </Td> <Td dataLabel={columnNames.branches}> <Flex> <FlexItem>{repo.branches}</FlexItem> <FlexItem> <CodeBranchIcon key="icon" /> </FlexItem> </Flex> </Td> <Td dataLabel={columnNames.prs}> <Flex> <FlexItem>{repo.prs}</FlexItem> <FlexItem> <CodeIcon key="icon" /> </FlexItem> </Flex> </Td> <Td dataLabel={columnNames.workspaces}> <Flex> <FlexItem>{repo.workspaces}</FlexItem> <FlexItem> <CubeIcon key="icon" /> </FlexItem> </Flex> </Td> <Td dataLabel={columnNames.lastCommit}>{repo.lastCommit}</Td> <Td key={`${rowIndex}_5`}> <ActionsColumn items={defaultActions} actionsToggle={customActionsToggle} /> </Td> </Tr> ))} </Tbody> </TableComposable> ); const panelContent = ( <DrawerPanelContent widths={{ default: 'width_33', xl: 'width_33' }}> <DrawerHead> <DrawerActions> <DrawerCloseButton onClick={() => { setRowClicked(null); setIsExpanded(false); }} /> </DrawerActions> <Flex spaceItems={{ default: 'spaceItemsSm' }} direction={{ default: 'column' }}> <FlexItem> <Title headingLevel="h2" size="lg"> {rowClicked} </Title> </FlexItem> <FlexItem> <a href="#">siemur/test-space</a> </FlexItem> </Flex> </DrawerHead> <DrawerPanelBody hasNoPadding> <Tabs activeKey={secondaryActiveTabKey} onSelect={(_event, tabIndex) => handleSecondaryTabClick(Number(tabIndex))} isBox isFilled id="tabs-tables-secondary-tabs" > <Tab eventKey={10} title={<TabTitleText>Overview</TabTitleText>} tabContentId={`tabContent${10}`} /> <Tab eventKey={11} title={<TabTitleText>Activity</TabTitleText>} tabContentId={`tabContent${11}`} /> </Tabs> </DrawerPanelBody> <DrawerPanelBody> <TabContent key={10} eventKey={10} id={`tabContent${10}`} activeKey={secondaryActiveTabKey} hidden={10 !== secondaryActiveTabKey} > <TabContentBody> <Flex direction={{ default: 'column' }} spaceItems={{ default: 'spaceItemsLg' }}> <FlexItem> <p> The content of the drawer really is up to you. It could have form fields, definition lists, text lists, labels, charts, progress bars, etc. Spacing recommendation is 24px margins. You can put tabs in here, and can also make the drawer scrollable. </p> </FlexItem> <FlexItem> <Progress value={33} title="Capacity" size={ProgressSize.sm} /> </FlexItem> <FlexItem> <Progress value={66} title="Modules" size={ProgressSize.sm} /> </FlexItem> <Flex direction={{ default: 'column' }}> <FlexItem> <Title headingLevel="h3">Tags</Title> </FlexItem> <FlexItem> <LabelGroup> {[1, 2, 3, 4, 5].map(labelNumber => ( <Label variant="outline" key={`label-${labelNumber}`}>{`Tag ${labelNumber}`}</Label> ))} </LabelGroup> </FlexItem> </Flex> </Flex> </TabContentBody> </TabContent> <TabContent key={11} eventKey={11} id={`tabContent${11}`} activeKey={secondaryActiveTabKey} hidden={11 !== secondaryActiveTabKey} > <TabContentBody>Activity panel</TabContentBody> </TabContent> </DrawerPanelBody> </DrawerPanelContent> ); const tabContent = ( <Drawer isExpanded={isExpanded} isInline> <DrawerContent panelContent={panelContent}> <DrawerContentBody> {toolbar} <Divider /> {tableComposable} <Pagination id="page-layout-table-column-management-action-toolbar-bottom" itemCount={36} widgetId="pagination-options-menu-bottom" page={1} variant={PaginationVariant.bottom} /> </DrawerContentBody> </DrawerContent> </Drawer> ); return ( <DashboardWrapper> <React.Fragment> <PageSection variant={PageSectionVariants.light}> <Title headingLevel="h1" size="2xl"> Nodes </Title> </PageSection> <PageSection type="tabs" variant={PageSectionVariants.light} padding={{ default: 'noPadding' }}> <Tabs activeKey={activeTabKey} onSelect={(_event, tabIndex) => handleTabClick(Number(tabIndex))} usePageInsets id="tabs-table-tabs-list" > <Tab eventKey={0} title={<TabTitleText>Nodes</TabTitleText>} tabContentId={`tabContent${0}`} /> <Tab eventKey={1} title={<TabTitleText>Node connectors</TabTitleText>} tabContentId={`tabContent${1}`} /> </Tabs> </PageSection> <PageSection variant={PageSectionVariants.light} padding={{ default: 'noPadding' }}> <TabContent key={0} eventKey={0} id={`tabContent${0}`} activeKey={activeTabKey} hidden={0 !== activeTabKey}> <TabContentBody>{tabContent}</TabContentBody> </TabContent> <TabContent key={1} eventKey={1} id={`tabContent${1}`} activeKey={activeTabKey} hidden={1 !== activeTabKey}> <TabContentBody>Node connectors panel</TabContentBody> </TabContent> </PageSection> </React.Fragment> </DashboardWrapper> ); };
jelly/patternfly-react
packages/react-core/src/components/SkipToContent/__tests__/SkipToContent.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import { SkipToContent } from '../SkipToContent'; const props = {}; test('Verify Skip To Content', () => { const { asFragment } = render(<SkipToContent href="#main-content" {...props} />); // Add a useful assertion here. expect(asFragment()).toMatchSnapshot(); }); test('Verify Skip To Content if forced to display', () => { const { asFragment } = render(<SkipToContent href="#main-content" {...props} show />); // Add a useful assertion here. expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-topology/src/anchors/EllipseAnchor.ts
<gh_stars>100-1000 import Point from '../geom/Point'; import { getEllipseAnchorPoint } from '../utils/anchor-utils'; import AbstractAnchor from './AbstractAnchor'; export default class EllipseAnchor extends AbstractAnchor { getLocation(reference: Point): Point { const r = this.owner.getBounds(); if (r.isEmpty()) { return r.getCenter(); } const offset2x = this.offset * 2; return getEllipseAnchorPoint(r.getCenter(), r.width + offset2x, r.height + offset2x, reference); } }
jelly/patternfly-react
packages/react-core/src/components/Label/__tests__/Label.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Label } from '../Label'; const labelColors = ['blue', 'cyan', 'green', 'orange', 'purple', 'red', 'grey']; describe('Label', () => { test('renders', () => { const { asFragment } = render(<Label>Something</Label>); expect(asFragment()).toMatchSnapshot(); }); test('renders with outline variant', () => { const { asFragment } = render(<Label variant="outline">Something</Label>); expect(asFragment()).toMatchSnapshot(); }); test('renders with isCompact', () => { const { asFragment } = render(<Label isCompact>Something</Label>); expect(asFragment()).toMatchSnapshot(); }); test('label with href', () => { const { asFragment } = render(<Label href="#">Something</Label>); expect(asFragment()).toMatchSnapshot(); }); test('label with href with outline variant', () => { const { asFragment } = render( <Label href="#" variant="outline"> Something </Label> ); expect(asFragment()).toMatchSnapshot(); }); test('label with close button', () => { const { asFragment } = render(<Label onClose={jest.fn()}>Something</Label>); expect(asFragment()).toMatchSnapshot(); }); test('label with close button and outline variant', () => { const { asFragment } = render( <Label onClose={jest.fn()} variant="outline"> Something </Label> ); expect(asFragment()).toMatchSnapshot(); }); labelColors.forEach((color: string) => test(`label with ${color} color`, () => { const { asFragment } = render(<Label color={color as any}>Something</Label>); expect(asFragment()).toMatchSnapshot(); }) ); labelColors.forEach((color: string) => test(`label with ${color} color with outline variant`, () => { const { asFragment } = render( <Label color={color as any} variant="outline"> Something </Label> ); expect(asFragment()).toMatchSnapshot(); }) ); test('label with additional class name', () => { const { asFragment } = render(<Label className="klass1">Something</Label>); expect(asFragment()).toMatchSnapshot(); }); test('label with additional class name and props', () => { const { asFragment } = render( <Label className="class-1" id="label-1" data-label-name="something"> Something </Label> ); expect(asFragment()).toMatchSnapshot(); }); test('label with truncation', () => { const { asFragment } = render( <Label isTruncated>Something very very very very very long that should be truncated</Label> ); expect(asFragment()).toMatchSnapshot(); }); test('editable label', () => { const { asFragment } = render( <Label onClose={jest.fn()} onEditCancel={jest.fn()} onEditComplete={jest.fn()} isEditable> Something </Label> ); const button = screen.getByRole('button', { name: 'Something' }); expect(button).toBeInTheDocument(); expect(asFragment()).toMatchSnapshot(); userEvent.click(button); expect(screen.queryByRole('button', { name: 'Something' })).toBeNull(); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/dom-utils/getWindowScrollBarX.ts
// @ts-nocheck import getBoundingClientRect from './getBoundingClientRect'; import getDocumentElement from './getDocumentElement'; import getWindowScroll from './getWindowScroll'; /** * @param element */ export default function getWindowScrollBarX(element: Element): number { // If <html> has a CSS width greater than the viewport, then this will be // incorrect for RTL. // Popper 1 is broken in this case and never had a bug report so let's assume // it's not an issue. I don't think anyone ever specifies width on <html> // anyway. // Browsers where the left scrollbar doesn't cause an issue report `0` for // this (e.g. Edge 2019, IE11, Safari) return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; }
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/DrawerDemo/DrawerResizeDemo.tsx
import React from 'react'; import { Button, Drawer, DrawerPanelContent, DrawerContent, DrawerContentBody, DrawerSection, DrawerHead, DrawerActions, DrawerCloseButton, DrawerProps } from '@patternfly/react-core'; export interface DrawerResizeDemoState { isExpanded: boolean; panelWidth: number; } export class DrawerResizeDemo extends React.Component<DrawerProps, DrawerResizeDemoState> { static displayName = 'DrawerDemo'; constructor(props: DrawerProps) { super(props); this.state = { isExpanded: false, panelWidth: 200 }; } drawerRef = React.createRef<HTMLButtonElement>(); onExpand = () => { this.drawerRef.current && this.drawerRef.current.focus(); }; // eslint-disable-next-line @typescript-eslint/no-unused-vars onResize = (newWidth: number, id: string) => { this.setState( { panelWidth: newWidth }, // eslint-disable-next-line no-console () => console.log(`${id} has new width: ${newWidth}`) ); }; onClick = () => { const isExpanded = !this.state.isExpanded; this.setState({ isExpanded }); }; onCloseClick = () => { this.setState({ isExpanded: false }); }; render() { const { isExpanded } = this.state; const panelContent = ( <DrawerPanelContent isResizable increment={50} onResize={this.onResize} id="panel" defaultSize={'200px'}> <DrawerHead> <span ref={this.drawerRef} tabIndex={isExpanded ? 0 : -1}> drawer-panel </span> <DrawerActions> <DrawerCloseButton onClick={this.onCloseClick} /> </DrawerActions> </DrawerHead> </DrawerPanelContent> ); const drawerContent = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pretium est a porttitor vehicula. Quisque vel commodo urna. Morbi mattis rutrum ante, id vehicula ex accumsan ut. Morbi viverra, eros vel porttitor facilisis, eros purus aliquet erat,nec lobortis felis elit pulvinar sem. Vivamus vulputate, risus eget commodo eleifend, eros nibh porta quam, vitae lacinia leo libero at magna. Maecenas aliquam sagittis orci, et posuere nisi ultrices sit amet. Aliquam ex odio, malesuada sed posuere quis, pellentesque at mauris. Phasellus venenatis massa ex, eget pulvinar libero auctor pretium. Aliquam erat volutpat. Duis euismod justo in quam ullamcorper, in commodo massa vulputate.'; return ( <React.Fragment> <Button id="toggleButton" onClick={this.onClick}> Toggle Drawer </Button> <Drawer isExpanded={isExpanded} onExpand={this.onExpand} position="bottom"> <DrawerSection>drawer-section</DrawerSection> <DrawerContent panelContent={panelContent}> <DrawerContentBody>{drawerContent}</DrawerContentBody> </DrawerContent> </Drawer> </React.Fragment> ); } }
jelly/patternfly-react
packages/react-core/src/components/Banner/__tests__/Banner.test.tsx
<reponame>jelly/patternfly-react import { Banner } from '../Banner'; import React from 'react'; import { render } from '@testing-library/react'; ['default', 'info', 'success', 'warning', 'danger'].forEach((variant: string) => { test(`${variant} banner`, () => { const { asFragment } = render( <Banner variant={variant as 'default' | 'info' | 'success' | 'warning' | 'danger'} aria-label={variant}> {variant} Banner </Banner> ); expect(asFragment()).toMatchSnapshot(); }); }); test(`sticky banner`, () => { const { asFragment } = render( <Banner aria-label="sticky" isSticky> Sticky Banner </Banner> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/demos/ComposableMenu/examples/ComposableTreeViewMenu.tsx
import React from 'react'; import { MenuToggle, Menu, MenuContent, MenuGroup, MenuList, Popper, TreeView, TreeViewDataItem } from '@patternfly/react-core'; export const ComposableTreeViewMenu: React.FunctionComponent = () => { const [isOpen, setIsOpen] = React.useState<boolean>(false); const [checkedItems, setCheckedItems] = React.useState<TreeViewDataItem[]>([]); const toggleRef = React.useRef<HTMLButtonElement>(); const menuRef = React.useRef<HTMLDivElement>(); const statusOptions: TreeViewDataItem[] = [ { name: 'Ready', id: 'ready', checkProps: { checked: false }, customBadgeContent: 1, children: [ { name: 'Updated', id: 'updated', checkProps: { checked: false }, customBadgeContent: 0 }, { name: 'Waiting to update', id: 'waiting', checkProps: { checked: false }, customBadgeContent: 0 }, { name: 'Conditions degraded', id: 'degraded', checkProps: { checked: false }, customBadgeContent: 1 }, { name: 'Approval required', id: 'approval', checkProps: { checked: false }, customBadgeContent: 0 } ] }, { name: 'Not ready', id: 'nr', checkProps: { checked: false }, customBadgeContent: 1, children: [ { name: 'Conditions degraded', id: 'nr-degraded', checkProps: { checked: false }, customBadgeContent: 1 } ] }, { name: 'Updating', id: 'updating', checkProps: { checked: false }, customBadgeContent: 0 } ]; const roleOptions = [ { name: 'Server', id: 'server', checkProps: { checked: false }, customBadgeContent: 2 }, { name: 'Worker', id: 'worker', checkProps: { checked: false }, customBadgeContent: 0 } ]; // Helper functions const isChecked = (dataItem: TreeViewDataItem) => checkedItems.some(item => item.id === dataItem.id); const areAllDescendantsChecked = (dataItem: TreeViewDataItem) => dataItem.children ? dataItem.children.every(child => areAllDescendantsChecked(child)) : isChecked(dataItem); const areSomeDescendantsChecked = (dataItem: TreeViewDataItem) => dataItem.children ? dataItem.children.some(child => areSomeDescendantsChecked(child)) : isChecked(dataItem); const flattenTree = (tree: TreeViewDataItem[]) => { let result = []; tree.forEach(item => { result.push(item); if (item.children) { result = result.concat(flattenTree(item.children)); } }); return result; }; const mapTree = (item: TreeViewDataItem) => { const hasCheck = areAllDescendantsChecked(item); // Reset checked properties to be updated item.checkProps.checked = false; if (hasCheck) { item.checkProps.checked = true; } else { const hasPartialCheck = areSomeDescendantsChecked(item); if (hasPartialCheck) { item.checkProps.checked = null; } } if (item.children) { return { ...item, children: item.children.map(mapTree) }; } return item; }; const filterItems = (item: TreeViewDataItem, checkedItem: TreeViewDataItem) => { if (item.id === checkedItem.id) { return true; } if (item.children) { return ( (item.children = item.children .map(opt => Object.assign({}, opt)) .filter(child => filterItems(child, checkedItem))).length > 0 ); } }; const onCheck = (evt: React.ChangeEvent, treeViewItem: TreeViewDataItem, treeType: string) => { const checked = (evt.target as HTMLInputElement).checked; let options = []; switch (treeType) { case 'status': options = statusOptions; break; case 'role': options = roleOptions; break; default: break; } const checkedItemTree = options.map(opt => Object.assign({}, opt)).filter(item => filterItems(item, treeViewItem)); const flatCheckedItems = flattenTree(checkedItemTree); setCheckedItems(prevCheckedItems => checked ? prevCheckedItems.concat(flatCheckedItems.filter(item => !prevCheckedItems.some(i => i.id === item.id))) : prevCheckedItems.filter(item => !flatCheckedItems.some(i => i.id === item.id)) ); }; const handleMenuKeys = (event: KeyboardEvent) => { if (!isOpen) { return; } if (menuRef.current.contains(event.target as Node) || toggleRef.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)) { 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 = (ev: React.MouseEvent) => { ev.stopPropagation(); // Stop handleClickOutside from handling setTimeout(() => { if (menuRef.current) { const firstElement = menuRef.current.querySelector('li > button:not(:disabled)'); firstElement && (firstElement as HTMLElement).focus(); } }, 0); setIsOpen(!isOpen); }; const toggle = ( <MenuToggle ref={toggleRef} onClick={onToggleClick} isExpanded={isOpen}> {isOpen ? 'Expanded' : 'Collapsed'} </MenuToggle> ); const statusMapped = statusOptions.map(mapTree); const roleMapped = roleOptions.map(mapTree); const menu = ( <Menu ref={menuRef} // eslint-disable-next-line no-console onSelect={(_ev, itemId) => console.log('selected', itemId)} style={ { '--pf-c-menu--Width': '300px' } as React.CSSProperties } > <MenuContent> <MenuList> <MenuGroup label="Status"> <TreeView data={statusMapped} hasBadges hasChecks onCheck={(event, item) => onCheck(event, item, 'status')} /> </MenuGroup> <MenuGroup label="Role"> <TreeView data={roleMapped} hasBadges hasChecks onCheck={(event, item) => onCheck(event, item, 'role')} /> </MenuGroup> </MenuList> </MenuContent> </Menu> ); return <Popper trigger={toggle} popper={menu} isVisible={isOpen} popperMatchesTriggerWidth={false} />; };
jelly/patternfly-react
packages/react-core/src/components/Divider/examples/DividerUsingDiv.tsx
<filename>packages/react-core/src/components/Divider/examples/DividerUsingDiv.tsx import React from 'react'; import { Divider } from '@patternfly/react-core'; export const DividerUsingDiv: React.FunctionComponent = () => <Divider component="div" />;
jelly/patternfly-react
packages/react-core/src/components/Toolbar/ToolbarExpandIconWrapper.tsx
<gh_stars>100-1000 import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Toolbar/toolbar'; import { css } from '@patternfly/react-styles'; export interface ToolbarExpandIconWrapperProps extends React.HTMLProps<HTMLSpanElement> { /** Icon content used for the expand all or collapse all indication. */ children?: React.ReactNode; /** Additional classes added to the span */ className?: string; } export const ToolbarExpandIconWrapper: React.FunctionComponent<ToolbarExpandIconWrapperProps> = ({ children, className, ...props }: ToolbarExpandIconWrapperProps) => ( <span {...props} className={css(styles.toolbarExpandAllIcon, className)}> {children} </span> ); ToolbarExpandIconWrapper.displayName = 'ToolbarExpandIconWrapper';
jelly/patternfly-react
packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyExpandedWithArray.tsx
<filename>packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyExpandedWithArray.tsx import React from 'react'; import { ClipboardCopy, ClipboardCopyVariant } from '@patternfly/react-core'; const text = [ 'Got a lot of text here,', 'need to see all of it?', 'Click that arrow on the left side and check out the resulting expansion.' ]; export const ClipboardCopyExpandedWithArray: React.FunctionComponent = () => ( <ClipboardCopy hoverTip="Copy" clickTip="Copied" variant={ClipboardCopyVariant.expansion}> {text.join(' ')} </ClipboardCopy> );
jelly/patternfly-react
packages/react-core/src/components/Divider/__tests__/Divider.test.tsx
<filename>packages/react-core/src/components/Divider/__tests__/Divider.test.tsx<gh_stars>0 import { Divider } from '../Divider'; import { Flex, FlexItem } from '../../../layouts/Flex'; import * as React from 'react'; import { render } from '@testing-library/react'; test('divider using hr', () => { const { asFragment } = render(<Divider />); expect(asFragment()).toMatchSnapshot(); }); test('divider using li', () => { const { asFragment } = render(<Divider component="li" />); expect(asFragment()).toMatchSnapshot(); }); test('divider using div', () => { const { asFragment } = render(<Divider component="div" />); expect(asFragment()).toMatchSnapshot(); }); test('vertical divider', () => { const { asFragment } = render( <Flex> <FlexItem>first item</FlexItem> <Divider orientation={{ default: 'vertical' }} /> <FlexItem>second item</FlexItem> </Flex> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/Alert/__tests__/Alert.test.tsx
import * as React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Alert, AlertVariant } from '../Alert'; import { AlertActionLink } from '../AlertActionLink'; import { AlertActionCloseButton } from '../AlertActionCloseButton'; import { UsersIcon } from '@patternfly/react-icons'; describe('Alert', () => { test('default Alert variant is default', () => { render(<Alert title="this is a test">Alert testing</Alert>); expect(screen.getByText('this is a test')).toHaveClass('pf-c-alert__title'); }); Object.values(AlertVariant).forEach(variant => { describe(`Alert - ${variant}`, () => { test('Description', () => { const { asFragment } = render( <Alert variant={variant} title=""> Some alert </Alert> ); expect(asFragment()).toMatchSnapshot(); }); test('Title', () => { const { asFragment } = render( <Alert variant={variant} title="Some title"> Some alert </Alert> ); expect(asFragment()).toMatchSnapshot(); }); test('Heading level', () => { const { asFragment } = render( <Alert variant={variant} title="Some title" titleHeadingLevel="h1"> Some alert </Alert> ); expect(asFragment()).toMatchSnapshot(); }); test('Action Link', () => { const { asFragment } = render( <Alert variant={variant} actionLinks={[<AlertActionLink key={'action-1'}>test</AlertActionLink>]} title=""> Some alert </Alert> ); expect(asFragment()).toMatchSnapshot(); }); test('Action Close Button', () => { const onClose = jest.fn(); render( <Alert variant={variant} actionClose={<AlertActionCloseButton aria-label="Close" onClose={onClose} />} title={`Sample ${variant} alert`} > Some alert </Alert> ); userEvent.click(screen.getByLabelText('Close')); expect(onClose).toHaveBeenCalled(); }); test('Action and Title', () => { const { asFragment } = render( <Alert variant={variant} actionLinks={[<AlertActionLink key={'action-1'}>test</AlertActionLink>]} title="Some title" > Some alert </Alert> ); expect(asFragment()).toMatchSnapshot(); }); test('Custom aria label', () => { const { asFragment } = render( <Alert variant={variant} aria-label={`Custom aria label for ${variant}`} actionLinks={[<AlertActionLink key={'action-1'}>test</AlertActionLink>]} title="Some title" > Some alert </Alert> ); expect(asFragment()).toMatchSnapshot(); }); test('inline variation', () => { const { asFragment } = render( <Alert variant={variant} isInline title="Some title"> Some alert </Alert> ); expect(asFragment()).toMatchSnapshot(); }); test('expandable variation', () => { const { asFragment } = render( <Alert variant={variant} title="Some title" isExpandable> <p>Success alert description. This should tell the user more information about the alert.</p> </Alert> ); expect(asFragment()).toMatchSnapshot(); }); test('expandable variation description hidden', () => { const description = 'Success alert description.'; render( <Alert variant={variant} title="Some title" isExpandable> <p>{description}</p> </Alert> ); expect(screen.queryByText(description)).toBeNull(); }); test('Toast alerts match snapsnot', () => { const { asFragment } = render( <Alert isLiveRegion={true} variant={variant} aria-label={`${variant} toast alert`} title="Some title"> Some toast alert </Alert> ); expect(asFragment()).toMatchSnapshot(); }); test('Toast alerts contain default live region', () => { const ariaLabel = `${variant} toast alert`; render( <Alert isLiveRegion={true} variant={variant} aria-label={ariaLabel} title="Some title"> Some toast alert </Alert> ); expect(screen.getByLabelText(ariaLabel)).toHaveAttribute('aria-live', 'polite'); }); test('Toast alert live regions are not atomic', () => { const ariaLabel = `${variant} toast alert`; render( <Alert isLiveRegion={true} variant={variant} aria-label={ariaLabel} title="Some title"> Some toast alert </Alert> ); expect(screen.getByLabelText(ariaLabel)).toHaveAttribute('aria-atomic', 'false'); }); test('Non-toast alerts can have custom live region settings', () => { const ariaLabel = `${variant} toast alert`; render( <Alert aria-live="assertive" aria-relevant="all" aria-atomic="true" variant={variant} aria-label={ariaLabel} title="Some title" > Some noisy alert </Alert> ); const alert = screen.getByLabelText(ariaLabel); expect(alert).toHaveAttribute('aria-live', 'assertive'); expect(alert).toHaveAttribute('aria-relevant', 'all'); expect(alert).toHaveAttribute('aria-atomic', 'true'); }); test('Custom icon', () => { const { asFragment } = render( <Alert customIcon={<UsersIcon />} variant={variant} aria-label={`${variant} custom icon alert`} title="custom icon alert title" > Some noisy alert </Alert> ); expect(asFragment()).toMatchSnapshot(); }); }); }); test('Alert truncate title', () => { render( <Alert truncateTitle={1} title="this is a test"> Alert testing </Alert> ); expect(screen.getByText('this is a test')).toHaveClass('pf-m-truncate'); }); });
jelly/patternfly-react
packages/react-core/src/components/Checkbox/examples/CheckboxWithDescription.tsx
<gh_stars>0 import React from 'react'; import { Checkbox } from '@patternfly/react-core'; export const CheckboxWithDescription: React.FunctionComponent = () => ( <Checkbox id="description-check-1" label="Checkbox with description" description="Single-tenant cloud service hosted and managed by Red Hat that offers high-availability enterprise-grade clusters in a virtual private cloud on AWS or GCP." /> );
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/utils/detectOverflow.ts
// @ts-nocheck import { State, SideObject, Padding } from '../types'; import { Placement, Boundary, RootBoundary, Context } from '../enums'; import getBoundingClientRect from '../dom-utils/getBoundingClientRect'; import getClippingRect from '../dom-utils/getClippingRect'; import getDocumentElement from '../dom-utils/getDocumentElement'; import computeOffsets from './computeOffsets'; import rectToClientRect from './rectToClientRect'; import { clippingParents, reference, popper, bottom, top, right, basePlacements, viewport } from '../enums'; import { isElement } from '../dom-utils/instanceOf'; import mergePaddingObject from './mergePaddingObject'; import expandToHashMap from './expandToHashMap'; // eslint-disable-next-line import/no-unused-modules export interface Options { placement: Placement; boundary: Boundary; rootBoundary: RootBoundary; elementContext: Context; altBoundary: boolean; padding: Padding; } /** * @param state * @param options */ export default function detectOverflow(state: State, options: Partial<Options> = {}): SideObject { const { placement = state.placement, boundary = clippingParents, rootBoundary = viewport, elementContext = popper, altBoundary = false, padding = 0 } = options; const paddingObject = mergePaddingObject( typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements) ); const altContext = elementContext === popper ? reference : popper; const referenceElement = state.elements.reference; const popperRect = state.rects.popper; const element = state.elements[altBoundary ? altContext : elementContext]; const clippingClientRect = getClippingRect( isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary ); const referenceClientRect = getBoundingClientRect(referenceElement); const popperOffsets = computeOffsets({ reference: referenceClientRect, element: popperRect, strategy: 'absolute', placement }); const popperClientRect = rectToClientRect({ ...popperRect, ...popperOffsets }); const elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect // 0 or negative = within the clipping rect const overflowOffsets = { top: clippingClientRect.top - elementClientRect.top + paddingObject.top, bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, left: clippingClientRect.left - elementClientRect.left + paddingObject.left, right: elementClientRect.right - clippingClientRect.right + paddingObject.right }; const offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element if (elementContext === popper && offsetData) { const offset = offsetData[placement]; Object.keys(overflowOffsets).forEach(key => { const multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; const axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x'; overflowOffsets[key] += offset[axis] * multiply; }); } return overflowOffsets; }
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/ToolbarDemo/ToolbarVisiblityDemo.tsx
import React from 'react'; import { Toolbar, ToolbarContent, ToolbarGroup, ToolbarItem, ToolbarToggleGroup } from '@patternfly/react-core'; import FilterIcon from '@patternfly/react-icons/dist/esm/icons/filter-icon'; export class ToolbarVisiblityDemo extends React.Component { static displayName = 'ToolbarVisibilityDemo'; render() { const toolbarContents = ( <React.Fragment> <ToolbarContent visiblity={{ default: 'visible', md: 'hidden' }}>ToolbarContent visiblity sm</ToolbarContent> <ToolbarContent visiblity={{ default: 'hidden', md: 'visible', lg: 'hidden' }}> ToolbarContent visiblity md </ToolbarContent> <ToolbarContent visiblity={{ default: 'hidden', lg: 'visible', xl: 'hidden' }}> ToolbarContent visiblity lg </ToolbarContent> <ToolbarContent visiblity={{ default: 'hidden', xl: 'visible', '2xl': 'hidden' }}> ToolbarContent visiblity xl </ToolbarContent> <ToolbarContent visiblity={{ default: 'hidden', '2xl': 'visible' }}> ToolbarContent visiblity 2xl </ToolbarContent> </React.Fragment> ); const toolbarGroups = ( <React.Fragment> <ToolbarGroup visiblity={{ default: 'visible', md: 'hidden' }}>ToolbarGroup visiblity sm</ToolbarGroup> <ToolbarGroup visiblity={{ default: 'hidden', md: 'visible', lg: 'hidden' }}> ToolbarGroup visiblity md </ToolbarGroup> <ToolbarGroup visiblity={{ default: 'hidden', lg: 'visible', xl: 'hidden' }}> ToolbarGroup visiblity lg </ToolbarGroup> <ToolbarGroup visiblity={{ default: 'hidden', xl: 'visible', '2xl': 'hidden' }}> ToolbarGroup visiblity xl </ToolbarGroup> <ToolbarGroup visiblity={{ default: 'hidden', '2xl': 'visible' }}>ToolbarGroup visiblity 2xl</ToolbarGroup> </React.Fragment> ); const toolbarItems = ( <React.Fragment> <ToolbarItem visiblity={{ default: 'visible', md: 'hidden' }}>ToolbarItem visiblity sm</ToolbarItem> <ToolbarItem visiblity={{ default: 'hidden', md: 'visible', lg: 'hidden' }}> ToolbarItem visiblity md </ToolbarItem> <ToolbarItem visiblity={{ default: 'hidden', lg: 'visible', xl: 'hidden' }}> ToolbarItem visiblity lg </ToolbarItem> <ToolbarItem visiblity={{ default: 'hidden', xl: 'visible', '2xl': 'hidden' }}> ToolbarItem visiblity xl </ToolbarItem> <ToolbarItem visiblity={{ default: 'hidden', '2xl': 'visible' }}>ToolbarItem visiblity 2xl</ToolbarItem> </React.Fragment> ); const toolbarToggleGroups = ( <React.Fragment> <Toolbar> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="md" visiblity={{ default: 'visible', md: 'hidden' }} > ToolbarToggleGroup visiblity sm </ToolbarToggleGroup> </ToolbarContent> </Toolbar> <Toolbar> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="lg" visiblity={{ default: 'hidden', md: 'visible', lg: 'hidden' }} > ToolbarToggleGroup visiblity md </ToolbarToggleGroup> </ToolbarContent> </Toolbar> <Toolbar> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="xl" visiblity={{ default: 'hidden', lg: 'visible', xl: 'hidden' }} > ToolbarToggleGroup visiblity lg </ToolbarToggleGroup> </ToolbarContent> </Toolbar> <Toolbar> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="2xl" visiblity={{ default: 'hidden', xl: 'visible', '2xl': 'hidden' }} > ToolbarToggleGroup visiblity xl </ToolbarToggleGroup> </ToolbarContent> </Toolbar> <Toolbar> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="md" visiblity={{ default: 'hidden', '2xl': 'visible' }} > ToolbarToggleGroup visiblity 2xl </ToolbarToggleGroup> </ToolbarContent> </Toolbar> </React.Fragment> ); return ( <div id="toolbar-visiblity-demo"> <Toolbar>{toolbarContents}</Toolbar> <Toolbar> <ToolbarContent>{toolbarGroups}</ToolbarContent> </Toolbar> <Toolbar> <ToolbarContent>{toolbarItems}</ToolbarContent> </Toolbar> {toolbarToggleGroups} </div> ); } }
jelly/patternfly-react
packages/react-topology/src/components/nodes/labels/LabelContextMenu.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import EllipsisVIcon from '@patternfly/react-icons/dist/esm/icons/ellipsis-v-icon'; import { WithContextMenuProps } from '../../../behavior'; import LabelActionIcon from './LabelActionIcon'; type LabelContextMenuProps = { className?: string; x: number; y: number; height: number; paddingX: number; paddingY: number; } & WithContextMenuProps; const LabelContextMenu = React.forwardRef<SVGRectElement, LabelContextMenuProps>( ({ onContextMenu, className, x, y, paddingX, paddingY, height }, menuRef) => ( <LabelActionIcon ref={menuRef} icon={<EllipsisVIcon />} iconOffsetX={-6} className={className} onClick={onContextMenu} x={x} y={y} height={height} paddingX={paddingX} paddingY={paddingY} /> ) ); export default LabelContextMenu;
jelly/patternfly-react
packages/react-core/src/components/CalendarMonth/examples/CalendarMonthDefault.tsx
import React from 'react'; import { CalendarMonth } from '@patternfly/react-core'; export const CalendarMonthDefault: React.FunctionComponent = () => <CalendarMonth date={new Date()} />;