repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
jelly/patternfly-react
packages/react-console/src/components/index.ts
/** Keep alphabetically sorted */ export * from './AccessConsoles'; export * from './DesktopViewer'; export * from './SerialConsole'; export * from './SpiceConsole'; export * from './VncConsole'; export * from './common/constants';
jelly/patternfly-react
packages/react-integration/cypress/integration/tablecomposable.spec.ts
<reponame>jelly/patternfly-react<filename>packages/react-integration/cypress/integration/tablecomposable.spec.ts describe('Text Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/table-composable-demo-nav-link'); }); it('Verify tooltip entry delay', () => { cy.get('#table-text-tooltip').click(); cy.get('.pf-c-tooltip', { timeout: 1000 }).should('exist'); }); });
jelly/patternfly-react
packages/react-topology/src/anchors/RectAnchor.ts
<gh_stars>100-1000 import Point from '../geom/Point'; import { getRectAnchorPoint } from '../utils/anchor-utils'; import AbstractAnchor from './AbstractAnchor'; export default class RectAnchor extends AbstractAnchor { getLocation(reference: Point): Point { const r = this.owner.getBounds(); const center = r.getCenter(); if (r.isEmpty()) { return center; } const offset2x = this.offset * 2; return getRectAnchorPoint(center, r.width + offset2x, r.height + offset2x, reference); } }
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/SelectDemo/SelectValidatedDemo.tsx
import React, { Component } from 'react'; import { Select, SelectOption, SelectVariant, StackItem, Title, ValidatedOptions } from '@patternfly/react-core'; /* eslint-disable no-console */ export interface SelectValidatedDemoState { isOpen: boolean; selected: string[]; validated: ValidatedOptions.default | ValidatedOptions.error | ValidatedOptions.warning | ValidatedOptions.success; } export class SelectValidatedDemo extends Component<SelectValidatedDemoState> { state = { isOpen: false, selected: [] as string[], validated: ValidatedOptions.default }; 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 }); }; onSelect = (event: React.MouseEvent | React.ChangeEvent, selection: string, isPlaceholder: boolean) => { let validatedState = 'success'; if (isPlaceholder) { this.clearSelection(); validatedState = 'error'; } else { if (selection === 'Other') { validatedState = 'warning'; } else { validatedState = 'success'; } this.setState({ selected: selection, isOpen: false }); console.log('selected:', selection); } this.setState({ validated: validatedState }); }; clearSelection = () => { this.setState({ selected: null, isOpen: false }); }; render() { const { isOpen, selected, validated } = this.state; const titleId = 'validated-select-id'; return ( <div id="select-validated-demo"> <StackItem isFilled={false}> <Title headingLevel="h2" size="2xl"> Validated Select </Title> <Select toggleId="validated-select" variant={SelectVariant.single} placeholderText="Select an option" aria-label="Select Input validated" onToggle={this.onToggle} onSelect={this.onSelect} selections={selected} isOpen={isOpen} aria-labelledby={titleId} aria-describedby="validated-helper" aria-invalid={validated === 'error' ? true : false} validated={validated} > {this.options} </Select> <div aria-live="polite" id="validated-helper" hidden> {validated} </div> </StackItem> </div> ); } }
jelly/patternfly-react
packages/react-console/src/components/AccessConsoles/AccessConsoles.tsx
<gh_stars>100-1000 import React from 'react'; import { css } from '@patternfly/react-styles'; import { Select, SelectOption, SelectOptionObject, SelectVariant } from '@patternfly/react-core'; import { constants } from '../common/constants'; import styles from '@patternfly/react-styles/css/components/Consoles/AccessConsoles'; import '@patternfly/react-styles/css/components/Consoles/AccessConsoles.css'; const { NONE_TYPE, SERIAL_CONSOLE_TYPE, VNC_CONSOLE_TYPE, DESKTOP_VIEWER_CONSOLE_TYPE } = constants; const getChildTypeName = (child: any) => child && child.props && child.props.type ? child.props.type : (child && child.type && child.type.displayName) || null; const isChildOfType = (child: any, type: string) => { if (child && child.props && child.props.type) { return child.props.type === type; } else if (child && child.type) { return child.type.displayName === type; } return false; }; export interface AccessConsolesProps { /** * Child element can be either * - <SerialConsole>, <VncConsole> or <DesktopViewer> * - or has a property "type" of value either SERIAL_CONSOLE_TYPE or VNC_CONSOLE_TYPE (useful when wrapping (composing) basic console components */ children?: React.ReactElement[] | React.ReactNode; /** Placeholder text for the console selection */ textSelectConsoleType?: string; /** The value for the Serial Console option. This can be overriden by the type property of the child component */ textSerialConsole?: string; /** The value for the VNC Console option. This can be overriden by the type property of the child component */ textVncConsole?: string; /** The value for the Desktop Viewer Console option. This can be overriden by the type property of the child component */ textDesktopViewerConsole?: string; /** Initial selection of the Select */ preselectedType?: string; // NONE_TYPE | SERIAL_CONSOLE_TYPE | VNC_CONSOLE_TYPE | DESKTOP_VIEWER_CONSOLE_TYPE; } export const AccessConsoles: React.FunctionComponent<AccessConsolesProps> = ({ children, textSelectConsoleType = 'Select console type', textSerialConsole = 'Serial console', textVncConsole = 'VNC console', textDesktopViewerConsole = 'Desktop viewer', preselectedType = null }) => { const typeMap = { [SERIAL_CONSOLE_TYPE]: textSerialConsole, [VNC_CONSOLE_TYPE]: textVncConsole, [DESKTOP_VIEWER_CONSOLE_TYPE]: textDesktopViewerConsole }; const [type, setType] = React.useState( preselectedType !== NONE_TYPE ? ({ value: preselectedType, toString: () => typeMap[preselectedType] } as SelectOptionObject) : null ); const [isOpen, setIsOpen] = React.useState(false); const getConsoleForType = (type: any) => React.Children.map(children as React.ReactElement[], (child: any) => { if (getChildTypeName(child) === type.value) { return <React.Fragment key={getChildTypeName(child)}>{child}</React.Fragment>; } else { return null; } }); const onToggle = (isOpen: boolean) => { setIsOpen(isOpen); }; const selectOptions: any[] = []; React.Children.toArray(children as React.ReactElement[]).forEach((child: any) => { if (isChildOfType(child, VNC_CONSOLE_TYPE)) { selectOptions.push( <SelectOption key={VNC_CONSOLE_TYPE} id={VNC_CONSOLE_TYPE} value={{ value: VNC_CONSOLE_TYPE, toString: () => textVncConsole } as SelectOptionObject} /> ); } else if (isChildOfType(child, SERIAL_CONSOLE_TYPE)) { selectOptions.push( <SelectOption key={SERIAL_CONSOLE_TYPE} id={SERIAL_CONSOLE_TYPE} value={{ value: SERIAL_CONSOLE_TYPE, toString: () => textSerialConsole } as SelectOptionObject} /> ); } else if (isChildOfType(child, DESKTOP_VIEWER_CONSOLE_TYPE)) { selectOptions.push( <SelectOption key={DESKTOP_VIEWER_CONSOLE_TYPE} id={DESKTOP_VIEWER_CONSOLE_TYPE} value={{ value: DESKTOP_VIEWER_CONSOLE_TYPE, toString: () => textDesktopViewerConsole } as SelectOptionObject} /> ); } else { const typeText = getChildTypeName(child); selectOptions.push( <SelectOption key={typeText} id={typeText} value={{ value: typeText, toString: () => typeText } as SelectOptionObject} /> ); } }); return ( <div className={css(styles.console)}> {React.Children.toArray(children).length > 1 && ( <div className={css(styles.consoleActions)}> <Select aria-label={textSelectConsoleType} placeholderText={textSelectConsoleType} toggleId="pf-c-console__type-selector" variant={SelectVariant.single} onSelect={(_, selection, __) => { setType(selection as SelectOptionObject); setIsOpen(false); }} selections={type} isOpen={isOpen} onToggle={onToggle} > {selectOptions} </Select> </div> )} {type && getConsoleForType(type)} </div> ); }; AccessConsoles.displayName = 'AccessConsoles';
jelly/patternfly-react
packages/react-console/src/declarations.d.ts
<gh_stars>100-1000 declare module '@spice-project/spice-html5' { export const SpiceMainConn: any; export const sendCtrlAltDel: any; } declare module '@novnc/novnc/core/rfb' { class RFB { constructor(target: any, url: any, options: any); } export = RFB; } declare module '@novnc/novnc/core/util/logging' { export const initLogging: any; }
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/utils/getOppositeVariationPlacement.ts
<filename>packages/react-core/src/helpers/Popper/thirdparty/popper-core/utils/getOppositeVariationPlacement.ts // @ts-nocheck import { Placement } from '../enums'; const hash = { start: 'end', end: 'start' }; /** * @param placement */ export default function getOppositeVariationPlacement(placement: Placement): Placement { return placement.replace(/start|end/g, matched => hash[matched]) as any; }
jelly/patternfly-react
packages/react-topology/src/components/edges/index.ts
<filename>packages/react-topology/src/components/edges/index.ts export { default as DefaultEdge } from './DefaultEdge'; export { default as DefaultConntectorTag } from './DefaultConnectorTag'; export * from './terminals';
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/data/miserables.ts
export default { nodes: [ { id: 'Myriel', group: 1 }, { id: 'Napoleon', group: 1 }, { id: 'Mlle.Baptistine', group: 1 }, { id: 'Mme.Magloire', group: 1 }, { id: 'CountessdeLo', group: 1 }, { id: 'Geborand', group: 1 }, { id: 'Champtercier', group: 1 }, { id: 'Cravatte', group: 1 }, { id: 'Count', group: 1 }, { id: 'OldMan', group: 1 }, { id: 'Labarre', group: 2 }, { id: 'Valjean', group: 2 }, { id: 'Marguerite', group: 3 }, { id: 'Mme.deR', group: 2 }, { id: 'Isabeau', group: 2 }, { id: 'Gervais', group: 2 }, { id: 'Tholomyes', group: 3 }, { id: 'Listolier', group: 3 }, { id: 'Fameuil', group: 3 }, { id: 'Blacheville', group: 3 }, { id: 'Favourite', group: 3 }, { id: 'Dahlia', group: 3 }, { id: 'Zephine', group: 3 }, { id: 'Fantine', group: 3 }, { id: 'Mme.Thenardier', group: 4 }, { id: 'Thenardier', group: 4 }, { id: 'Cosette', group: 5 }, { id: 'Javert', group: 4 }, { id: 'Fauchelevent', group: 0 }, { id: 'Bamatabois', group: 2 }, { id: 'Perpetue', group: 3 }, { id: 'Simplice', group: 2 }, { id: 'Scaufflaire', group: 2 }, { id: 'Woman1', group: 2 }, { id: 'Judge', group: 2 }, { id: 'Champmathieu', group: 2 }, { id: 'Brevet', group: 2 }, { id: 'Chenildieu', group: 2 }, { id: 'Cochepaille', group: 2 }, { id: 'Pontmercy', group: 4 }, { id: 'Boulatruelle', group: 6 }, { id: 'Eponine', group: 4 }, { id: 'Anzelma', group: 4 }, { id: 'Woman2', group: 5 }, { id: 'MotherInnocent', group: 0 }, { id: 'Gribier', group: 0 }, { id: 'Jondrette', group: 7 }, { id: 'Mme.Burgon', group: 7 }, { id: 'Gavroche', group: 8 }, { id: 'Gillenormand', group: 5 }, { id: 'Magnon', group: 5 }, { id: 'Mlle.Gillenormand', group: 5 }, { id: 'Mme.Pontmercy', group: 5 }, { id: 'Mlle.Vaubois', group: 5 }, { id: 'Lt.Gillenormand', group: 5 }, { id: 'Marius', group: 8 }, { id: 'BaronessT', group: 5 }, { id: 'Mabeuf', group: 8 }, { id: 'Enjolras', group: 8 }, { id: 'Combeferre', group: 8 }, { id: 'Prouvaire', group: 8 }, { id: 'Feuilly', group: 8 }, { id: 'Courfeyrac', group: 8 }, { id: 'Bahorel', group: 8 }, { id: 'Bossuet', group: 8 }, { id: 'Joly', group: 8 }, { id: 'Grantaire', group: 8 }, { id: 'MotherPlutarch', group: 9 }, { id: 'Gueulemer', group: 4 }, { id: 'Babet', group: 4 }, { id: 'Claquesous', group: 4 }, { id: 'Montparnasse', group: 4 }, { id: 'Toussaint', group: 5 }, { id: 'Child1', group: 10 }, { id: 'Child2', group: 10 }, { id: 'Brujon', group: 4 }, { id: 'Mme.Hucheloup', group: 8 } ], links: [ { source: 'Napoleon', target: 'Myriel' }, { source: 'Mlle.Baptistine', target: 'Myriel' }, { source: 'Mme.Magloire', target: 'Myriel' }, { source: 'Mme.Magloire', target: 'Mlle.Baptistine' }, { source: 'CountessdeLo', target: 'Myriel' }, { source: 'Geborand', target: 'Myriel' }, { source: 'Champtercier', target: 'Myriel' }, { source: 'Cravatte', target: 'Myriel' }, { source: 'Count', target: 'Myriel' }, { source: 'OldMan', target: 'Myriel' }, { source: 'Valjean', target: 'Labarre' }, { source: 'Valjean', target: 'Mme.Magloire' }, { source: 'Valjean', target: 'Mlle.Baptistine' }, { source: 'Valjean', target: 'Myriel' }, { source: 'Marguerite', target: 'Valjean' }, { source: 'Mme.deR', target: 'Valjean' }, { source: 'Isabeau', target: 'Valjean' }, { source: 'Gervais', target: 'Valjean' }, { source: 'Listolier', target: 'Tholomyes' }, { source: 'Fameuil', target: 'Tholomyes' }, { source: 'Fameuil', target: 'Listolier' }, { source: 'Blacheville', target: 'Tholomyes' }, { source: 'Blacheville', target: 'Listolier' }, { source: 'Blacheville', target: 'Fameuil' }, { source: 'Favourite', target: 'Tholomyes' }, { source: 'Favourite', target: 'Listolier' }, { source: 'Favourite', target: 'Fameuil' }, { source: 'Favourite', target: 'Blacheville' }, { source: 'Dahlia', target: 'Tholomyes' }, { source: 'Dahlia', target: 'Listolier' }, { source: 'Dahlia', target: 'Fameuil' }, { source: 'Dahlia', target: 'Blacheville' }, { source: 'Dahlia', target: 'Favourite' }, { source: 'Zephine', target: 'Tholomyes' }, { source: 'Zephine', target: 'Listolier' }, { source: 'Zephine', target: 'Fameuil' }, { source: 'Zephine', target: 'Blacheville' }, { source: 'Zephine', target: 'Favourite' }, { source: 'Zephine', target: 'Dahlia' }, { source: 'Fantine', target: 'Tholomyes' }, { source: 'Fantine', target: 'Listolier' }, { source: 'Fantine', target: 'Fameuil' }, { source: 'Fantine', target: 'Blacheville' }, { source: 'Fantine', target: 'Favourite' }, { source: 'Fantine', target: 'Dahlia' }, { source: 'Fantine', target: 'Zephine' }, { source: 'Fantine', target: 'Marguerite' }, { source: 'Fantine', target: 'Valjean' }, { source: 'Mme.Thenardier', target: 'Fantine' }, { source: 'Mme.Thenardier', target: 'Valjean' }, { source: 'Thenardier', target: 'Mme.Thenardier' }, { source: 'Thenardier', target: 'Fantine' }, { source: 'Thenardier', target: 'Valjean' }, { source: 'Cosette', target: 'Mme.Thenardier' }, { source: 'Cosette', target: 'Valjean' }, { source: 'Cosette', target: 'Tholomyes' }, { source: 'Cosette', target: 'Thenardier' }, { source: 'Javert', target: 'Valjean' }, { source: 'Javert', target: 'Fantine' }, { source: 'Javert', target: 'Thenardier' }, { source: 'Javert', target: 'Mme.Thenardier' }, { source: 'Javert', target: 'Cosette' }, { source: 'Fauchelevent', target: 'Valjean' }, { source: 'Fauchelevent', target: 'Javert' }, { source: 'Bamatabois', target: 'Fantine' }, { source: 'Bamatabois', target: 'Javert' }, { source: 'Bamatabois', target: 'Valjean' }, { source: 'Perpetue', target: 'Fantine' }, { source: 'Simplice', target: 'Perpetue' }, { source: 'Simplice', target: 'Valjean' }, { source: 'Simplice', target: 'Fantine' }, { source: 'Simplice', target: 'Javert' }, { source: 'Scaufflaire', target: 'Valjean' }, { source: 'Woman1', target: 'Valjean' }, { source: 'Woman1', target: 'Javert' }, { source: 'Judge', target: 'Valjean' }, { source: 'Judge', target: 'Bamatabois' }, { source: 'Champmathieu', target: 'Valjean' }, { source: 'Champmathieu', target: 'Judge' }, { source: 'Champmathieu', target: 'Bamatabois' }, { source: 'Brevet', target: 'Judge' }, { source: 'Brevet', target: 'Champmathieu' }, { source: 'Brevet', target: 'Valjean' }, { source: 'Brevet', target: 'Bamatabois' }, { source: 'Chenildieu', target: 'Judge' }, { source: 'Chenildieu', target: 'Champmathieu' }, { source: 'Chenildieu', target: 'Brevet' }, { source: 'Chenildieu', target: 'Valjean' }, { source: 'Chenildieu', target: 'Bamatabois' }, { source: 'Cochepaille', target: 'Judge' }, { source: 'Cochepaille', target: 'Champmathieu' }, { source: 'Cochepaille', target: 'Brevet' }, { source: 'Cochepaille', target: 'Chenildieu' }, { source: 'Cochepaille', target: 'Valjean' }, { source: 'Cochepaille', target: 'Bamatabois' }, { source: 'Pontmercy', target: 'Thenardier' }, { source: 'Boulatruelle', target: 'Thenardier' }, { source: 'Eponine', target: 'Mme.Thenardier' }, { source: 'Eponine', target: 'Thenardier' }, { source: 'Anzelma', target: 'Eponine' }, { source: 'Anzelma', target: 'Thenardier' }, { source: 'Anzelma', target: 'Mme.Thenardier' }, { source: 'Woman2', target: 'Valjean' }, { source: 'Woman2', target: 'Cosette' }, { source: 'Woman2', target: 'Javert' }, { source: 'MotherInnocent', target: 'Fauchelevent' }, { source: 'MotherInnocent', target: 'Valjean' }, { source: 'Gribier', target: 'Fauchelevent' }, { source: 'Mme.Burgon', target: 'Jondrette' }, { source: 'Gavroche', target: 'Mme.Burgon' }, { source: 'Gavroche', target: 'Thenardier' }, { source: 'Gavroche', target: 'Javert' }, { source: 'Gavroche', target: 'Valjean' }, { source: 'Gillenormand', target: 'Cosette' }, { source: 'Gillenormand', target: 'Valjean' }, { source: 'Magnon', target: 'Gillenormand' }, { source: 'Magnon', target: 'Mme.Thenardier' }, { source: 'Mlle.Gillenormand', target: 'Gillenormand' }, { source: 'Mlle.Gillenormand', target: 'Cosette' }, { source: 'Mlle.Gillenormand', target: 'Valjean' }, { source: 'Mme.Pontmercy', target: 'Mlle.Gillenormand' }, { source: 'Mme.Pontmercy', target: 'Pontmercy' }, { source: 'Mlle.Vaubois', target: 'Mlle.Gillenormand' }, { source: 'Lt.Gillenormand', target: 'Mlle.Gillenormand' }, { source: 'Lt.Gillenormand', target: 'Gillenormand' }, { source: 'Lt.Gillenormand', target: 'Cosette' }, { source: 'Marius', target: 'Mlle.Gillenormand' }, { source: 'Marius', target: 'Gillenormand' }, { source: 'Marius', target: 'Pontmercy' }, { source: 'Marius', target: 'Lt.Gillenormand' }, { source: 'Marius', target: 'Cosette' }, { source: 'Marius', target: 'Valjean' }, { source: 'Marius', target: 'Tholomyes' }, { source: 'Marius', target: 'Thenardier' }, { source: 'Marius', target: 'Eponine' }, { source: 'Marius', target: 'Gavroche' }, { source: 'BaronessT', target: 'Gillenormand' }, { source: 'BaronessT', target: 'Marius' }, { source: 'Mabeuf', target: 'Marius' }, { source: 'Mabeuf', target: 'Eponine' }, { source: 'Mabeuf', target: 'Gavroche' }, { source: 'Enjolras', target: 'Marius' }, { source: 'Enjolras', target: 'Gavroche' }, { source: 'Enjolras', target: 'Javert' }, { source: 'Enjolras', target: 'Mabeuf' }, { source: 'Enjolras', target: 'Valjean' }, { source: 'Combeferre', target: 'Enjolras' }, { source: 'Combeferre', target: 'Marius' }, { source: 'Combeferre', target: 'Gavroche' }, { source: 'Combeferre', target: 'Mabeuf' }, { source: 'Prouvaire', target: 'Gavroche' }, { source: 'Prouvaire', target: 'Enjolras' }, { source: 'Prouvaire', target: 'Combeferre' }, { source: 'Feuilly', target: 'Gavroche' }, { source: 'Feuilly', target: 'Enjolras' }, { source: 'Feuilly', target: 'Prouvaire' }, { source: 'Feuilly', target: 'Combeferre' }, { source: 'Feuilly', target: 'Mabeuf' }, { source: 'Feuilly', target: 'Marius' }, { source: 'Courfeyrac', target: 'Marius' }, { source: 'Courfeyrac', target: 'Enjolras' }, { source: 'Courfeyrac', target: 'Combeferre' }, { source: 'Courfeyrac', target: 'Gavroche' }, { source: 'Courfeyrac', target: 'Mabeuf' }, { source: 'Courfeyrac', target: 'Eponine' }, { source: 'Courfeyrac', target: 'Feuilly' }, { source: 'Courfeyrac', target: 'Prouvaire' }, { source: 'Bahorel', target: 'Combeferre' }, { source: 'Bahorel', target: 'Gavroche' }, { source: 'Bahorel', target: 'Courfeyrac' }, { source: 'Bahorel', target: 'Mabeuf' }, { source: 'Bahorel', target: 'Enjolras' }, { source: 'Bahorel', target: 'Feuilly' }, { source: 'Bahorel', target: 'Prouvaire' }, { source: 'Bahorel', target: 'Marius' }, { source: 'Bossuet', target: 'Marius' }, { source: 'Bossuet', target: 'Courfeyrac' }, { source: 'Bossuet', target: 'Gavroche' }, { source: 'Bossuet', target: 'Bahorel' }, { source: 'Bossuet', target: 'Enjolras' }, { source: 'Bossuet', target: 'Feuilly' }, { source: 'Bossuet', target: 'Prouvaire' }, { source: 'Bossuet', target: 'Combeferre' }, { source: 'Bossuet', target: 'Mabeuf' }, { source: 'Bossuet', target: 'Valjean' }, { source: 'Joly', target: 'Bahorel' }, { source: 'Joly', target: 'Bossuet' }, { source: 'Joly', target: 'Gavroche' }, { source: 'Joly', target: 'Courfeyrac' }, { source: 'Joly', target: 'Enjolras' }, { source: 'Joly', target: 'Feuilly' }, { source: 'Joly', target: 'Prouvaire' }, { source: 'Joly', target: 'Combeferre' }, { source: 'Joly', target: 'Mabeuf' }, { source: 'Joly', target: 'Marius' }, { source: 'Grantaire', target: 'Bossuet' }, { source: 'Grantaire', target: 'Enjolras' }, { source: 'Grantaire', target: 'Combeferre' }, { source: 'Grantaire', target: 'Courfeyrac' }, { source: 'Grantaire', target: 'Joly' }, { source: 'Grantaire', target: 'Gavroche' }, { source: 'Grantaire', target: 'Bahorel' }, { source: 'Grantaire', target: 'Feuilly' }, { source: 'Grantaire', target: 'Prouvaire' }, { source: 'MotherPlutarch', target: 'Mabeuf' }, { source: 'Gueulemer', target: 'Thenardier' }, { source: 'Gueulemer', target: 'Valjean' }, { source: 'Gueulemer', target: 'Mme.Thenardier' }, { source: 'Gueulemer', target: 'Javert' }, { source: 'Gueulemer', target: 'Gavroche' }, { source: 'Gueulemer', target: 'Eponine' }, { source: 'Babet', target: 'Thenardier' }, { source: 'Babet', target: 'Gueulemer' }, { source: 'Babet', target: 'Valjean' }, { source: 'Babet', target: 'Mme.Thenardier' }, { source: 'Babet', target: 'Javert' }, { source: 'Babet', target: 'Gavroche' }, { source: 'Babet', target: 'Eponine' }, { source: 'Claquesous', target: 'Thenardier' }, { source: 'Claquesous', target: 'Babet' }, { source: 'Claquesous', target: 'Gueulemer' }, { source: 'Claquesous', target: 'Valjean' }, { source: 'Claquesous', target: 'Mme.Thenardier' }, { source: 'Claquesous', target: 'Javert' }, { source: 'Claquesous', target: 'Eponine' }, { source: 'Claquesous', target: 'Enjolras' }, { source: 'Montparnasse', target: 'Javert' }, { source: 'Montparnasse', target: 'Babet' }, { source: 'Montparnasse', target: 'Gueulemer' }, { source: 'Montparnasse', target: 'Claquesous' }, { source: 'Montparnasse', target: 'Valjean' }, { source: 'Montparnasse', target: 'Gavroche' }, { source: 'Montparnasse', target: 'Eponine' }, { source: 'Montparnasse', target: 'Thenardier' }, { source: 'Toussaint', target: 'Cosette' }, { source: 'Toussaint', target: 'Javert' }, { source: 'Toussaint', target: 'Valjean' }, { source: 'Child1', target: 'Gavroche' }, { source: 'Child2', target: 'Gavroche' }, { source: 'Child2', target: 'Child1' }, { source: 'Brujon', target: 'Babet' }, { source: 'Brujon', target: 'Gueulemer' }, { source: 'Brujon', target: 'Thenardier' }, { source: 'Brujon', target: 'Gavroche' }, { source: 'Brujon', target: 'Eponine' }, { source: 'Brujon', target: 'Claquesous' }, { source: 'Brujon', target: 'Montparnasse' }, { source: 'Mme.Hucheloup', target: 'Bossuet' }, { source: 'Mme.Hucheloup', target: 'Joly' }, { source: 'Mme.Hucheloup', target: 'Grantaire' }, { source: 'Mme.Hucheloup', target: 'Bahorel' }, { source: 'Mme.Hucheloup', target: 'Courfeyrac' }, { source: 'Mme.Hucheloup', target: 'Gavroche' }, { source: 'Mme.Hucheloup', target: 'Enjolras' } ] };
jelly/patternfly-react
packages/react-core/src/components/Card/examples/CardWithNoFooter.tsx
<gh_stars>0 import React from 'react'; import { Card, CardTitle, CardBody } from '@patternfly/react-core'; export const CardWithNoFooter: React.FunctionComponent = () => ( <Card> <CardTitle>Header</CardTitle> <CardBody>This card has no footer</CardBody> </Card> );
jelly/patternfly-react
packages/react-core/src/components/Tabs/TabContentBody.tsx
import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/TabContent/tab-content'; export interface TabContentBodyProps extends React.HTMLProps<HTMLDivElement> { /** Content rendered inside the tab content body. */ children: React.ReactNode; /** Additional classes added to the tab content body. */ className?: string; /** Indicates if there should be padding around the tab content body */ hasPadding?: boolean; } export const TabContentBody: React.FunctionComponent<TabContentBodyProps> = ({ children, className, hasPadding, ...props }: TabContentBodyProps) => ( <div className={css(styles.tabContentBody, hasPadding && styles.modifiers.padding, className)} {...props}> {children} </div> ); TabContentBody.displayName = 'TabContentBody';
jelly/patternfly-react
packages/react-core/src/components/ClipboardCopy/__tests__/Generated/ClipboardCopy.test.tsx
/** * This test was generated */ import * as React from 'react'; import { render } from '@testing-library/react'; import { ClipboardCopy } from '../../ClipboardCopy'; // any missing imports can usually be resolved by adding them here import {} from '../..'; it('ClipboardCopy should match snapshot (auto-generated)', () => { const { asFragment } = render( <ClipboardCopy className={'string'} hoverTip={"'Copy to clipboard'"} clickTip={"'Successfully copied to clipboard!'"} textAriaLabel={"'Copyable input'"} toggleAriaLabel={"'Show content'"} isReadOnly={false} isExpanded={false} isCode={false} variant={'inline'} position={'auto'} maxWidth={"'150px'"} exitDelay={1600} entryDelay={100} switchDelay={2000} onCopy={(event: React.ClipboardEvent<HTMLDivElement>, text?: React.ReactNode) => { const clipboard = event.currentTarget.parentElement; const el = document.createElement('input'); el.value = text.toString(); clipboard.appendChild(el); el.select(); document.execCommand('copy'); clipboard.removeChild(el); }} onChange={(): any => undefined} children={<div>ReactNode</div>} /> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-charts/src/components/ChartBullet/index.ts
<reponame>jelly/patternfly-react export * from './ChartBullet'; export * from './ChartBulletComparativeErrorMeasure'; export * from './ChartBulletComparativeMeasure'; export * from './ChartBulletComparativeWarningMeasure'; export * from './ChartBulletPrimaryDotMeasure'; export * from './ChartBulletPrimarySegmentedMeasure'; export * from './ChartBulletQualitativeRange';
jelly/patternfly-react
packages/react-topology/src/components/factories/RegisterElementFactory.tsx
import * as React from 'react'; import useElementFactory from '../../hooks/useElementFactory'; import { ElementFactory } from '../../types'; interface Props { factory: ElementFactory; } const RegisteElementFactory: React.FunctionComponent<Props> = ({ factory }) => { useElementFactory(factory); return null; }; export default RegisteElementFactory;
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TabsDemo/TabsDisabledDemo.tsx
import React from 'react'; import { Tabs, Tab, TabTitleText, Tooltip } from '@patternfly/react-core'; export class TabsDisabledDemo extends React.Component { static displayName = 'TabsDisabledDemo'; state = { activeTabKey: 0, isBox: false }; constructor(props: {}) { super(props); } private handleTabClick = (_event: React.MouseEvent<HTMLElement, MouseEvent>, tabIndex: number | string) => { this.setState({ activeTabKey: tabIndex }); }; render() { const { activeTabKey } = this.state; const tooltipRef = React.createRef(); return ( <> <Tabs id="disabledTabs" activeKey={activeTabKey} onSelect={this.handleTabClick}> <Tab eventKey={0} title={<TabTitleText>Users</TabTitleText>} id="not-disabled"> <div id="not-disabled-content">Users</div> </Tab> <Tab eventKey={1} title={<TabTitleText>Disabled</TabTitleText>} isDisabled id="is-disabled"> <div id="is-disabled-content">Disabled</div> </Tab> <Tab eventKey={2} title={<TabTitleText>ARIA Disabled</TabTitleText>} isAriaDisabled id="is-aria-disabled"> <div id="is-aira-disabled-content">ARIA Disabled</div> </Tab> <Tab eventKey={3} title={<TabTitleText>ARIA Disabled (Tooltip)</TabTitleText>} isAriaDisabled ref={tooltipRef} id="with-tooltip" > <div id="with-tooltip-content">ARIA Disabled (Tooltip)</div> </Tab> </Tabs> <Tooltip content={ <div id="tooltip-content"> Aria-disabled tabs are like disabled tabs, but focusable. Allows for tooltip support." </div> } reference={tooltipRef} /> </> ); } }
jelly/patternfly-react
packages/react-core/src/components/DatePicker/examples/DatePickerBasic.tsx
import React from 'react'; import { DatePicker } from '@patternfly/react-core'; export const DatePickerBasic: React.FunctionComponent = () => ( <DatePicker // eslint-disable-next-line no-console onBlur={(str, date) => console.log('onBlur', str, date)} // eslint-disable-next-line no-console onChange={(str, date) => console.log('onChange', str, date)} /> );
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/shapes/Polygon.tsx
<filename>packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/shapes/Polygon.tsx import { PointTuple, ShapeProps, usePolygonAnchor } from '@patternfly/react-topology'; import * as React from 'react'; const Polygon: React.FunctionComponent<ShapeProps> = ({ className, width, height, filter, dndDropRef }) => { const points: PointTuple[] = React.useMemo( () => [ [width / 2, 0], [width - width / 8, height], [0, height / 3], [width, height / 3], [width / 8, height] ], [height, width] ); usePolygonAnchor(points); return ( <polygon className={className} ref={dndDropRef} points={points.map(p => `${p[0]},${p[1]}`).join(' ')} filter={filter} /> ); }; export default Polygon;
jelly/patternfly-react
packages/react-core/src/layouts/Split/Split.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/layouts/Split/split'; import { css } from '@patternfly/react-styles'; export interface SplitProps extends React.HTMLProps<HTMLDivElement> { /** Adds space between children. */ hasGutter?: boolean; /** Allows children to wrap */ isWrappable?: boolean; /** content rendered inside the Split layout */ children?: React.ReactNode; /** additional classes added to the Split layout */ className?: string; /** Sets the base component to render. defaults to div */ component?: React.ReactNode; } export const Split: React.FunctionComponent<SplitProps> = ({ hasGutter = false, isWrappable = false, className = '', children = null, component = 'div', ...props }: SplitProps) => { const Component = component as any; return ( <Component {...props} className={css( styles.split, hasGutter && styles.modifiers.gutter, isWrappable && styles.modifiers.wrap, className )} > {children} </Component> ); }; Split.displayName = 'Split';
jelly/patternfly-react
packages/react-integration/cypress/integration/progressstepper.spec.ts
<reponame>jelly/patternfly-react describe('Progress Stepper Demo Test', () => { it('Navigate to progress stepper section', () => { cy.visit('http://localhost:3000/progress-stepper-demo-nav-link'); }); it('Display Progress stepper and launch popover', () => { cy.get('#popover-step1-title').then((popoverLink: JQuery<HTMLDivElement>) => { cy.get('.pf-c-popover').should('not.exist'); cy.wrap(popoverLink).click(); cy.get('.pf-c-popover').should('exist'); cy.get('button[aria-label="Close"]').then(closeBtn => { cy.wrap(closeBtn).click(); cy.get('.pf-c-popover').should('not.exist'); }); }); }); });
jelly/patternfly-react
packages/react-core/src/components/DragDrop/examples/DragDropMultipleLists.tsx
<filename>packages/react-core/src/components/DragDrop/examples/DragDropMultipleLists.tsx import React from 'react'; import { DragDrop, Draggable, Droppable, Split, SplitItem } from '@patternfly/react-core'; interface ItemType { id: string; content: string; } interface SourceType { droppableId: string; index: number; } interface DestinationType extends SourceType {} const getItems = (count: number, startIndex: number) => Array.from({ length: count }, (_, idx) => idx + startIndex).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; }; const move = (source: ItemType[], destination: ItemType[], sourceIndex: number, destIndex: number) => { const sourceClone = source; const destClone = destination; const [removed] = sourceClone.splice(sourceIndex, 1); destClone.splice(destIndex, 0, removed); return [sourceClone, destClone]; }; export const DragDropMultipleLists: React.FunctionComponent = () => { const [items, setItems] = React.useState({ items1: getItems(10, 0), items2: getItems(5, 10) }); function onDrop(source: SourceType, dest: DestinationType) { // eslint-disable-next-line no-console console.log(source, dest); if (dest) { if (source.droppableId === dest.droppableId) { const newItems = reorder( source.droppableId === 'items1' ? items.items1 : items.items2, source.index, dest.index ); if (source.droppableId === 'items1') { setItems({ items1: newItems, items2: items.items2 }); } else { setItems({ items1: items.items1, items2: newItems }); } } else { const [newItems1, newItems2] = move( source.droppableId === 'items1' ? items.items1 : items.items2, dest.droppableId === 'items1' ? items.items1 : items.items2, source.index, dest.index ); setItems({ items1: source.droppableId === 'items1' ? newItems1 : newItems2, items2: dest.droppableId === 'items1' ? newItems1 : newItems2 }); } return true; } return false; } return ( <DragDrop onDrop={onDrop}> <Split hasGutter> {Object.entries(items).map(([key, subitems]) => ( <SplitItem key={key} style={{ flex: 1 }}> <Droppable zone="multizone" droppableId={key}> {subitems.map(({ id, content }) => ( <Draggable key={id} style={{ padding: '8px' }}> {content} </Draggable> ))} </Droppable> </SplitItem> ))} </Split> </DragDrop> ); };
jelly/patternfly-react
packages/react-core/src/components/TextInput/TextInput.tsx
<filename>packages/react-core/src/components/TextInput/TextInput.tsx<gh_stars>0 import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/FormControl/form-control'; import { css } from '@patternfly/react-styles'; import { ValidatedOptions } from '../../helpers/constants'; import { trimLeft } from '../../helpers/util'; import { getDefaultOUIAId, getOUIAProps, OUIAProps } from '../../helpers'; import { getResizeObserver } from '../../helpers/resizeObserver'; export enum TextInputTypes { text = 'text', date = 'date', datetimeLocal = 'datetime-local', email = 'email', month = 'month', number = 'number', password = 'password', search = 'search', tel = 'tel', time = 'time', url = 'url' } export interface TextInputProps extends Omit<React.HTMLProps<HTMLInputElement>, 'onChange' | 'onFocus' | 'onBlur' | 'disabled' | 'ref'>, OUIAProps { /** Additional classes added to the TextInput. */ className?: string; /** Flag to show if the input is disabled. */ isDisabled?: boolean; /** Flag to show if the input is read only. */ isReadOnly?: boolean; /** Flag to show if the input is required. */ isRequired?: boolean; /** Value to indicate if the input is modified to show that validation state. * If set to success, input will be modified to indicate valid state. * If set to error, input will be modified to indicate error state. */ validated?: 'success' | 'warning' | 'error' | 'default'; /** A callback for when the input value changes. */ onChange?: (value: string, event: React.FormEvent<HTMLInputElement>) => void; /** Type that the input accepts. */ type?: | 'text' | 'date' | 'datetime-local' | 'email' | 'month' | 'number' | 'password' | 'search' | 'tel' | 'time' | 'url'; /** Value of the input. */ value?: string | number; /** Aria-label. The input requires an associated id or aria-label. */ 'aria-label'?: string; /** A reference object to attach to the input box. */ innerRef?: React.RefObject<any>; /** Trim text on left */ isLeftTruncated?: boolean; /** Callback function when input is focused */ onFocus?: (event?: any) => void; /** Callback function when input is blurred (focus leaves) */ onBlur?: (event?: any) => void; /** icon variant */ iconVariant?: 'calendar' | 'clock' | 'search'; /** Use the external file instead of a data URI */ isIconSprite?: boolean; /** Custom icon url to set as the input's background-image */ customIconUrl?: string; /** Dimensions for the custom icon set as the input's background-size */ customIconDimensions?: string; } interface TextInputState { ouiaStateId: string; } export class TextInputBase extends React.Component<TextInputProps, TextInputState> { static displayName = 'TextInputBase'; static defaultProps: TextInputProps = { 'aria-label': null, className: '', isRequired: false, validated: 'default' as 'success' | 'warning' | 'error' | 'default', isDisabled: false, isReadOnly: false, isIconSprite: false, type: TextInputTypes.text, isLeftTruncated: false, onChange: (): any => undefined, ouiaSafe: true }; inputRef = React.createRef<HTMLInputElement>(); observer: any = () => {}; constructor(props: TextInputProps) { super(props); if (!props.id && !props['aria-label'] && !props['aria-labelledby']) { // eslint-disable-next-line no-console console.error('Text input:', 'Text input requires either an id or aria-label to be specified'); } this.state = { ouiaStateId: getDefaultOUIAId(TextInputBase.displayName) }; } handleChange = (event: React.FormEvent<HTMLInputElement>) => { if (this.props.onChange) { this.props.onChange(event.currentTarget.value, event); } }; componentDidMount() { if (this.props.isLeftTruncated) { const inputRef = this.props.innerRef || this.inputRef; this.observer = getResizeObserver(inputRef.current, this.handleResize); this.handleResize(); } } componentWillUnmount() { if (this.props.isLeftTruncated) { this.observer(); } } handleResize = () => { const inputRef = this.props.innerRef || this.inputRef; if (inputRef && inputRef.current) { trimLeft(inputRef.current, String(this.props.value)); } }; restoreText = () => { const inputRef = this.props.innerRef || this.inputRef; // restore the value (inputRef.current as HTMLInputElement).value = String(this.props.value); // make sure we still see the rightmost value to preserve cursor click position inputRef.current.scrollLeft = inputRef.current.scrollWidth; }; onFocus = (event?: any) => { const { isLeftTruncated, onFocus } = this.props; if (isLeftTruncated) { this.restoreText(); } onFocus && onFocus(event); }; onBlur = (event?: any) => { const { isLeftTruncated, onBlur } = this.props; if (isLeftTruncated) { this.handleResize(); } onBlur && onBlur(event); }; render() { const { innerRef, className, type, value, validated, /* eslint-disable @typescript-eslint/no-unused-vars */ onChange, onFocus, onBlur, isLeftTruncated, /* eslint-enable @typescript-eslint/no-unused-vars */ isReadOnly, isRequired, isDisabled, isIconSprite, iconVariant, customIconUrl, customIconDimensions, ouiaId, ouiaSafe, ...props } = this.props; const customIconStyle = {} as any; if (customIconUrl) { customIconStyle.backgroundImage = `url('${customIconUrl}')`; } if (customIconDimensions) { customIconStyle.backgroundSize = customIconDimensions; } return ( <input {...props} onFocus={this.onFocus} onBlur={this.onBlur} className={css( styles.formControl, isIconSprite && styles.modifiers.iconSprite, validated === ValidatedOptions.success && styles.modifiers.success, validated === ValidatedOptions.warning && styles.modifiers.warning, ((iconVariant && iconVariant !== 'search') || customIconUrl) && styles.modifiers.icon, iconVariant && styles.modifiers[iconVariant], className )} onChange={this.handleChange} type={type} value={this.sanitizeInputValue(value)} aria-invalid={props['aria-invalid'] ? props['aria-invalid'] : validated === ValidatedOptions.error} required={isRequired} disabled={isDisabled} readOnly={isReadOnly} ref={innerRef || this.inputRef} {...((customIconUrl || customIconDimensions) && { style: customIconStyle })} {...getOUIAProps(TextInput.displayName, ouiaId !== undefined ? ouiaId : this.state.ouiaStateId, ouiaSafe)} /> ); } private sanitizeInputValue = (value: string | number) => typeof value === 'string' ? value.replace(/\n/g, ' ') : value; } export const TextInput = React.forwardRef((props: TextInputProps, ref: React.Ref<HTMLInputElement>) => ( <TextInputBase {...props} innerRef={ref as React.MutableRefObject<any>} /> )); TextInput.displayName = 'TextInput';
jelly/patternfly-react
packages/react-core/src/components/DataList/examples/DataListControllingText.tsx
import React from 'react'; import { DataList, DataListItem, DataListItemRow, DataListItemCells, DataListCell, DataListWrapModifier } from '@patternfly/react-core'; export const DataListControllingText: React.FunctionComponent = () => ( <DataList aria-label="Simple data list example"> <DataListItem aria-labelledby="simple-item1"> <DataListItemRow> <DataListItemCells dataListCells={[ <DataListCell key="primary content" wrapModifier={DataListWrapModifier.breakWord}> <span id="simple-item1">Primary content</span> </DataListCell>, <DataListCell key="secondary content" wrapModifier={DataListWrapModifier.truncate}> Really really really really really really really really really really really really really really long description that should be truncated before it ends </DataListCell> ]} /> </DataListItemRow> </DataListItem> </DataList> );
jelly/patternfly-react
packages/react-core/src/components/ActionList/__tests__/ActionListGroup.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import { ActionListGroup } from '../ActionListGroup'; describe('action list group', () => { test('renders successfully', () => { const { asFragment } = render(<ActionListGroup>test</ActionListGroup>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-charts/src/components/ChartUtils/chart-interactive-legend.ts
/* eslint-disable camelcase */ import chart_area_Opacity from '@patternfly/react-tokens/dist/esm/chart_area_Opacity'; import chart_color_black_500 from '@patternfly/react-tokens/dist/esm/chart_color_black_500'; interface ChartInteractiveLegendInterface { // The names or groups of names associated with each data series // Example: // [ area-1, area-2, area-3 ] // [ [area-1, scatter-1], [area-2, scatter-2], [area-3, scatter-3] ] chartNames: [string | string[]]; isDataHidden?: (data: any) => boolean; // Returns true if given data is hidden -- helpful when bar charts are hidden isHidden?: (index: number) => boolean; // Returns true if given index, associated with the legend item, is hidden legendName: string; // The name property associated with the legend onLegendClick?: (props: any) => void; // Called when legend item is clicked } interface ChartInteractiveLegendExtInterface extends ChartInteractiveLegendInterface { omitIndex?: number; // Used to omit child names when attaching events target?: 'data' | 'labels'; // Event target } // Returns child names for each series, except given ID index const getChildNames = ({ chartNames, omitIndex }: ChartInteractiveLegendExtInterface) => { const result = [] as any; chartNames.map((chartName: any, index: number) => { if (index !== omitIndex) { if (Array.isArray(chartName)) { chartName.forEach(name => result.push(name)); } else { result.push(chartName); } } }); return result; }; // Returns events for an interactive legend export const getInteractiveLegendEvents = (props: ChartInteractiveLegendInterface) => [ ...getInteractiveLegendTargetEvents({ ...props, target: 'data' }), ...getInteractiveLegendTargetEvents({ ...props, target: 'labels' }) ]; // Returns legend items, except given ID index const getInteractiveLegendItems = ({ chartNames, omitIndex }: ChartInteractiveLegendExtInterface) => { const result = [] as any; chartNames.map((_, index: number) => { if (index !== omitIndex) { result.push(index); } }); return result; }; // Returns styles for interactive legend items export const getInteractiveLegendItemStyles = (hidden = false) => !hidden ? {} : { labels: { fill: chart_color_black_500.value }, symbol: { fill: chart_color_black_500.value, type: 'eyeSlash' } }; // Returns targeted events for legend 'data' or 'labels' const getInteractiveLegendTargetEvents = ({ chartNames, isDataHidden = () => false, isHidden = () => false, legendName, onLegendClick = () => null, target }: ChartInteractiveLegendExtInterface) => { if (chartNames === undefined || legendName === undefined) { // eslint-disable-next-line no-console console.error('getInteractiveLegendTargetEvents:', 'requires chartNames and legendName to be specified'); return []; } return chartNames.map((_, index) => { // Get IDs to attach events to, except the IDs associated with this event. // // For example, if the current event key is 0, we need IDs associated with events 1 and 2. If the current event // key is 1, we need IDs associated with events 0 and 2. And so on... const childNames = getChildNames({ chartNames, legendName, omitIndex: index }); const legendItems = getInteractiveLegendItems({ chartNames, legendName, omitIndex: index }); return { childName: legendName, target, eventKey: index, eventHandlers: { onClick: () => [ { // Hide each data series individually target: 'data', mutation: (props: any) => { onLegendClick(props); return null; } } ], onMouseOver: () => isHidden(index) ? null : [ { // Mute all data series, except the data associated with this event childName: childNames, target: 'data', eventKey: 'all', mutation: (props: any) => isDataHidden(props.data) ? null : ({ // Skip if hidden style: props.padAngle !== undefined // Support for pie chart ? { ...props.style, ...(index !== props.index && { opacity: chart_area_Opacity.value }) } : { ...props.style, opacity: chart_area_Opacity.value } } as any) }, { // Mute all legend item symbols, except the symbol associated with this event childName: legendName, target: 'data', eventKey: legendItems, mutation: (props: any) => isHidden(props.index) ? null : { // Skip if hidden style: { ...props.style, opacity: chart_area_Opacity.value } } }, { // Mute all legend item labels, except the label associated with this event childName: legendName, target: 'labels', eventKey: legendItems, mutation: (props: any) => { const column = props.datum && props.datum.column ? props.datum.column : 0; return isHidden(column) ? null : { // Skip if hidden style: { ...props.style, opacity: chart_area_Opacity.value } }; } } ], onMouseOut: () => [ { // Restore all data series associated with this event childName: 'all', target: 'data', eventKey: 'all', mutation: () => null as any }, { // Restore all legend item symbols associated with this event childName: 'legend', target: 'data', eventKey: legendItems, mutation: () => null as any }, { // Restore all legend item labels associated with this event childName: 'legend', target: 'labels', eventKey: legendItems, mutation: () => null as any } ] } }; }); };
jelly/patternfly-react
packages/react-charts/src/components/ChartLegendTooltip/index.ts
export * from './ChartLegendTooltip'; export * from './ChartLegendTooltipContent'; export * from './ChartLegendTooltipLabel';
jelly/patternfly-react
packages/react-topology/src/layouts/ConcentricNode.ts
import { LayoutNode } from './LayoutNode'; import { Node } from '../types'; export class ConcentricNode extends LayoutNode { constructor(node: Node, distance: number, index: number = -1) { super(node, distance, index); } }
jelly/patternfly-react
packages/react-core/src/components/Form/index.ts
<gh_stars>100-1000 export * from './ActionGroup'; export * from './Form'; export * from './FormAlert'; export * from './FormFieldGroup'; export * from './FormFieldGroupExpandable'; export * from './FormFieldGroupHeader'; export * from './FormGroup'; export * from './FormHelperText'; export * from './FormSection';
jelly/patternfly-react
packages/react-core/src/demos/examples/HelperText/HelperTextDynamicVariantStaticText.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { Form, FormGroup, FormHelperText, TextInput, HelperText, HelperTextItem } from '@patternfly/react-core'; export const HelperTextDynamicVariantDynamicText: React.FunctionComponent = () => { const [value, setValue] = React.useState(''); const [inputValidation, setInputValidation] = React.useState({ ruleLength: 'indeterminate', ruleCharacterTypes: 'indeterminate' }); const { ruleLength, ruleCharacterTypes } = inputValidation; React.useEffect(() => { let lengthStatus = ruleLength; let typeStatus = ruleCharacterTypes; if (value === '') { setInputValidation({ ruleLength: 'indeterminate', ruleCharacterTypes: 'indeterminate' }); return; } if (!/\d/g.test(value)) { typeStatus = 'error'; } else { typeStatus = 'success'; } if (value.length < 5) { lengthStatus = 'error'; } else { lengthStatus = 'success'; } setInputValidation({ ruleLength: lengthStatus, ruleCharacterTypes: typeStatus }); }, [value, ruleLength, ruleCharacterTypes]); const handleInputChange = (inputValue: string) => { setValue(inputValue); }; const filterValidations = () => Object.keys(inputValidation).filter(item => inputValidation[item] !== 'success'); return ( <Form> <FormGroup label="Username" isRequired fieldId="login-input-helper-text3"> <TextInput isRequired type="text" id="login-input-helper-text3" name="login-input-helper-text3" onChange={handleInputChange} aria-describedby={filterValidations().join(' ')} aria-invalid={ruleCharacterTypes === 'error' || ruleLength === 'error'} value={value} /> <FormHelperText isHidden={false} component="div"> <HelperText component="ul"> <HelperTextItem component="li" id="ruleLength" isDynamic variant={ruleLength as any}> Must be at least 5 characters in length </HelperTextItem> <HelperTextItem component="li" id="ruleCharacterTypes" isDynamic variant={ruleCharacterTypes as any}> Must include at least 1 number </HelperTextItem> </HelperText> </FormHelperText> </FormGroup> </Form> ); };
jelly/patternfly-react
packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyInlineCompactInSentence.tsx
<filename>packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyInlineCompactInSentence.tsx import React from 'react'; import { ClipboardCopy } from '@patternfly/react-core'; export const ClipboardCopyInlineCompactInSentence: React.FunctionComponent = () => ( <React.Fragment> <b>Basic</b> <br /> Lorem ipsum{' '} { <ClipboardCopy hoverTip="Copy" clickTip="Copied" variant="inline-compact"> 2.3.4-2-redhat </ClipboardCopy> } dolor sit amet. <br /> <br /> <b>Long copy string</b> <br /> Lorem ipsum dolor sit amet, consectetur adipiscing elit.{' '} { <ClipboardCopy hoverTip="Copy" clickTip="Copied" variant="inline-compact"> https://app.openshift.io/path/sub-path/sub-sub-path/?runtime=quarkus/12345678901234567890/abcdefghijklmnopqrstuvwxyz1234567890 </ClipboardCopy> }{' '} Mauris luctus, libero nec dapibus ultricies, urna purus pretium mauris, ullamcorper pharetra lacus nibh vitae enim. <br /> <br /> <b>Long copy string in block</b> <br /> Lorem ipsum dolor sit amet, consectetur adipiscing elit.{' '} { <ClipboardCopy hoverTip="Copy" clickTip="Copied" variant="inline-compact" isBlock> https://app.openshift.io/path/sub-path/sub-sub-path/?runtime=quarkus/12345678901234567890/abcdefghijklmnopqrstuvwxyz1234567890 </ClipboardCopy> }{' '} Mauris luctus, libero nec dapibus ultricies, urna purus pretium mauris, ullamcorper pharetra lacus nibh vitae enim. </React.Fragment> );
jelly/patternfly-react
packages/react-table/src/components/Table/utils/decorators/collapsible.tsx
import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Table/table'; import { CollapseColumn } from '../../CollapseColumn'; import { ExpandableRowContent } from '../../ExpandableRowContent'; import { IExtra, IFormatterValueType, IFormatter, decoratorReturnType } from '../../TableTypes'; export const collapsible: IFormatter = ( value: IFormatterValueType, { rowIndex, columnIndex, rowData, column, property }: IExtra ) => { const { extraParams: { onCollapse, rowLabeledBy = 'simple-node', expandId = 'expand-toggle', allRowsExpanded, collapseAllAriaLabel } } = column; const extraData = { rowIndex, columnIndex, column, property }; const rowId = rowIndex !== undefined ? rowIndex : -1; const customProps = { ...(rowId !== -1 ? { isOpen: rowData?.isOpen, 'aria-labelledby': `${rowLabeledBy}${rowId} ${expandId}${rowId}` } : { isOpen: allRowsExpanded, 'aria-label': collapseAllAriaLabel || 'Expand all rows' }) }; /** * @param {React.MouseEvent} event - Mouse event */ function onToggle(event: React.MouseEvent<HTMLButtonElement, MouseEvent>) { const open = rowData ? !rowData.isOpen : !allRowsExpanded; // tslint:disable-next-line:no-unused-expression onCollapse && onCollapse(event, rowIndex, open, rowData, extraData); } return { className: (rowData?.isOpen !== undefined || rowId === -1) && css(styles.tableToggle), isVisible: !rowData?.fullWidth, children: ( <CollapseColumn aria-labelledby={`${rowLabeledBy}${rowId} ${expandId}${rowId}`} onToggle={onToggle} id={expandId + rowId} {...customProps} > {value} </CollapseColumn> ) }; }; export const expandable: IFormatter = (value: IFormatterValueType, { rowData }: IExtra) => rowData && rowData.hasOwnProperty('parent') ? <ExpandableRowContent>{value}</ExpandableRowContent> : value; export const expandedRow = (colSpan?: number) => { const expandedRowFormatter = ( value: IFormatterValueType, { columnIndex, rowIndex, rowData, column: { extraParams: { contentId = 'expanded-content' } } }: IExtra ): decoratorReturnType => value && rowData.hasOwnProperty('parent') && { // todo: rewrite this logic, it is not type safe colSpan: !rowData.cells || rowData.cells.length === 1 ? colSpan + (!!rowData.fullWidth as any) : 1, id: contentId + rowIndex + (columnIndex ? '-' + columnIndex : ''), className: rowData.noPadding && css(styles.modifiers.noPadding) }; return expandedRowFormatter; };
jelly/patternfly-react
packages/react-topology/src/components/TopologySideBar/index.ts
export * from './TopologySideBar';
jelly/patternfly-react
packages/react-table/src/components/Table/utils/decorators/wrappable.tsx
<gh_stars>100-1000 import styles from '@patternfly/react-styles/css/components/Table/table'; import { ITransform } from '../../TableTypes'; export const breakWord: ITransform = () => ({ className: styles.modifiers.breakWord }); export const fitContent: ITransform = () => ({ className: styles.modifiers.fitContent }); export const nowrap: ITransform = () => ({ className: styles.modifiers.nowrap }); export const truncate: ITransform = () => ({ className: styles.modifiers.truncate }); export const wrappable: ITransform = () => ({ className: styles.modifiers.wrap });
jelly/patternfly-react
packages/react-core/src/components/Nav/__tests__/Nav.test.tsx
import * as React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Nav, NavContext } from '../Nav'; import { NavList } from '../NavList'; import { NavGroup } from '../NavGroup'; import { NavItem } from '../NavItem'; import { NavExpandable } from '../NavExpandable'; const props = { items: [ { to: '#link1', label: 'Link 1' }, { to: '#link2', label: 'Link 2' }, { to: '#link3', label: 'Link 3' }, { to: '#link4', label: 'Link 4' } ] }; const renderNav = (ui: React.ReactElement<any, string | React.JSXElementConstructor<any>>) => render(<NavContext.Provider value={{ onSelect: jest.fn(), onToggle: jest.fn() }}>{ui}</NavContext.Provider>); describe('Nav', () => { beforeEach(() => { window.location.hash = '#link1'; }); test('Default Nav List', () => { const { asFragment } = renderNav( <Nav className="test-nav-class"> <NavList className="test-nav-list-class"> {props.items.map(item => ( <NavItem to={item.to} key={item.to} className="test-nav-item-class"> {item.label} </NavItem> ))} </NavList> </Nav> ); expect(asFragment()).toMatchSnapshot(); }); test('Dark Nav List', () => { const { asFragment } = renderNav( <Nav className="test=nav-class" theme="dark"> <NavList className="test-nav-list-class"> {props.items.map(item => ( <NavItem to={item.to} key={item.to} className="test-nav-item-class"> {item.label} </NavItem> ))} </NavList> </Nav> ); expect(asFragment()).toMatchSnapshot(); }); test('Default Nav List - Trigger item active update', () => { const { asFragment } = renderNav( <Nav> <NavList> {props.items.map(item => ( <NavItem to={item.to} key={item.to}> {item.label} </NavItem> ))} </NavList> </Nav> ); userEvent.click(screen.getByText('Link 2')); expect(asFragment()).toMatchSnapshot(); }); test('Expandable Nav List', () => { const { asFragment } = renderNav( <Nav> <NavList> <NavExpandable id="grp-1" title="Section 1"> {props.items.map(item => ( <NavItem to={item.to} key={item.to}> {item.label} </NavItem> ))} </NavExpandable> </NavList> </Nav> ); expect(asFragment()).toMatchSnapshot(); }); test('Expandable Nav verify onExpand', () => { const onExpand = jest.fn(); renderNav( <Nav> <NavList> <NavExpandable id="grp-1" title="Section 1" onExpand={onExpand}> {props.items.map(item => ( <NavItem to={item.to} key={item.to}> {item.label} </NavItem> ))} </NavExpandable> </NavList> </Nav> ); userEvent.click(screen.getByRole('button')); expect(onExpand).toHaveBeenCalled(); }); test('Expandable Nav List - Trigger toggle', () => { window.location.hash = '#link2'; const { asFragment } = renderNav( <Nav> <NavList> <NavExpandable id="grp-1" title="Section 1" className="expandable-group" isExpanded> {props.items.map(item => ( <NavItem to={item.to} key={item.to}> {item.label} </NavItem> ))} </NavExpandable> </NavList> </Nav> ); userEvent.click(screen.getByText('Section 1')); expect(asFragment()).toMatchSnapshot(); }); test('Expandable Nav List with aria label', () => { const { asFragment } = renderNav( <Nav aria-label="Test"> <NavList> <NavExpandable id="grp-1" title="Section 1" srText="Section 1 - Example sub-navigation"> {props.items.map(item => ( <NavItem to={item.to} key={item.to}> {item.label} </NavItem> ))} </NavExpandable> </NavList> </Nav> ); expect(asFragment()).toMatchSnapshot(); }); test('Nav Grouped List', () => { const { asFragment } = renderNav( <Nav> <NavGroup id="grp-1" title="Section 1"> <NavList> {props.items.map(item => ( <NavItem to={item.to} key={`section1_${item.to}`}> {item.label} </NavItem> ))} </NavList> </NavGroup> <NavGroup id="grp-2" title="Section 2"> <NavList> {props.items.map(item => ( <NavItem to={item.to} key={`section2_${item.to}`}> {item.label} </NavItem> ))} </NavList> </NavGroup> </Nav> ); expect(asFragment()).toMatchSnapshot(); }); test('Horizontal Nav List', () => { const { asFragment } = renderNav( <Nav variant="horizontal"> <NavList> {props.items.map(item => ( <NavItem to={item.to} key={item.to}> {item.label} </NavItem> ))} </NavList> </Nav> ); expect(asFragment()).toMatchSnapshot(); }); test('Horizontal SubNav List', () => { const { asFragment } = renderNav( <Nav variant="horizontal-subnav"> <NavList> {props.items.map(item => ( <NavItem to={item.to} key={item.to}> {item.label} </NavItem> ))} </NavList> </Nav> ); expect(asFragment()).toMatchSnapshot(); }); test('Tertiary Nav List', () => { const { asFragment } = renderNav( <Nav variant="tertiary"> <NavList> {props.items.map(item => ( <NavItem to={item.to} key={item.to}> {item.label} </NavItem> ))} </NavList> </Nav> ); expect(asFragment()).toMatchSnapshot(); }); test('Nav List with custom item nodes', () => { const { asFragment } = renderNav( <Nav variant="tertiary"> <NavList> <NavItem to="/components/nav#link1" className="test-nav-item-class"> <div className="my-custom-node">My custom node</div> </NavItem> </NavList> </Nav> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/Alert/examples/AlertDynamicLiveRegion.tsx
<gh_stars>100-1000 import React from 'react'; import { Alert, AlertGroup, AlertVariant, InputGroup } from '@patternfly/react-core'; interface AlertInfo { title: string; variant: AlertVariant; key: number; } export const DynamicLiveRegionAlert: React.FunctionComponent = () => { const [alerts, setAlerts] = React.useState<AlertInfo[]>([]); const getUniqueId: () => number = () => new Date().getTime(); const btnClasses = ['pf-c-button', 'pf-m-secondary'].join(' '); const addAlert = (alertInfo: AlertInfo) => { setAlerts(prevAlertInfo => [...prevAlertInfo, alertInfo]); }; const addSuccessAlert = () => { addAlert({ title: 'Single success alert', variant: AlertVariant.success, key: getUniqueId() }); }; const addInfoAlert = () => { addAlert({ title: 'Single info alert', variant: AlertVariant.info, key: getUniqueId() }); }; const addDangerAlert = () => { addAlert({ title: 'Single danger alert', variant: AlertVariant.danger, key: getUniqueId() }); }; return ( <React.Fragment> <InputGroup style={{ marginBottom: '16px' }}> <button onClick={addSuccessAlert} type="button" className={btnClasses}> Add single success alert </button> <button onClick={addInfoAlert} type="button" className={btnClasses}> Add single info alert </button> <button onClick={addDangerAlert} type="button" className={btnClasses}> Add single danger alert </button> </InputGroup> <AlertGroup isLiveRegion aria-live="polite" aria-relevant="additions text" aria-atomic="false"> {alerts.map(({ title, variant, key }) => ( <Alert variant={variant} title={title} key={key} /> ))} </AlertGroup> </React.Fragment> ); };
jelly/patternfly-react
packages/react-code-editor/src/components/CodeEditor/examples/CodeEditorCustomControl.tsx
import React from 'react'; import { CodeEditor, CodeEditorControl } from '@patternfly/react-code-editor'; import PlayIcon from '@patternfly/react-icons/dist/esm/icons/play-icon'; export const CodeEditorCustomControl: React.FunctionComponent = () => { const [code, setCode] = React.useState(''); const onChange = code => { setCode(code); }; const onExecuteCode = code => { // eslint-disable-next-line no-console console.log(code); }; const customControl = ( <CodeEditorControl icon={<PlayIcon />} aria-label="Execute code" toolTipText="Execute code" onClick={onExecuteCode} isVisible={code !== ''} /> ); return ( <CodeEditor isDownloadEnabled isCopyEnabled height="400px" customControls={customControl} code={code} onChange={onChange} /> ); };
jelly/patternfly-react
packages/react-integration/cypress/integration/datalist.spec.ts
describe('Data List Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/data-list-demo-nav-link'); }); it('Verify rows selectable', () => { cy.get('#row1.pf-m-selectable').should('exist'); cy.get('#row2.pf-m-selectable').should('exist'); cy.get('#row1.pf-m-selected').should('not.exist'); cy.get('#row2.pf-m-selected').should('not.exist'); cy.get('#row1').click(); cy.get('#row1.pf-m-selected').should('exist'); cy.get('#row2.pf-m-selected').should('not.exist'); cy.get('#row2').click(); cy.get('#row1.pf-m-selected').should('not.exist'); cy.get('#row2.pf-m-selected').should('exist'); }); }); describe('Data List Draggable Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/data-list-draggable-demo-nav-link'); }); it('Verify drag', () => { cy.get('#data1').contains('Item 1'); cy.get('#drag1').type(' '); cy.get('#drag1').type('{downarrow}'); cy.get('#data1').should('have.class', 'pf-m-ghost-row'); cy.get('#drag1').type('{downarrow}'); cy.get('#drag1').type('{enter}'); cy.get('#data1').should('not.have.class', 'pf-m-ghost-row'); }); });
jelly/patternfly-react
packages/react-core/src/components/DataList/examples/DataListCheckboxes.tsx
<filename>packages/react-core/src/components/DataList/examples/DataListCheckboxes.tsx import React from 'react'; import { Button, DataList, DataListItem, DataListItemCells, DataListItemRow, DataListCell, DataListCheck, DataListAction, Dropdown, DropdownItem, DropdownPosition, KebabToggle } from '@patternfly/react-core'; export const DataListCheckboxes: React.FunctionComponent = () => { const [isOpen1, setIsOpen1] = React.useState(false); const [isOpen2, setIsOpen2] = React.useState(false); const [isOpen3, setIsOpen3] = React.useState(false); const onToggle1 = isOpen1 => { setIsOpen1(isOpen1); }; const onSelect1 = () => { setIsOpen1(!isOpen1); }; const onToggle2 = isOpen2 => { setIsOpen2(isOpen2); }; const onSelect2 = () => { setIsOpen2(!isOpen2); }; const onToggle3 = isOpen3 => { setIsOpen3(isOpen3); }; const onSelect3 = () => { setIsOpen3(!isOpen3); }; return ( <DataList aria-label="Checkbox and action data list example"> <DataListItem aria-labelledby="check-action-item1"> <DataListItemRow> <DataListCheck aria-labelledby="check-action-item1" name="check-action-check1" /> <DataListItemCells dataListCells={[ <DataListCell key="primary content"> <span id="check-action-item1">Primary content</span> Dolor sit amet, consectetur adipisicing elit, sed do eiusmod. </DataListCell>, <DataListCell key="secondary content 1"> Secondary content. Dolor sit amet, consectetur adipisicing elit, sed do eiusmod. </DataListCell>, <DataListCell key="secondary content 2"> <span>Tertiary content</span> Dolor sit amet, consectetur adipisicing elit, sed do eiusmod. </DataListCell>, <DataListCell key="more content 1"> <span>More content</span> Dolor sit amet, consectetur adipisicing elit, sed do eiusmod. </DataListCell>, <DataListCell key="more content 2"> <span>More content</span> Dolor sit amet, consectetur adipisicing elit, sed do eiusmod. </DataListCell> ]} /> <DataListAction aria-labelledby="check-action-item1 check-action-action1" id="check-action-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> <DataListItem aria-labelledby="check-action-item2"> <DataListItemRow> <DataListCheck aria-labelledby="check-action-item2" name="check-action-check2" /> <DataListItemCells dataListCells={[ <DataListCell key="primary content"> <span id="check-action-item2">Primary content - Lorem ipsum</span> dolor sit amet, consectetur adipisicing elit, sed do eiusmod. </DataListCell>, <DataListCell key="secondary content"> Secondary content. Dolor sit amet, consectetur adipisicing elit, sed do eiusmod. </DataListCell> ]} /> <DataListAction visibility={{ lg: 'hidden' }} aria-labelledby="check-action-item2 check-action-action2" id="check-action-action2" aria-label="Actions" isPlainButtonAction > <Dropdown isPlain position={DropdownPosition.right} isOpen={isOpen2} onSelect={onSelect2} toggle={<KebabToggle onToggle={onToggle2} />} dropdownItems={[ <DropdownItem key="pri-action2" component="button"> Primary </DropdownItem>, <DropdownItem key="sec-action2" component="button"> Secondary </DropdownItem> ]} /> </DataListAction> <DataListAction visibility={{ default: 'hidden', lg: 'visible' }} aria-labelledby="check-action-item2 check-action-action2" id="check-action-action2" aria-label="Actions" > <Button variant="primary">Primary</Button> <Button variant="secondary">Secondary</Button> </DataListAction> </DataListItemRow> </DataListItem> <DataListItem aria-labelledby="check-action-item3"> <DataListItemRow> <DataListCheck aria-labelledby="check-action-item3" name="check-action-check3" /> <DataListItemCells dataListCells={[ <DataListCell key="primary content"> <span id="check-action-item3">Primary content - Lorem ipsum</span> dolor sit amet, consectetur adipisicing elit, sed do eiusmod. </DataListCell>, <DataListCell key="secondary content"> Secondary content. Dolor sit amet, consectetur adipisicing elit, sed do eiusmod. </DataListCell> ]} /> <DataListAction visibility={{ xl: 'hidden' }} aria-labelledby="check-action-item3 check-action-action3" id="check-actiokn-action3" aria-label="Actions" isPlainButtonAction > <Dropdown isPlain position={DropdownPosition.right} isOpen={isOpen3} onSelect={onSelect3} toggle={<KebabToggle onToggle={onToggle3} />} dropdownItems={[ <DropdownItem key="pri-action3" component="button"> Primary </DropdownItem>, <DropdownItem key="sec1-action3" component="button"> Secondary </DropdownItem>, <DropdownItem key="sec2-action3" component="button"> Secondary </DropdownItem>, <DropdownItem key="sec3-action3" component="button"> Secondary </DropdownItem> ]} /> </DataListAction> <DataListAction visibility={{ default: 'hidden', xl: 'visible' }} aria-labelledby="check-action-item3 check-action-action3" id="check-action-action3" aria-label="Actions" > <Button variant="primary">Primary</Button> <Button variant="secondary">Secondary</Button> <Button variant="secondary">Secondary</Button> <Button variant="secondary">Secondary</Button> </DataListAction> </DataListItemRow> </DataListItem> </DataList> ); };
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/DescriptionListDemo/DescriptionListDemo.tsx
<reponame>jelly/patternfly-react<gh_stars>100-1000 import { Button, DescriptionList, DescriptionListDescription, DescriptionListGroup, DescriptionListTerm, DescriptionListTermHelpText, DescriptionListTermHelpTextButton, Stack, StackItem, Title, Divider, Popover } from '@patternfly/react-core'; import PlusCircleIcon from '@patternfly/react-icons/dist/esm/icons/plus-circle-icon'; import React, { Component } from 'react'; export class DescriptionListDemo extends Component { componentDidMount() { window.scrollTo(0, 0); } renderSimpleDescriptionList() { return ( <StackItem isFilled> <Title headingLevel="h2" size="2xl"> Simple Description List </Title> <Divider component="div" /> <br /> <div className="example"> <DescriptionList id="simple-description-list"> <DescriptionListGroup> <DescriptionListTerm>Name</DescriptionListTerm> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> </div> </StackItem> ); } renderDescriptionListWithHelpText() { return ( <StackItem isFilled> <Title headingLevel="h2" size="2xl"> Description List with help text </Title> <Divider component="div" /> <br /> <div className="example"> <DescriptionList id="description-list-help-text"> <DescriptionListGroup> <DescriptionListTermHelpText> <Popover headerContent={<div>Name</div>} bodyContent={<div>Additional name info</div>}> <DescriptionListTermHelpTextButton> Name </DescriptionListTermHelpTextButton> </Popover> </DescriptionListTermHelpText> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTermHelpText> <Popover headerContent={<div>Namespace</div>} bodyContent={<div>Additional namespace info</div>}> <DescriptionListTermHelpTextButton> Namespace </DescriptionListTermHelpTextButton> </Popover> </DescriptionListTermHelpText> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTermHelpText> <Popover headerContent={<div>Labels</div>} bodyContent={<div>Additional labels info</div>}> <DescriptionListTermHelpTextButton> Labels </DescriptionListTermHelpTextButton> </Popover> </DescriptionListTermHelpText> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTermHelpText> <Popover headerContent={<div>Pod selector</div>} bodyContent={<div>Additional pod selector info</div>}> <DescriptionListTermHelpTextButton> Pod selector </DescriptionListTermHelpTextButton> </Popover> </DescriptionListTermHelpText> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTermHelpText> <Popover headerContent={<div>Annotation</div>} bodyContent={<div>Additional annotation info</div>}> <DescriptionListTermHelpTextButton> Annotation </DescriptionListTermHelpTextButton> </Popover> </DescriptionListTermHelpText> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> </div> </StackItem> ); } render2ColDescriptionList() { return ( <StackItem isFilled> <br /> <Title headingLevel="h2" size="2xl"> Two Column Description List </Title> <Divider component="div" /> <br /> <div className="example"> <DescriptionList id="2-col-description-list" columnModifier={{ default: '2Col' }}> <DescriptionListGroup> <DescriptionListTerm>Name</DescriptionListTerm> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> </div> </StackItem> ); } renderResponsiveDescriptionList() { return ( <StackItem isFilled> <br /> <Title headingLevel="h2" size="2xl"> Responsive Description List </Title> <Divider component="div" /> <br /> <div className="example"> <DescriptionList id="responsive-description-list" columnModifier={{ lg: '2Col', xl: '3Col' }}> <DescriptionListGroup> <DescriptionListTerm>Name</DescriptionListTerm> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> </div> </StackItem> ); } renderHorizontalDescriptionList() { return ( <StackItem isFilled> <br /> <Title headingLevel="h2" size="2xl"> Horizontal Description List </Title> <Divider component="div" /> <br /> <div className="example"> <DescriptionList id="horizontal-description-list" isHorizontal> <DescriptionListGroup> <DescriptionListTerm>Name</DescriptionListTerm> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> </div> </StackItem> ); } renderAutoColumnWidthsDescriptionList() { return ( <StackItem isFilled> <br /> <Title headingLevel="h2" size="2xl"> Auto Column Widths Description List </Title> <Divider component="div" /> <br /> <div className="example"> <DescriptionList id="auto-col-widths-description-list" isAutoColumnWidths> <DescriptionListGroup> <DescriptionListTerm>Name</DescriptionListTerm> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> </div> </StackItem> ); } renderInlineGridDescriptionList() { return ( <StackItem isFilled> <br /> <Title headingLevel="h2" size="2xl"> Inline Grid Description List </Title> <Divider component="div" /> <br /> <div className="example"> <DescriptionList id="inline-grid-description-list" isInlineGrid> <DescriptionListGroup> <DescriptionListTerm>Name</DescriptionListTerm> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> </div> </StackItem> ); } renderAutoFitDescriptionList() { return ( <StackItem isFilled> <br /> <Title headingLevel="h2" size="2xl"> Auto Fit Description List </Title> <Divider component="div" /> <br /> <div className="example"> <DescriptionList autoFitMinModifier={{ md: '100px', lg: '150px', xl: '200px', '2xl': '300px' }} id="auto-fit-description-list" isAutoFit > <DescriptionListGroup> <DescriptionListTerm>Name</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> </div> </StackItem> ); } renderCompactDescriptionList() { return ( <StackItem isFilled> <Title headingLevel="h2" size="2xl"> Compact Description List </Title> <Divider component="div" /> <br /> <div className="example"> <DescriptionList id="compact-description-list" isCompact> <DescriptionListGroup> <DescriptionListTerm>Name</DescriptionListTerm> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> </div> </StackItem> ); } renderFluidDescriptionList() { return ( <StackItem isFilled> <Title headingLevel="h2" size="2xl"> Compact Description List </Title> <Divider component="div" /> <br /> <div className="example"> <DescriptionList id="fluid-description-list" isFluid isHorizontal> <DescriptionListGroup> <DescriptionListTerm>Name</DescriptionListTerm> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> </div> </StackItem> ); } render() { return ( <Stack hasGutter> {this.renderSimpleDescriptionList()} {this.renderDescriptionListWithHelpText()} {this.renderResponsiveDescriptionList()} {this.renderHorizontalDescriptionList()} {this.renderAutoColumnWidthsDescriptionList()} {this.renderInlineGridDescriptionList()} {this.renderAutoFitDescriptionList()} {this.renderCompactDescriptionList()} {this.renderFluidDescriptionList()} </Stack> ); } } export default DescriptionListDemo;
jelly/patternfly-react
packages/react-core/src/layouts/Split/SplitItem.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import styles from '@patternfly/react-styles/css/layouts/Split/split'; import { css } from '@patternfly/react-styles'; export interface SplitItemProps extends React.HTMLProps<HTMLDivElement> { /** Flag indicating if this Split Layout item should fill the available horizontal space. */ isFilled?: boolean; /** content rendered inside the Split Layout Item */ children?: React.ReactNode; /** additional classes added to the Split Layout Item */ className?: string; } export const SplitItem: React.FunctionComponent<SplitItemProps> = ({ isFilled = false, className = '', children = null, ...props }: SplitItemProps) => ( <div {...props} className={css(styles.splitItem, isFilled && styles.modifiers.fill, className)}> {children} </div> ); SplitItem.displayName = 'SplitItem';
jelly/patternfly-react
packages/react-topology/src/components/decorators/Decorator.tsx
import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; import SvgDropShadowFilter from '../svg/SvgDropShadowFilter'; import { createSvgIdUrl, useHover } from '../../utils'; import { DEFAULT_DECORATOR_PADDING } from '../nodes'; interface DecoratorTypes { className?: string; x: number; y: number; radius: number; padding?: number; showBackground?: boolean; icon?: React.ReactNode; onClick?(event: React.MouseEvent<SVGGElement, MouseEvent>): void; ariaLabel?: string; circleRef?: React.Ref<SVGCircleElement>; } const HOVER_FILTER_ID = 'DecoratorDropShadowHoverFilterId'; const Decorator: React.FunctionComponent<DecoratorTypes> = ({ className, x, y, showBackground, radius, padding = DEFAULT_DECORATOR_PADDING, children, icon, onClick, ariaLabel, circleRef }) => { const [hover, hoverRef] = useHover(); const iconRadius = radius - padding; return ( <g ref={hoverRef} className={css(styles.topologyNodeDecorator, className)} {...(onClick ? { onClick: e => { e.stopPropagation(); onClick(e); }, role: 'button', 'aria-label': ariaLabel } : null)} > <SvgDropShadowFilter id={HOVER_FILTER_ID} dy={3} stdDeviation={5} floodOpacity={0.5} /> {showBackground && ( <circle key={hover ? 'circle-hover' : 'circle'} // update key on hover to force update of shadow filter ref={circleRef} className={css(styles.topologyNodeDecoratorBg)} cx={x} cy={y} r={radius} filter={hover ? createSvgIdUrl(HOVER_FILTER_ID) : undefined} /> )} <g transform={`translate(${x}, ${y})`}> {icon ? ( <g className={css(styles.topologyNodeDecoratorIcon)} style={{ fontSize: `${iconRadius * 2}px` }} transform={`translate(-${iconRadius}, -${iconRadius})`} > {icon} </g> ) : null} {children} </g> </g> ); }; export default Decorator;
jelly/patternfly-react
packages/react-core/src/demos/examples/Tabs/NestedTabs.tsx
import React from 'react'; import { Card, CardHeader, CardBody, Grid, GridItem, PageSection, Tabs, Tab, TabContent, TabContentBody, TabTitleText, Title, Flex, FlexItem } from '@patternfly/react-core'; import DashboardWrapper from '../DashboardWrapper'; export const NestedTabs: React.FunctionComponent = () => { const [activeTabKey, setActiveTabKey] = React.useState(0); 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 xl={8} md={6}> <Card> <CardHeader> <Title headingLevel="h2">Status</Title> </CardHeader> <CardBody> <Flex direction={{ default: 'column' }}> <FlexItem> <Tabs activeKey={activeNestedTabKey} isSecondary onSelect={(_event, tabIndex) => handleNestedTabClick(Number(tabIndex))} id="nested-tabs-example-nested-tabs-list" > <Tab eventKey={10} title={<TabTitleText>Cluster</TabTitleText>} tabContentId={`tabContent${10}`} /> <Tab eventKey={11} title={<TabTitleText>Control plane</TabTitleText>} tabContentId={`tabContent${11}`} /> <Tab eventKey={12} title={<TabTitleText>Operators</TabTitleText>} tabContentId={`tabContent${12}`} /> <Tab eventKey={13} title={<TabTitleText>Virtualization</TabTitleText>} tabContentId={`tabContent${13}`} /> </Tabs> </FlexItem> <FlexItem> <TabContent key={10} eventKey={10} id={`tabContent${10}`} activeKey={activeNestedTabKey} hidden={10 !== activeNestedTabKey} > <TabContentBody> { 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce in odio porttitor, feugiat risus in, feugiat arcu. Nullam euismod enim eget fringilla condimentum. Maecenas tincidunt et metus id aliquet. Integer et fermentum purus. Nulla tempor velit arcu, vitae semper purus iaculis at. Sed malesuada auctor luctus. Pellentesque et leo urna. Aliquam vitae felis congue lacus mattis fringilla. Nullam et ultricies erat, sed dignissim elit. Cras mattis pulvinar aliquam. In ac est nulla. Pellentesque fermentum nibh ac sapien porta, ut congue orci aliquam. Sed nisl est, tempor eu pharetra eget, ullamcorper ut augue. Vestibulum eleifend libero eu nulla cursus lacinia.' } </TabContentBody> </TabContent> <TabContent key={11} eventKey={11} id={`tabContent${11}`} activeKey={activeNestedTabKey} hidden={11 !== activeNestedTabKey} > <TabContentBody>Control plane 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> </FlexItem> </Flex> </CardBody> </Card> </GridItem> <GridItem xl={4} md={6}> <Flex direction={{ default: 'column' }} className="pf-u-h-100"> <FlexItem flex={{ default: 'flex_1' }}> <Card isFullHeight> <CardHeader> <Title headingLevel="h2">Title of Card</Title> </CardHeader> </Card> </FlexItem> <FlexItem flex={{ default: 'flex_1' }}> <Card isFullHeight> <CardHeader> <Title headingLevel="h2">Title of Card</Title> </CardHeader> </Card> </FlexItem> </Flex> </GridItem> </Grid> ); return ( <DashboardWrapper hasPageTemplateTitle> <PageSection type="tabs" isWidthLimited> <Tabs activeKey={activeTabKey} onSelect={(_event, tabIndex) => handleTabClick(Number(tabIndex))} usePageInsets id="nested-tabs-example-tabs-list" > <Tab eventKey={0} title={<TabTitleText>Cluster 1</TabTitleText>} tabContentId={`tabContent${0}`} /> <Tab eventKey={1} title={<TabTitleText>Cluster 2</TabTitleText>} tabContentId={`tabContent${1}`} /> </Tabs> </PageSection> <PageSection isWidthLimited> <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>Cluster 2 panel</TabContentBody> </TabContent> </PageSection> </DashboardWrapper> ); };
jelly/patternfly-react
packages/react-core/src/components/ContextSelector/__tests__/ContextSelectorItem.test.tsx
<filename>packages/react-core/src/components/ContextSelector/__tests__/ContextSelectorItem.test.tsx import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { ContextSelectorItem } from '../ContextSelectorItem'; test('Renders ContextSelectorItem', () => { const { asFragment } = render( <ContextSelectorItem sendRef={jest.fn()} index={0}> My Project </ContextSelectorItem> ); expect(asFragment()).toMatchSnapshot(); }); test('Renders ContextSelectorItem disabled and hovered', () => { const { asFragment } = render( <ContextSelectorItem isDisabled sendRef={jest.fn()} index={0}> My Project </ContextSelectorItem> ); expect(asFragment()).toMatchSnapshot(); }); test('Verify onClick is called ', () => { const mockfn = jest.fn(); render( <ContextSelectorItem onClick={mockfn} sendRef={jest.fn()} index={0}> My Project </ContextSelectorItem> ); userEvent.click(screen.getByRole('button')); expect(mockfn.mock.calls).toHaveLength(1); });
jelly/patternfly-react
packages/react-topology/src/components/nodes/index.ts
export { default as DefaultNode } from './DefaultNode'; export { default as NodeShadows } from './NodeShadows'; export * from './shapes'; export * from './labels';
jelly/patternfly-react
packages/react-core/src/components/DataList/DataListDragButton.tsx
<gh_stars>100-1000 import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/DataList/data-list'; import GripVerticalIcon from '@patternfly/react-icons/dist/esm/icons/grip-vertical-icon'; import { DataListContext } from './DataList'; export interface DataListDragButtonProps extends React.HTMLProps<HTMLButtonElement> { /** Additional classes added to the drag button */ className?: string; /** Sets button type */ type?: 'button' | 'submit' | 'reset'; /** Flag indicating if drag is disabled for the item */ isDisabled?: boolean; } export const DataListDragButton: React.FunctionComponent<DataListDragButtonProps> = ({ className = '', isDisabled = false, ...props }: DataListDragButtonProps) => ( <DataListContext.Consumer> {({ dragKeyHandler }) => ( <button className={css(styles.dataListItemDraggableButton, isDisabled && styles.modifiers.disabled, className)} onKeyDown={dragKeyHandler} type="button" disabled={isDisabled} {...props} > <span className={css(styles.dataListItemDraggableIcon)}> <GripVerticalIcon /> </span> </button> )} </DataListContext.Consumer> ); DataListDragButton.displayName = 'DataListDragButton';
jelly/patternfly-react
packages/react-topology/src/components/popper/Portal.tsx
<gh_stars>0 import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { useIsomorphicLayoutEffect } from '@patternfly/react-core'; type GetContainer = Element | null | undefined | (() => Element); interface PortalProps { container?: GetContainer; } const getContainer = (container: GetContainer): Element | null | undefined => typeof container === 'function' ? container() : container; const Portal: React.FunctionComponent<PortalProps> = ({ children, container }) => { const [containerNode, setContainerNode] = React.useState<Element>(); useIsomorphicLayoutEffect(() => { setContainerNode(getContainer(container) || document.body); }, [container]); return containerNode ? ReactDOM.createPortal(children, containerNode) : null; }; export default Portal;
jelly/patternfly-react
packages/react-core/src/helpers/GenerateId/__tests__/GenerateId.test.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { render } from '@testing-library/react'; import { GenerateId } from '../GenerateId'; test('generates id', () => { const { asFragment } = render(<GenerateId>{id => <div id={id}>div with random ID</div>}</GenerateId>); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/Card/examples/CardWithImageAndActions.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { Brand, Card, CardHeader, CardHeaderMain, CardActions, CardTitle, CardBody, CardFooter, Checkbox, Dropdown, DropdownItem, DropdownSeparator, KebabToggle } from '@patternfly/react-core'; import pfLogo from './pfLogo.svg'; export const CardWithImageAndActions: React.FunctionComponent = () => { const [isOpen, setIsOpen] = React.useState<boolean>(false); const [isChecked, setIsChecked] = React.useState<boolean>(false); const [hasNoOffset, setHasNoOffset] = React.useState<boolean>(false); const onSelect = () => { setIsOpen(!isOpen); }; const onClick = (checked: boolean) => { setIsChecked(checked); }; const toggleOffset = (checked: boolean) => { setHasNoOffset(checked); }; const dropdownItems = [ <DropdownItem key="link">Link</DropdownItem>, <DropdownItem key="action" component="button"> Action </DropdownItem>, <DropdownItem key="disabled link" isDisabled> Disabled Link </DropdownItem>, <DropdownItem key="disabled action" isDisabled component="button"> Disabled Action </DropdownItem>, <DropdownSeparator key="separator" />, <DropdownItem key="separated link">Separated Link</DropdownItem>, <DropdownItem key="separated action" component="button"> Separated Action </DropdownItem> ]; return ( <> <Card> <CardHeader> <CardHeaderMain> <Brand src={pfLogo} alt="PatternFly logo" style={{ height: '50px' }} /> </CardHeaderMain> <CardActions hasNoOffset={hasNoOffset}> <Dropdown onSelect={onSelect} toggle={<KebabToggle onToggle={setIsOpen} />} isOpen={isOpen} isPlain dropdownItems={dropdownItems} position={'right'} /> <Checkbox isChecked={isChecked} onChange={onClick} aria-label="card checkbox example" id="check-1" name="check1" /> </CardActions> </CardHeader> <CardTitle>Header</CardTitle> <CardBody>Body</CardBody> <CardFooter>Footer</CardFooter> </Card> <div style={{ marginTop: '20px' }}> <Checkbox label="actions hasNoOffset" isChecked={hasNoOffset} onChange={toggleOffset} aria-label="remove actions offset" id="toggle-actions-offset" name="toggle-actions-offset" /> </div> </> ); };
jelly/patternfly-react
packages/react-core/src/components/Card/examples/CardOnlyImageInCardHead.tsx
import React from 'react'; import { Brand, Card, CardBody, CardFooter, CardHeader, CardHeaderMain, CardTitle } from '@patternfly/react-core'; import pfLogo from './pfLogo.svg'; export const CardOnlyImageInCardHead: React.FunctionComponent = () => ( <Card> <CardHeader> <CardHeaderMain> <Brand src={pfLogo} alt="PatternFly logo" style={{ height: '50px' }} /> </CardHeaderMain> </CardHeader> <CardTitle>Header</CardTitle> <CardBody>Body</CardBody> <CardFooter>Footer</CardFooter> </Card> );
jelly/patternfly-react
packages/react-core/src/components/Form/Form.tsx
<gh_stars>0 import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Form/form'; import { css } from '@patternfly/react-styles'; export interface FormProps extends React.HTMLProps<HTMLFormElement> { /** Anything that can be rendered as Form content. */ children?: React.ReactNode; /** Additional classes added to the Form. */ className?: string; /** Sets the Form to horizontal. */ isHorizontal?: boolean; /** Limits the max-width of the form. */ isWidthLimited?: boolean; /** Sets a custom max-width for the form. */ maxWidth?: string; } export const Form: React.FunctionComponent<FormProps> = ({ children = null, className = '', isHorizontal = false, isWidthLimited = false, maxWidth = '', ...props }: FormProps) => ( <form noValidate {...(maxWidth && { style: { '--pf-c-form--m-limit-width--MaxWidth': maxWidth, ...props.style } as React.CSSProperties })} {...props} className={css( styles.form, isHorizontal && styles.modifiers.horizontal, (isWidthLimited || maxWidth) && styles.modifiers.limitWidth, className )} > {children} </form> ); Form.displayName = 'Form';
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/ToolbarDemo/ToolbarVisibilityDemo.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 ToolbarVisibilityDemo extends React.Component { static displayName = 'ToolbarVisibilityDemo'; render() { const toolbarContents = ( <React.Fragment> <ToolbarContent visibility={{ default: 'visible', md: 'hidden' }}>ToolbarContent visibility sm</ToolbarContent> <ToolbarContent visibility={{ default: 'hidden', md: 'visible', lg: 'hidden' }}> ToolbarContent visibility md </ToolbarContent> <ToolbarContent visibility={{ default: 'hidden', lg: 'visible', xl: 'hidden' }}> ToolbarContent visibility lg </ToolbarContent> <ToolbarContent visibility={{ default: 'hidden', xl: 'visible', '2xl': 'hidden' }}> ToolbarContent visibility xl </ToolbarContent> <ToolbarContent visibility={{ default: 'hidden', '2xl': 'visible' }}> ToolbarContent visibility 2xl </ToolbarContent> </React.Fragment> ); const toolbarGroups = ( <React.Fragment> <ToolbarGroup visibility={{ default: 'visible', md: 'hidden' }}>ToolbarGroup visibility sm</ToolbarGroup> <ToolbarGroup visibility={{ default: 'hidden', md: 'visible', lg: 'hidden' }}> ToolbarGroup visibility md </ToolbarGroup> <ToolbarGroup visibility={{ default: 'hidden', lg: 'visible', xl: 'hidden' }}> ToolbarGroup visibility lg </ToolbarGroup> <ToolbarGroup visibility={{ default: 'hidden', xl: 'visible', '2xl': 'hidden' }}> ToolbarGroup visibility xl </ToolbarGroup> <ToolbarGroup visibility={{ default: 'hidden', '2xl': 'visible' }}>ToolbarGroup visibility 2xl</ToolbarGroup> </React.Fragment> ); const toolbarItems = ( <React.Fragment> <ToolbarItem visibility={{ default: 'visible', md: 'hidden' }}>ToolbarItem visibility sm</ToolbarItem> <ToolbarItem visibility={{ default: 'hidden', md: 'visible', lg: 'hidden' }}> ToolbarItem visibility md </ToolbarItem> <ToolbarItem visibility={{ default: 'hidden', lg: 'visible', xl: 'hidden' }}> ToolbarItem visibility lg </ToolbarItem> <ToolbarItem visibility={{ default: 'hidden', xl: 'visible', '2xl': 'hidden' }}> ToolbarItem visibility xl </ToolbarItem> <ToolbarItem visibility={{ default: 'hidden', '2xl': 'visible' }}>ToolbarItem visibility 2xl</ToolbarItem> </React.Fragment> ); const toolbarToggleGroups = ( <React.Fragment> <Toolbar> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="md" visibility={{ default: 'visible', md: 'hidden' }} > ToolbarToggleGroup visibility sm </ToolbarToggleGroup> </ToolbarContent> </Toolbar> <Toolbar> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="lg" visibility={{ default: 'hidden', md: 'visible', lg: 'hidden' }} > ToolbarToggleGroup visibility md </ToolbarToggleGroup> </ToolbarContent> </Toolbar> <Toolbar> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="xl" visibility={{ default: 'hidden', lg: 'visible', xl: 'hidden' }} > ToolbarToggleGroup visibility lg </ToolbarToggleGroup> </ToolbarContent> </Toolbar> <Toolbar> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="2xl" visibility={{ default: 'hidden', xl: 'visible', '2xl': 'hidden' }} > ToolbarToggleGroup visibility xl </ToolbarToggleGroup> </ToolbarContent> </Toolbar> <Toolbar> <ToolbarContent> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="md" visibility={{ default: 'hidden', '2xl': 'visible' }} > ToolbarToggleGroup visibility 2xl </ToolbarToggleGroup> </ToolbarContent> </Toolbar> </React.Fragment> ); return ( <div id="toolbar-visibility-demo"> <Toolbar>{toolbarContents}</Toolbar> <Toolbar> <ToolbarContent>{toolbarGroups}</ToolbarContent> </Toolbar> <Toolbar> <ToolbarContent>{toolbarItems}</ToolbarContent> </Toolbar> {toolbarToggleGroups} </div> ); } }
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/styles/donut-styles.ts
<reponame>jelly/patternfly-react /* eslint-disable camelcase */ import chart_global_FontSize_sm from '@patternfly/react-tokens/dist/esm/chart_global_FontSize_sm'; import chart_global_FontSize_2xl from '@patternfly/react-tokens/dist/esm/chart_global_FontSize_2xl'; import chart_donut_label_subtitle_Fill from '@patternfly/react-tokens/dist/esm/chart_donut_label_subtitle_Fill'; import chart_donut_label_subtitle_position from '@patternfly/react-tokens/dist/esm/chart_donut_label_subtitle_position'; // Donut styles export const DonutStyles = { label: { subTitle: { // Victory props only fill: chart_donut_label_subtitle_Fill.value, fontSize: chart_global_FontSize_sm.value }, subTitlePosition: chart_donut_label_subtitle_position.value, title: { // Victory props only fontSize: chart_global_FontSize_2xl.value } } };
jelly/patternfly-react
packages/react-inline-edit-extension/src/components/InlineEdit/editableRowWrapper.tsx
<filename>packages/react-inline-edit-extension/src/components/InlineEdit/editableRowWrapper.tsx<gh_stars>100-1000 import * as React from 'react'; import { createPortal } from 'react-dom'; import { css } from '@patternfly/react-styles'; import { RowWrapper, RowWrapperRow } from '@patternfly/react-table'; import { shallowLeftSideEquals, getBoundingClientRect, getClientWindowDimensions, WindowDimensions, ClientBoundingRect } from '../../utils/utils'; import { inlineEditStyles as styles } from './css/inline-edit-css'; import { ConfirmButtons } from '../ConfirmButtons'; import { EditConfig } from '../Body'; import '@patternfly/react-styles/css/components/Table/inline-edit.css'; export interface EditableRowWrapperRow extends RowWrapperRow { isEditing?: boolean; isTableEditing?: boolean; isFirstVisible?: boolean; isLastVisible?: boolean; isChildEditing?: boolean; isParentEditing?: boolean; isLastVisibleParent?: boolean; editConfig?: EditConfig; } export interface EditableRowWrapperProps extends RowWrapper { className?: string; row: EditableRowWrapperRow; trRef: (instance: any) => void; onScroll: (event: React.UIEvent<Element>) => void; onResize: (event: React.UIEvent<Element>) => void; rowProps: { rowIndex: number; rowKey: string; }; } // TableEditConfirmation constants like TABLE_TOP cannot be referenced but must be hardcoded due to this issue: // https://github.com/reactjs/react-docgen/issues/317#issue-393678795 const tableConfirmationMapper = { TABLE_TOP: { hasConfirmationButtons: ({ isTableEditing, isFirstVisible }: EditableRowWrapperRow) => isTableEditing && isFirstVisible, isTableConfirmation: () => true, areButtonsOnTop: () => true, hasBoldBorder: () => true, getEditStyles: ({ isTableEditing, isFirstVisible }: EditableRowWrapperRow) => css(styles.tableEditableRow, isTableEditing && isFirstVisible && styles.modifiers.tableEditingFirstRow) }, TABLE_BOTTOM: { hasConfirmationButtons: ({ isTableEditing, isLastVisible }: EditableRowWrapperRow) => isTableEditing && isLastVisible, isTableConfirmation: () => true, areButtonsOnTop: () => false, hasBoldBorder: () => true, getEditStyles: ({ isTableEditing, isLastVisible }: EditableRowWrapperRow) => css(styles.tableEditableRow, isTableEditing && isLastVisible && styles.modifiers.tableEditingLastRow) }, ROW: { hasConfirmationButtons: ({ isEditing, isParentEditing, isLastVisibleParent, isChildEditing, isLastVisible }: EditableRowWrapperRow) => isEditing && !(isChildEditing && isParentEditing) && // buttons can't appear in the middle !(isParentEditing && isLastVisible) && // parent will show the buttons on top !(isChildEditing && !isLastVisibleParent), // child will show the buttons on bottom isTableConfirmation: () => false, areButtonsOnTop: ({ isLastVisible, isLastVisibleParent }: EditableRowWrapperRow) => isLastVisible || isLastVisibleParent, hasBoldBorder: () => false, getEditStyles: ({ isEditing }: EditableRowWrapperRow) => css(styles.tableEditableRow, isEditing && styles.modifiers.editing) }, NO_CONFIRM_ROW: { hasConfirmationButtons: () => false, isTableConfirmation: () => false, areButtonsOnTop: () => false, hasBoldBorder: () => false, getEditStyles: ({ isEditing }: EditableRowWrapperRow) => css(styles.tableEditableRow, isEditing && styles.modifiers.editing) }, NONE: { hasConfirmationButtons: () => false, isTableConfirmation: () => false, areButtonsOnTop: () => false, hasBoldBorder: () => false, getEditStyles: () => css(styles.tableEditableRow) } }; const getTableConfirmation = ({ editConfig }: EditableRowWrapperRow) => (editConfig && tableConfirmationMapper[editConfig.editConfirmationType as keyof typeof tableConfirmationMapper]) || tableConfirmationMapper.NONE; interface EditableRowWrapperState { hasConfirmationButtons?: boolean; window?: WindowDimensions; rowDimensions?: ClientBoundingRect; } export const editableRowWrapper = (RowWrapperComponent: typeof RowWrapper) => class EditableRowWrapper extends React.Component<EditableRowWrapperProps, EditableRowWrapperState> { state = { hasConfirmationButtons: false, window: undefined as WindowDimensions, rowDimensions: undefined as ClientBoundingRect, ...EditableRowWrapper.getDerivedStateFromProps(this.props) }; element = React.createRef<HTMLTableRowElement>(); tableElem: HTMLElement; static defaultProps = { onScroll: () => {}, onResize: () => {} }; static getDerivedStateFromProps = (props: EditableRowWrapperProps) => ({ hasConfirmationButtons: getTableConfirmation(props.row).hasConfirmationButtons(props.row) }); setStateWith2dEquals = (newState: EditableRowWrapperState) => { this.setState(oldState => Object.keys(newState).find( key => !shallowLeftSideEquals( newState[key as keyof EditableRowWrapperState], oldState[key as keyof EditableRowWrapperState] ) ) ? newState : null ); }; componentDidMount() { this.tableElem = this.element.current.closest('table'); if (typeof this.props.trRef === 'function') { this.props.trRef(this.element.current); } this.updateRowDimensions(); if (this.state.hasConfirmationButtons) { this.fetchClientDimensions(); } } updateRowDimensions = () => { if (this.element.current) { this.setStateWith2dEquals({ rowDimensions: getBoundingClientRect(this.element.current) }); } }; handleScroll = () => { this.updateRowDimensions(); }; handleResize = () => { this.fetchClientDimensions(); this.updateRowDimensions(); }; fetchClientDimensions() { this.setStateWith2dEquals({ window: getClientWindowDimensions() }); } getConfirmationButtons() { const { row, rowProps, ...props } = this.props; const { isLastVisible, isParentEditing, isLastVisibleParent, editConfig } = row; if (!editConfig) { return null; } const { onEditConfirmed, onEditCanceled } = editConfig; const tableConfirmation = getTableConfirmation(row); let confirmButtons; if (this.element.current && this.state.rowDimensions) { const options = tableConfirmation.isTableConfirmation() ? {} : rowProps; const actionObject = tableConfirmation.isTableConfirmation() ? null : row; confirmButtons = createPortal( <ConfirmButtons {...props} onConfirm={event => onEditConfirmed(event, actionObject, options)} onCancel={event => onEditCanceled(event, actionObject, options)} buttonsOnTop={tableConfirmation.areButtonsOnTop({ isLastVisible, isParentEditing, isLastVisibleParent })} boldBorder={tableConfirmation.hasBoldBorder()} environment={{ window: this.state.window, row: getBoundingClientRect(this.element.current) }} />, this.tableElem ? (this.tableElem.parentNode as HTMLElement) : document.body ); } return confirmButtons; } render() { const { className, onScroll, onResize, row: { isFirstVisible, isLastVisible, isEditing, isTableEditing, editConfig } } = this.props; const { hasConfirmationButtons } = this.state; const trClassName = getTableConfirmation({ editConfig }).getEditStyles({ isEditing, isTableEditing, isFirstVisible, isLastVisible }); return ( <React.Fragment> <RowWrapperComponent {...this.props} trRef={this.element} className={css(trClassName, className)} onScroll={event => { if (hasConfirmationButtons) { this.handleScroll(); } onScroll(event); }} onResize={event => { if (hasConfirmationButtons) { this.handleResize(); } onResize(event); }} /> {hasConfirmationButtons && this.getConfirmationButtons()} </React.Fragment> ); } };
jelly/patternfly-react
packages/react-integration/cypress/integration/alert.spec.ts
<reponame>jelly/patternfly-react describe('Alert Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/alert-demo-nav-link'); }); it('Verify alerts close', () => { cy.get('#test-button-1').click(); cy.get('#test-button-2').click(); cy.get('#info-alert').should('not.exist'); }); it('Verify truncateTitle and no tooltip on short text', () => { cy.get('#default-alert > .pf-c-alert__title') .should('have.class', 'pf-m-truncate') .then((noTooltipLink: JQuery<HTMLDivElement>) => { cy.wrap(noTooltipLink) .trigger('mouseenter') .get('.pf-c-tooltip') .should('not.exist'); cy.wrap(noTooltipLink).trigger('mouseleave'); }); }); it('Verify truncateTitle alert and tooltip', () => { cy.get('#long-title-alert > .pf-c-alert__title') .should('have.class', 'pf-m-truncate') .then((tooltipLink: JQuery<HTMLDivElement>) => { cy.get('.pf-c-tooltip').should('not.exist'); cy.wrap(tooltipLink) .trigger('mouseenter') .get('.pf-c-tooltip') .should('exist'); cy.wrap(tooltipLink).trigger('mouseleave'); }); }); it('Verify expandable alert', () => { cy.get('#expandable-alert') .should('have.class', 'pf-m-expandable') .should('not.have.class', 'pf-m-expanded') .within(() => { cy.get('.pf-c-alert__description').should('not.exist'); cy.get('.pf-c-alert__toggle').click(); cy.get('.pf-c-alert__description').should('exist'); cy.root().should('have.class', 'pf-m-expanded'); cy.get('.pf-c-alert__toggle').click(); cy.get('.pf-c-alert__description').should('not.exist'); cy.root().should('not.have.class', 'pf-m-expanded'); }); }); });
jelly/patternfly-react
packages/react-inline-edit-extension/src/components/InlineEdit/css/inline-edit-css.ts
export const inlineEditStyles = { tableEditableRow: 'pf-c-table__editable-row', tableInlineEditButtons: 'pf-c-table__inline-edit-buttons', modifiers: { tableEditingFirstRow: 'pf-m-table-editing-first-row ', tableEditingLastRow: 'pf-m-table-editing-last-row', editing: 'pf-m-editing', top: 'pf-m-top', bottom: 'pf-m-bottom', bold: 'pf-m-bold' } };
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/modifiers/arrow.ts
// @ts-nocheck import { Modifier, ModifierArguments, Padding } from '../types'; import getBasePlacement from '../utils/getBasePlacement'; import getLayoutRect from '../dom-utils/getLayoutRect'; import contains from '../dom-utils/contains'; import getOffsetParent from '../dom-utils/getOffsetParent'; import getMainAxisFromPlacement from '../utils/getMainAxisFromPlacement'; import within from '../utils/within'; import mergePaddingObject from '../utils/mergePaddingObject'; import expandToHashMap from '../utils/expandToHashMap'; import { left, right, basePlacements, top, bottom } from '../enums'; import { isHTMLElement } from '../dom-utils/instanceOf'; // eslint-disable-next-line import/no-unused-modules export interface Options { element: HTMLElement | string | null; padding: Padding; } /** * */ function arrow({ state, name }: ModifierArguments<Options>) { const arrowElement = state.elements.arrow; const popperOffsets = state.modifiersData.popperOffsets; const basePlacement = getBasePlacement(state.placement); const axis = getMainAxisFromPlacement(basePlacement); const isVertical = [left, right].indexOf(basePlacement) >= 0; const len = isVertical ? 'height' : 'width'; if (!arrowElement || !popperOffsets) { return; } const paddingObject = state.modifiersData[`${name}#persistent`].padding; const arrowRect = getLayoutRect(arrowElement); const minProp = axis === 'y' ? top : left; const maxProp = axis === 'y' ? bottom : right; const endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len]; const startDiff = popperOffsets[axis] - state.rects.reference[axis]; const arrowOffsetParent = getOffsetParent(arrowElement); const clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; const centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is // outside of the popper bounds const min = paddingObject[minProp]; const max = clientSize - arrowRect[len] - paddingObject[maxProp]; const center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; const offset = within(min, center, max); // Prevents breaking syntax highlighting... const axisProp: string = axis; state.modifiersData[name] = { [axisProp]: offset, centerOffset: offset - center }; } /** * */ function effect({ state, options, name }: ModifierArguments<Options>) { let { element: arrowElement = '[data-popper-arrow]', padding = 0 } = options; if (arrowElement == null) { return; } // CSS selector if (typeof arrowElement === 'string') { arrowElement = state.elements.popper.querySelector(arrowElement); if (!arrowElement) { return; } } if (false /* __DEV__*/) { if (!isHTMLElement(arrowElement)) { console.error( [ 'Popper: "arrow" element must be an HTMLElement (not an SVGElement).', 'To use an SVG arrow, wrap it in an HTMLElement that will be used as', 'the arrow.' ].join(' ') ); } } if (!contains(state.elements.popper, arrowElement)) { if (false /* __DEV__*/) { console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper', 'element.'].join(' ')); } return; } state.elements.arrow = arrowElement; state.modifiersData[`${name}#persistent`] = { padding: mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements)) }; } // eslint-disable-next-line import/no-unused-modules export type ArrowModifier = Modifier<'arrow', Options>; export default { name: 'arrow', enabled: true, phase: 'main', fn: arrow, effect, requires: ['popperOffsets'], requiresIfExists: ['preventOverflow'] } as ArrowModifier;
jelly/patternfly-react
packages/react-core/src/components/DatePicker/examples/DatePickerFrench.tsx
import React from 'react'; import { DatePicker, Weekday } from '@patternfly/react-core'; export const DatePickerFrench: React.FunctionComponent = () => { const minDate = new Date(2020, 2, 16); const maxDate = new Date(2020, 2, 20); const rangeValidator = (date: Date) => { if (date < minDate) { return 'Cette date est antérieure à la première date valide.'; } else if (date > maxDate) { return 'Cette date est postérieure à la dernière date valide.'; } return ''; }; return ( <DatePicker value="2020-03-17" validators={[rangeValidator]} placeholder="aaaa-mm-jj" invalidFormatText="Cette date est invalide." locale="fr" weekStart={Weekday.Monday} /> ); };
jelly/patternfly-react
packages/react-charts/src/components/ChartContainer/index.ts
<gh_stars>100-1000 export * from './ChartContainer';
jelly/patternfly-react
packages/react-charts/src/components/ChartBullet/ChartBulletPrimaryDotMeasure.test.tsx
<gh_stars>0 import * as React from 'react'; import { render } from '@testing-library/react'; import { ChartBulletPrimaryDotMeasure } from './ChartBulletPrimaryDotMeasure'; Object.values([true, false]).forEach(() => { test('ChartBulletPrimaryDotMeasure', () => { const { asFragment } = render(<ChartBulletPrimaryDotMeasure />); expect(asFragment()).toMatchSnapshot(); }); }); test('renders component data', () => { const { asFragment } = render( <ChartBulletPrimaryDotMeasure data={[{ y: 50 }, { y: 85 }, { y: 150 }]} domain={{ x: [0, 200] }} /> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-integration/cypress/integration/alerttimeoutclosebutton.spec.ts
describe('Alert Demo Test', () => { it('Verify alert closes when clicked if timeout is set', () => { cy.clock(); cy.visit('http://localhost:3000/alert-timeout-close-button-demo-nav-link'); cy.get('#alert-custom-timeout').should('not.exist'); cy.get('#close-button-alert-button').click(); cy.get('#close-button-alert').should('exist'); cy.tick(8000); cy.get('#close-button-alert').should('exist'); cy.get('#test-close-button').click(); cy.get('#close-button-alert').should('not.exist'); }); });
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/styles/common-styles.ts
<filename>packages/react-charts/src/components/ChartTheme/styles/common-styles.ts /* eslint-disable camelcase */ import chart_global_FontFamily from '@patternfly/react-tokens/dist/esm/chart_global_FontFamily'; import chart_global_FontSize_sm from '@patternfly/react-tokens/dist/esm/chart_global_FontSize_sm'; import chart_global_label_Margin from '@patternfly/react-tokens/dist/esm/chart_global_label_Margin'; import chart_global_letter_spacing from '@patternfly/react-tokens/dist/esm/chart_global_letter_spacing'; import chart_legend_Margin from '@patternfly/react-tokens/dist/esm/chart_legend_Margin'; import chart_legend_position from '@patternfly/react-tokens/dist/esm/chart_legend_position'; // Typography const TYPOGRAPHY_FONT_FAMILY = chart_global_FontFamily.var; const TYPOGRAPHY_LETTER_SPACING = chart_global_letter_spacing.var; const TYPOGRAPHY_FONT_SIZE = chart_global_FontSize_sm.value; export const CommonStyles = { label: { fontFamily: TYPOGRAPHY_FONT_FAMILY, fontSize: TYPOGRAPHY_FONT_SIZE, letterSpacing: TYPOGRAPHY_LETTER_SPACING, margin: chart_global_label_Margin.value }, legend: { margin: chart_legend_Margin.value, position: chart_legend_position.value } };
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TabsDemo/TabsExpandableDemo.tsx
<reponame>jelly/patternfly-react import { Tabs, Tab, TabTitleText } from '@patternfly/react-core'; import React, { Component } from 'react'; export class TabsExpandableDemo extends Component { state = { activeTabKeyControlled: 0, activeTabKeyUncontrolled: 0, activeTabKeyBreakpoint1: 0, activeTabKeyBreakpoint2: 0, activeTabKeyBreakpoint3: 0, isExpandedControlled: false, isExpandedBreakpoint1: false, isExpandedBreakpoint2: false, isExpandedBreakpoint3: false }; // Toggle currently active tab private handleTabClickControlled = (_event: React.MouseEvent<HTMLElement, MouseEvent>, tabIndex: number | string) => { this.setState({ activeTabKey: tabIndex }); }; private handleTabClickUncontrolled = ( _event: React.MouseEvent<HTMLElement, MouseEvent>, tabIndex: number | string ) => { this.setState({ activeTabKeyUncontrolled: tabIndex }); }; private handleTabClickBreakpoint1 = ( _event: React.MouseEvent<HTMLElement, MouseEvent>, tabIndex: number | string ) => { this.setState({ activeTabKeyBreakpoint1: tabIndex }); }; private handleTabClickBreakpoint2 = ( _event: React.MouseEvent<HTMLElement, MouseEvent>, tabIndex: number | string ) => { this.setState({ activeTabKeyBreakpoint2: tabIndex }); }; private handleTabClickBreakpoint3 = ( _event: React.MouseEvent<HTMLElement, MouseEvent>, tabIndex: number | string ) => { this.setState({ activeTabKeyBreakpoint3: tabIndex }); }; // Toggle Expandable tabs private onToggleControlled = (isExpanded: boolean) => { this.setState({ isExpandedControlled: isExpanded }); }; private onToggleBreakpoint1 = (isExpanded: boolean) => { this.setState({ isExpandedBreakpoint1: isExpanded }); }; private onToggleBreakpoint2 = (isExpanded: boolean) => { this.setState({ isExpandedBreakpoint2: isExpanded }); }; private onToggleBreakpoint3 = (isExpanded: boolean) => { this.setState({ isExpandedBreakpoint3: isExpanded }); }; componentDidMount() { window.scrollTo(0, 0); } render() { return ( <React.Fragment> <div> <Tabs id="expandable-controlled" activeKey={this.state.activeTabKeyControlled} isVertical isExpanded={this.state.isExpandedControlled} toggleText="Tabs controlled" expandable={{ default: 'expandable' }} onToggle={this.onToggleControlled} onSelect={this.handleTabClickControlled} > <Tab eventKey={0} title={<TabTitleText>Users</TabTitleText>}> Users </Tab> <Tab eventKey={1} title={<TabTitleText>Containers</TabTitleText>}> Containers </Tab> <Tab eventKey={2} title={<TabTitleText>Database</TabTitleText>}> Database </Tab> </Tabs> </div> <div> <Tabs id="expandable-uncontrolled" activeKey={this.state.activeTabKeyUncontrolled} isVertical toggleAriaLabel="Tabs uncontrolled" expandable={{ default: 'expandable' }} defaultIsExpanded={false} onSelect={this.handleTabClickUncontrolled} > <Tab eventKey={0} title={<TabTitleText>Users</TabTitleText>}> Users </Tab> <Tab eventKey={1} title={<TabTitleText>Containers</TabTitleText>}> Containers </Tab> <Tab eventKey={2} title={<TabTitleText>Database</TabTitleText>}> Database </Tab> </Tabs> </div> <div> <Tabs id="expandable-breakpoints1" activeKey={this.state.activeTabKeyBreakpoint1} isVertical isExpanded={this.state.isExpandedBreakpoint1} toggleText="Tabs expand on breakpoints" expandable={{ sm: 'expandable', md: 'expandable', lg: 'expandable', xl: 'expandable', '2xl': 'expandable' }} onToggle={this.onToggleBreakpoint1} onSelect={this.handleTabClickBreakpoint1} > <Tab eventKey={0} title={<TabTitleText>Users</TabTitleText>}> Users </Tab> <Tab eventKey={1} title={<TabTitleText>Containers</TabTitleText>}> Containers </Tab> <Tab eventKey={2} title={<TabTitleText>Database</TabTitleText>}> Database </Tab> </Tabs> </div> <div> <Tabs id="expandable-breakpoints2" activeKey={this.state.activeTabKeyBreakpoint2} isVertical toggleText="Tabs expand on breakpoints 2" isExpanded={this.state.isExpandedBreakpoint2} expandable={{ default: 'expandable', sm: 'nonExpandable', md: 'nonExpandable', xl: 'nonExpandable', '2xl': 'nonExpandable' }} onToggle={this.onToggleBreakpoint2} onSelect={this.handleTabClickBreakpoint2} > <Tab eventKey={0} title={<TabTitleText>Users</TabTitleText>}> Users </Tab> <Tab eventKey={1} title={<TabTitleText>Containers</TabTitleText>}> Containers </Tab> <Tab eventKey={2} title={<TabTitleText>Database</TabTitleText>}> Database </Tab> </Tabs> </div> <div> <Tabs id="expandable-breakpoints3" activeKey={this.state.activeTabKeyBreakpoint2} isVertical isExpanded={this.state.isExpandedBreakpoint3} toggleText="Tabs expand on breakpoints 3" expandable={{ default: 'nonExpandable', lg: 'nonExpandable', xl: 'expandable' }} onToggle={this.onToggleBreakpoint3} onSelect={this.handleTabClickBreakpoint3} > <Tab eventKey={0} title={<TabTitleText>Users</TabTitleText>}> Users </Tab> <Tab eventKey={1} title={<TabTitleText>Containers</TabTitleText>}> Containers </Tab> <Tab eventKey={2} title={<TabTitleText>Database</TabTitleText>}> Database </Tab> </Tabs> </div> </React.Fragment> ); } }
jelly/patternfly-react
packages/react-core/src/components/Radio/__tests__/Radio.test.tsx
<gh_stars>0 import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Radio } from '../Radio'; const props = { onChange: jest.fn() }; describe('Radio', () => { test('controlled', () => { const { asFragment } = render(<Radio isChecked id="check" aria-label="check" name="check" />); expect(asFragment()).toMatchSnapshot(); }); test('uncontrolled', () => { const { asFragment } = render(<Radio id="check" aria-label="check" name="check" />); expect(asFragment()).toMatchSnapshot(); }); test('isDisabled', () => { const { asFragment } = render(<Radio id="check" isDisabled aria-label="check" name="check" />); expect(asFragment()).toMatchSnapshot(); }); test('isLabelBeforeButton', () => { const { asFragment } = render( <Radio id="check" isLabelBeforeButton label="Radio label" aria-label="check" name="check" /> ); expect(asFragment()).toMatchSnapshot(); }); test('isLabelWrapped', () => { const { asFragment } = render( <Radio id="check" isLabelWrapped label="Radio label" aria-label="check" name="check" /> ); expect(asFragment()).toMatchSnapshot(); }); test('label is string', () => { const { asFragment } = render(<Radio label="Label" id="check" isChecked aria-label="check" name="check" />); expect(asFragment()).toMatchSnapshot(); }); test('label is function', () => { const functionLabel = () => <h1>Header</h1>; const { asFragment } = render( <Radio label={functionLabel()} id="check" isChecked aria-label="check" name="check" /> ); expect(asFragment()).toMatchSnapshot(); }); test('label is node', () => { const { asFragment } = render( <Radio label={<h1>Header</h1>} id="check" isChecked aria-label="check" name="check" /> ); expect(asFragment()).toMatchSnapshot(); }); test('passing class', () => { const { asFragment } = render( <Radio label="label" className="class-123" id="check" isChecked aria-label="check" name="check" /> ); expect(asFragment()).toMatchSnapshot(); }); test('passing HTML attribute', () => { const { asFragment } = render( <Radio label="label" aria-labelledby="labelId" id="check" isChecked aria-label="check" name="check" /> ); expect(asFragment()).toMatchSnapshot(); }); test('Radio passes value and event to onChange handler', () => { render(<Radio id="check" {...props} aria-label="check" name="check" />); userEvent.click(screen.getByRole('radio')); expect(props.onChange).toHaveBeenCalledWith(true, expect.any(Object)); }); test('Radio description', () => { render(<Radio id="check" name="check" aria-label="check" description="Text description..." />); expect(screen.getByText('Text description...')).toBeInTheDocument(); }); test('Radio body', () => { render(<Radio id="check" name="check" aria-label="check" body="Text body..." />); expect(screen.getByText('Text body...')).toBeInTheDocument(); }); test('should throw console error when no id is given', () => { const myMock = jest.fn(); global.console = { ...global.console, error: myMock }; render(<Radio id={undefined} name="check" aria-label="check" description="Text description..." />); expect(myMock).toHaveBeenCalled(); }); });
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/shapesComponentFactory.ts
import { ComponentType } from 'react'; import { GraphElement, ComponentFactory, ModelKind } from '@patternfly/react-topology'; import DemoDefaultNode from './DemoDefaultNode'; import CustomPathNode from './CustomPathNode'; import CustomPolygonNode from './CustomPolygonNode'; const shapesComponentFactory: ComponentFactory = ( kind: ModelKind, type: string ): ComponentType<{ element: GraphElement }> | undefined => { switch (type) { case 'node': return DemoDefaultNode; case 'node-path': return CustomPathNode; case 'node-polygon': return CustomPolygonNode; default: return undefined; } }; export default shapesComponentFactory;
jelly/patternfly-react
packages/react-core/src/components/Form/__tests__/Form.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { Form } from '../Form'; describe('Form component', () => { test('should render default form variant', () => { const { asFragment } = render(<Form />); expect(asFragment()).toMatchSnapshot(); }); test('should render horizontal form variant', () => { const { asFragment } = render(<Form isHorizontal />); expect(asFragment()).toMatchSnapshot(); }); test('should render form with limited width', () => { const { asFragment } = render(<Form isWidthLimited />); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/__tests__/MultipleFileUploadMain.test.tsx
<reponame>jelly/patternfly-react<gh_stars>0 import React from 'react'; import { render } from '@testing-library/react'; import { MultipleFileUploadMain } from '../MultipleFileUploadMain'; describe('MultipleFileUploadMain', () => { test('renders with expected class names', () => { const { asFragment } = render(<MultipleFileUploadMain />); expect(asFragment()).toMatchSnapshot(); }); test('renders custom class names', () => { const { asFragment } = render(<MultipleFileUploadMain className="test" />); expect(asFragment()).toMatchSnapshot(); }); test('passes props to the title as expected', () => { const { asFragment } = render( <MultipleFileUploadMain titleIcon="icon" titleText="title text" titleTextSeparator="title test separator" /> ); expect(asFragment()).toMatchSnapshot(); }); test('renders without the button when expected', () => { const { asFragment } = render(<MultipleFileUploadMain isUploadButtonHidden />); expect(asFragment()).toMatchSnapshot(); }); test('passes props to the info component as expected', () => { const { asFragment } = render(<MultipleFileUploadMain infoText="info text" />); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-topology/src/components/edges/DefaultEdge.tsx
<gh_stars>0 import * as React from 'react'; import * as _ from 'lodash'; import { observer } from 'mobx-react'; import { Edge, EdgeTerminalType, NodeStatus } from '../../types'; import { WithContextMenuProps, WithRemoveConnectorProps, WithSelectionProps, WithSourceDragProps, WithTargetDragProps } from '../../behavior'; import { useHover } from '../../utils'; import { Layer } from '../layers'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; import { getEdgeAnimationDuration, getEdgeStyleClassModifier } from '../../utils/style-utils'; import DefaultConnectorTerminal from './terminals/DefaultConnectorTerminal'; import { TOP_LAYER } from '../../const'; import DefaultConnectorTag from './DefaultConnectorTag'; import { Point } from '../../geom'; import { getConnectorStartPoint } from './terminals/terminalUtils'; type BaseEdgeProps = { element: Edge; dragging?: boolean; className?: string; animationDuration?: number; startTerminalType?: EdgeTerminalType; startTerminalClass?: string; startTerminalStatus?: NodeStatus; startTerminalSize?: number; endTerminalType?: EdgeTerminalType; endTerminalClass?: string; endTerminalStatus?: NodeStatus; endTerminalSize?: number; tag?: string; tagClass?: string; tagStatus?: NodeStatus; } & Partial< WithRemoveConnectorProps & WithSourceDragProps & WithTargetDragProps & WithSelectionProps & WithContextMenuProps >; const BaseEdge: React.FunctionComponent<BaseEdgeProps> = ({ element, dragging, sourceDragRef, targetDragRef, animationDuration, onShowRemoveConnector, onHideRemoveConnector, startTerminalType = EdgeTerminalType.none, startTerminalClass, startTerminalStatus, startTerminalSize = 14, endTerminalType = EdgeTerminalType.directional, endTerminalClass, endTerminalStatus, endTerminalSize = 14, tag, tagClass, tagStatus, children, className, selected, onSelect, onContextMenu }) => { const [hover, hoverRef] = useHover(); const startPoint = element.getStartPoint(); const endPoint = element.getEndPoint(); // eslint-disable-next-line patternfly-react/no-layout-effect React.useLayoutEffect(() => { if (hover && !dragging) { onShowRemoveConnector && onShowRemoveConnector(); } else { onHideRemoveConnector && onHideRemoveConnector(); } }, [hover, dragging, onShowRemoveConnector, onHideRemoveConnector]); const groupClassName = css( styles.topologyEdge, className, dragging && 'pf-m-dragging', hover && !dragging && 'pf-m-hover', selected && !dragging && 'pf-m-selected' ); const edgeAnimationDuration = animationDuration ?? getEdgeAnimationDuration(element.getEdgeAnimationSpeed()); const linkClassName = css(styles.topologyEdgeLink, getEdgeStyleClassModifier(element.getEdgeStyle())); const bendpoints = element.getBendpoints(); const d = `M${startPoint.x} ${startPoint.y} ${bendpoints.map((b: Point) => `L${b.x} ${b.y} `).join('')}L${ endPoint.x } ${endPoint.y}`; const bgStartPoint = !startTerminalType || startTerminalType === EdgeTerminalType.none ? [startPoint.x, startPoint.y] : getConnectorStartPoint(_.head(bendpoints) || endPoint, startPoint, startTerminalSize); const bgEndPoint = !endTerminalType || endTerminalType === EdgeTerminalType.none ? [endPoint.x, endPoint.y] : getConnectorStartPoint(_.last(bendpoints) || startPoint, endPoint, endTerminalSize); const backgroundPath = `M${bgStartPoint[0]} ${bgStartPoint[1]} ${bendpoints .map((b: Point) => `L${b.x} ${b.y} `) .join('')}L${bgEndPoint[0]} ${bgEndPoint[1]}`; return ( <Layer id={dragging || hover ? TOP_LAYER : undefined}> <g ref={hoverRef} data-test-id="edge-handler" className={groupClassName} onClick={onSelect} onContextMenu={onContextMenu} > <path className={css(styles.topologyEdgeBackground)} d={backgroundPath} onMouseEnter={onShowRemoveConnector} onMouseLeave={onHideRemoveConnector} /> <path className={linkClassName} d={d} style={{ animationDuration: `${edgeAnimationDuration}s` }} /> {tag && ( <DefaultConnectorTag className={tagClass} startPoint={element.getStartPoint()} endPoint={element.getEndPoint()} tag={tag} status={tagStatus} /> )} <DefaultConnectorTerminal className={startTerminalClass} isTarget={false} edge={element} size={startTerminalSize} dragRef={sourceDragRef} terminalType={startTerminalType} status={startTerminalStatus} highlight={dragging || hover} /> <DefaultConnectorTerminal className={endTerminalClass} isTarget dragRef={targetDragRef} edge={element} size={endTerminalSize} terminalType={endTerminalType} status={endTerminalStatus} highlight={dragging || hover} /> {children} </g> </Layer> ); }; export default observer(BaseEdge);
jelly/patternfly-react
packages/react-inline-edit-extension/src/components/TableTextInput/index.ts
<filename>packages/react-inline-edit-extension/src/components/TableTextInput/index.ts export * from './TableTextInput';
jelly/patternfly-react
packages/react-core/src/components/CodeBlock/CodeBlockAction.tsx
<filename>packages/react-core/src/components/CodeBlock/CodeBlockAction.tsx import * as React from 'react'; import { css } from '@patternfly/react-styles'; export interface CodeBlockActionProps extends React.HTMLProps<HTMLDivElement> { /** Content rendered inside the code block action */ children?: React.ReactNode; /** Additional classes passed to the code block action */ className?: string; } export const CodeBlockAction: React.FunctionComponent<CodeBlockActionProps> = ({ children = null, className, ...props }: CodeBlockActionProps) => ( <div className={css('pf-c-code-block__actions-item', className)} {...props}> {children} </div> ); CodeBlockAction.displayName = 'CodeBlockAction';
jelly/patternfly-react
packages/react-table/src/components/Table/examples/LegacyTableStriped.tsx
import React from 'react'; import { Table, TableHeader, TableBody, TableProps } from '@patternfly/react-table'; interface Repository { name: string; branches: string; prs: string; workspaces: string; lastCommit: string; } export const LegacyTableStriped: React.FunctionComponent = () => { // In real usage, this data would come from some external source like an API via props. const repositories: Repository[] = [ { name: 'Repository one', branches: 'Branch one', prs: 'PR one', workspaces: 'Workspace one', lastCommit: 'Commit one' }, { name: 'Repository two', branches: 'Branch two', prs: 'PR two', workspaces: 'Workspace two', lastCommit: 'Commit two' }, { name: 'Repository three', branches: 'Branch three', prs: 'PR three', workspaces: 'Workspace three', lastCommit: 'Commit three' } ]; 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 ]); return ( <Table aria-label="Simple Table" cells={columns} rows={rows} isStriped> <TableHeader /> <TableBody /> </Table> ); };
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/CustomPathNode.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import { observer } from 'mobx-react'; import { WithCreateConnectorProps, Node, WithContextMenuProps, WithDragNodeProps, WithSelectionProps, WithDndDragProps, WithDndDropProps } from '@patternfly/react-topology'; import Path from './shapes/Path'; import DemoDefaultNode from './DemoDefaultNode'; type CustomPathNodeProps = { element: Node; droppable?: boolean; canDrop?: boolean; } & WithSelectionProps & WithDragNodeProps & WithDndDragProps & WithDndDropProps & WithCreateConnectorProps & WithContextMenuProps; const CustomPathNode: React.FunctionComponent<CustomPathNodeProps> = props => ( <DemoDefaultNode getCustomShape={() => Path} {...props} /> ); export default observer(CustomPathNode);
jelly/patternfly-react
packages/react-core/src/components/Masthead/__tests__/Masthead.test.tsx
<filename>packages/react-core/src/components/Masthead/__tests__/Masthead.test.tsx import React from 'react'; import { render } from '@testing-library/react'; import { Masthead, MastheadBrand, MastheadContent, MastheadMain, MastheadToggle } from '../index'; describe('Masthead', () => { test('verify basic', () => { const { asFragment } = render(<Masthead>test</Masthead>); expect(asFragment()).toMatchSnapshot(); }); test('verify full structure', () => { const { asFragment } = render( <Masthead> <MastheadToggle>Toggle</MastheadToggle> <MastheadMain> <MastheadBrand>Logo</MastheadBrand> </MastheadMain> <MastheadContent> <span>Content</span> </MastheadContent> </Masthead> ); expect(asFragment()).toMatchSnapshot(); }); test('verify custom class', () => { const { asFragment } = render(<Masthead className="custom-css">test</Masthead>); expect(asFragment()).toMatchSnapshot(); }); test('verify inline display breakpoints', () => { const { asFragment } = render( <Masthead display={{ default: 'inline', sm: 'inline', md: 'inline', lg: 'inline', xl: 'inline', '2xl': 'inline' }} > test </Masthead> ); expect(asFragment()).toMatchSnapshot(); }); test('verify stack display breakpoints', () => { const { asFragment } = render( <Masthead display={{ default: 'stack', sm: 'stack', md: 'stack', lg: 'stack', xl: 'stack', '2xl': 'stack' }}> test </Masthead> ); expect(asFragment()).toMatchSnapshot(); }); Object.values(['insetNone', 'insetXs', 'insetSm', 'insetMd', 'insetLg', 'insetXl', 'inset2xl', 'inset3xl'] as [ 'insetNone', 'insetXs', 'insetSm', 'insetMd', 'insetLg', 'insetXl', 'inset2xl', 'inset3xl' ]).forEach(inset => { test(`verify ${inset} inset breakpoints`, () => { const { asFragment } = render( <Masthead inset={{ default: inset, sm: inset, md: inset, lg: inset, xl: inset, '2xl': inset }}>test</Masthead> ); expect(asFragment()).toMatchSnapshot(); }); }); }); describe('MastheadBrand', () => { test('verify basic', () => { const { asFragment } = render(<MastheadBrand>test</MastheadBrand>); expect(asFragment()).toMatchSnapshot(); }); test('verify custom class', () => { const { asFragment } = render(<MastheadBrand className="custom-css">test</MastheadBrand>); expect(asFragment()).toMatchSnapshot(); }); test('verify custom component', () => { const { asFragment } = render(<MastheadBrand component="div">test</MastheadBrand>); expect(asFragment()).toMatchSnapshot(); }); }); describe('MastheadContent', () => { test('verify basic', () => { const { asFragment } = render(<MastheadContent>test</MastheadContent>); expect(asFragment()).toMatchSnapshot(); }); test('verify custom class', () => { const { asFragment } = render(<MastheadContent className="custom-css">test</MastheadContent>); expect(asFragment()).toMatchSnapshot(); }); }); describe('MastheadMain', () => { test('verify basic', () => { const { asFragment } = render(<MastheadMain>test</MastheadMain>); expect(asFragment()).toMatchSnapshot(); }); test('verify custom class', () => { const { asFragment } = render(<MastheadMain className="custom-css">test</MastheadMain>); expect(asFragment()).toMatchSnapshot(); }); }); describe('MastheadToggle', () => { test('verify basic', () => { const { asFragment } = render(<MastheadToggle>test</MastheadToggle>); expect(asFragment()).toMatchSnapshot(); }); test('verify custom class', () => { const { asFragment } = render(<MastheadToggle className="custom-css">test</MastheadToggle>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-table/src/components/TableComposable/examples/ComposableTableStripedMultipleTbody.tsx
<gh_stars>0 import React from 'react'; import { TableComposable, Caption, Thead, Tr, Th, Tbody, Td } from '@patternfly/react-table'; interface Repository { name: string; branches: number; description?: string; prs: number; workspaces: number; lastCommit: string; } export const ComposableTableStripedMultipleTbody: React.FunctionComponent = () => { // In real usage, this data would come from some external source like an API via props. const repositories1: Repository[] = [ { name: 'tbody 1 - Repository 1', description: '(odd rows striped)', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' }, { name: 'tbody 1 - Repository 2', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' }, { name: 'tbody 1 - Repository 3', description: '(odd rows striped)', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' } ]; const repositories2: Repository[] = [ { name: 'tbody 2 - Repository 4', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' }, { name: 'tbody 2 - Repository 5', description: '(even rows striped)', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' }, { name: 'tbody 2 - Repository 6', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' }, { name: 'tbody 2 - Repository 7', description: '(even rows striped)', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' } ]; const columnNames = { name: 'Repositories', branches: 'Branches', prs: 'Pull requests', workspaces: 'Workspaces', lastCommit: 'Last commit' }; return ( <TableComposable aria-label="Simple table"> <Caption>Striped table using multiple tbody 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 isOddStriped> {repositories1.map(repo => ( <Tr key={repo.name}> <Td dataLabel={columnNames.name}> {repo.description ? ( <React.Fragment> {repo.name} <br /> <small>{repo.description}</small> </React.Fragment> ) : ( 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> <Tbody isEvenStriped> {repositories2.map(repo => ( <Tr key={repo.name}> <Td dataLabel={columnNames.name}> {repo.description ? ( <React.Fragment> {repo.name} <br /> <small>{repo.description}</small> </React.Fragment> ) : ( 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> ); };
jelly/patternfly-react
packages/react-core/src/components/Accordion/examples/AccordionFixedWithMultipleExpandBehavior.tsx
import React from 'react'; import { Accordion, AccordionItem, AccordionContent, AccordionToggle } from '@patternfly/react-core'; export const AccordionFixedWithMultipleExpandBehavior: React.FunctionComponent = () => { const [expanded, setExpanded] = React.useState(['ex2-toggle4']); const toggle = id => { const index = expanded.indexOf(id); const newExpanded: string[] = index >= 0 ? [...expanded.slice(0, index), ...expanded.slice(index + 1, expanded.length)] : [...expanded, id]; setExpanded(newExpanded); }; return ( <Accordion asDefinitionList={false}> <AccordionItem> <AccordionToggle onClick={() => toggle('ex2-toggle1')} isExpanded={expanded.includes('ex2-toggle1')} id="ex2-toggle1" > Item one </AccordionToggle> <AccordionContent id="ex2-expand1" isHidden={!expanded.includes('ex2-toggle1')} isFixed> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </AccordionContent> </AccordionItem> <AccordionItem> <AccordionToggle onClick={() => toggle('ex2-toggle2')} isExpanded={expanded.includes('ex2-toggle2')} id="ex2-toggle2" > Item two </AccordionToggle> <AccordionContent id="ex2-expand2" isHidden={!expanded.includes('ex2-toggle2')} isFixed> <p> Vivamus et tortor sed arcu congue vehicula eget et diam. Praesent nec dictum lorem. Aliquam id diam ultrices, faucibus erat id, maximus nunc. </p> </AccordionContent> </AccordionItem> <AccordionItem> <AccordionToggle onClick={() => toggle('ex2-toggle3')} isExpanded={expanded.includes('ex2-toggle3')} id="ex2-toggle3" > Item three </AccordionToggle> <AccordionContent id="ex2-expand3" isHidden={!expanded.includes('ex2-toggle3')} isFixed> <p>Morbi vitae urna quis nunc convallis hendrerit. Aliquam congue orci quis ultricies tempus.</p> </AccordionContent> </AccordionItem> <AccordionItem> <AccordionToggle onClick={() => toggle('ex2-toggle4')} isExpanded={expanded.includes('ex2-toggle4')} id="ex2-toggle4" > Item four </AccordionToggle> <AccordionContent id="ex2-expand4" isHidden={!expanded.includes('ex2-toggle4')} isFixed> <p> Donec vel posuere orci. Phasellus quis tortor a ex hendrerit efficitur. Aliquam lacinia ligula pharetra, sagittis ex ut, pellentesque diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum ultricies nulla nibh. Etiam vel dui fermentum ligula ullamcorper eleifend non quis tortor. Morbi tempus ornare tempus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris et velit neque. Donec ultricies condimentum mauris, pellentesque imperdiet libero convallis convallis. Aliquam erat volutpat. Donec rutrum semper tempus. Proin dictum imperdiet nibh, quis dapibus nulla. Integer sed tincidunt lectus, sit amet auctor eros. </p> </AccordionContent> </AccordionItem> <AccordionItem> <AccordionToggle onClick={() => toggle('ex2-toggle5')} isExpanded={expanded.includes('ex2-toggle5')} id="ex2-toggle5" > Item five </AccordionToggle> <AccordionContent id="ex2-expand5" isHidden={!expanded.includes('ex2-toggle5')} isFixed> <p>Vivamus finibus dictum ex id ultrices. Mauris dictum neque a iaculis blandit.</p> </AccordionContent> </AccordionItem> </Accordion> ); };
jelly/patternfly-react
packages/react-core/src/components/DatePicker/examples/DatePickerHelperText.tsx
import React from 'react'; import { DatePicker } from '@patternfly/react-core'; export const DatePickerHelperText: React.FunctionComponent = () => ( <DatePicker value="2020-03-05" helperText="Select a date." /> );
jelly/patternfly-react
packages/react-core/src/components/CodeBlock/examples/CodeBlockBasic.tsx
import React from 'react'; import { CodeBlock, CodeBlockAction, CodeBlockCode, ClipboardCopyButton, Button } from '@patternfly/react-core'; import PlayIcon from '@patternfly/react-icons/dist/esm/icons/play-icon'; export const BasicCodeBlock: React.FunctionComponent = () => { const [copied, setCopied] = React.useState(false); const clipboardCopyFunc = (event, text) => { 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); }; const onClick = (event, text) => { clipboardCopyFunc(event, text); setCopied(true); }; const code = `apiVersion: helm.openshift.io/v1beta1/ kind: HelmChartRepository metadata: name: azure-sample-repo0oooo00ooo spec: connectionConfig: url: https://raw.githubusercontent.com/Azure-Samples/helm-charts/master/docs`; const actions = ( <React.Fragment> <CodeBlockAction> <ClipboardCopyButton id="copy-button" textId="code-content" aria-label="Copy to clipboard" onClick={e => onClick(e, code)} exitDelay={600} maxWidth="110px" variant="plain" > {copied ? 'Successfully copied to clipboard!' : 'Copy to clipboard'} </ClipboardCopyButton> </CodeBlockAction> <CodeBlockAction> <Button variant="plain" aria-label="Play icon"> <PlayIcon /> </Button> </CodeBlockAction> </React.Fragment> ); return ( <CodeBlock actions={actions}> <CodeBlockCode id="code-content">{code}</CodeBlockCode> </CodeBlock> ); };
jelly/patternfly-react
packages/react-core/src/helpers/Popper/__tests__/Generated/FindRefWrapper.test.tsx
/** * This test was generated */ import * as React from 'react'; import { render } from '@testing-library/react'; import { FindRefWrapper } from '../../FindRefWrapper'; it('FindRefWrapper should match snapshot (auto-generated)', () => { const { asFragment } = render(<FindRefWrapper children={<div>ReactNode</div>} onFoundRef={(foundRef: any) => {}} />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/DualListSelector/DualListSelectorTree.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/DualListSelector/dual-list-selector'; import { DualListSelectorTreeItem } from './DualListSelectorTreeItem'; export interface DualListSelectorTreeItemData { /** Content rendered inside the dual list selector. */ children?: DualListSelectorTreeItemData[]; /** Additional classes applied to the dual list selector. */ className?: string; /** Flag indicating this option is expanded by default. */ defaultExpanded?: boolean; /** Flag indicating this option has a badge */ hasBadge?: boolean; /** Callback fired when an option is checked */ onOptionCheck?: ( event: React.MouseEvent | React.ChangeEvent<HTMLInputElement> | React.KeyboardEvent, isChecked: boolean, isChosen: boolean, itemData: DualListSelectorTreeItemData ) => void; /** ID of the option */ id: string; /** Text of the option */ text: string; /** Parent id of an option */ parentId?: string; /** Checked state of the option */ isChecked: boolean; /** Additional properties to pass to the option checkbox */ checkProps?: any; /** Additional properties to pass to the option badge */ badgeProps?: any; /** Flag indicating whether the component is disabled. */ isDisabled?: boolean; } export interface DualListSelectorTreeProps { /** Data of the tree view */ data: DualListSelectorTreeItemData[] | (() => DualListSelectorTreeItemData[]); /** ID of the tree view */ id?: string; /** @hide Flag indicating if the list is nested */ isNested?: boolean; /** Flag indicating if all options should have badges */ hasBadges?: boolean; /** Sets the default expanded behavior */ defaultAllExpanded?: boolean; /** Callback fired when an option is checked */ isDisabled?: boolean; onOptionCheck?: ( event: React.MouseEvent | React.ChangeEvent<HTMLInputElement> | React.KeyboardEvent, isChecked: boolean, itemData: DualListSelectorTreeItemData ) => void; } export const DualListSelectorTree: React.FunctionComponent<DualListSelectorTreeProps> = ({ data, hasBadges = false, isNested = false, defaultAllExpanded = false, onOptionCheck, isDisabled = false, ...props }: DualListSelectorTreeProps) => { const dataToRender = typeof data === 'function' ? data() : data; const tree = dataToRender.map(item => ( <DualListSelectorTreeItem key={item.id} text={item.text} id={item.id} defaultExpanded={item.defaultExpanded !== undefined ? item.defaultExpanded : defaultAllExpanded} onOptionCheck={onOptionCheck} isChecked={item.isChecked} checkProps={item.checkProps} hasBadge={item.hasBadge !== undefined ? item.hasBadge : hasBadges} badgeProps={item.badgeProps} itemData={item} isDisabled={isDisabled} useMemo={true} {...(item.children && { children: ( <DualListSelectorTree isNested data={item.children} hasBadges={hasBadges} defaultAllExpanded={defaultAllExpanded} onOptionCheck={onOptionCheck} isDisabled={isDisabled} /> ) })} /> )); return isNested ? ( <ul className={css(styles.dualListSelectorList)} role="group" {...props}> {tree} </ul> ) : ( <>{tree}</> ); }; DualListSelectorTree.displayName = 'DualListSelectorTree';
jelly/patternfly-react
packages/react-core/src/components/Checkbox/examples/CheckboxWithDescriptionBody.tsx
<gh_stars>0 import React from 'react'; import { Checkbox } from '@patternfly/react-core'; export const CheckboxWithDescriptionBody: React.FunctionComponent = () => ( <Checkbox id="description-body-check" label="Checkbox with description and body" 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." body="This is where custom content goes." /> );
jelly/patternfly-react
packages/react-core/src/components/Progress/__tests__/Progress.test.tsx
<filename>packages/react-core/src/components/Progress/__tests__/Progress.test.tsx import React from 'react'; import { render } from '@testing-library/react'; import { Progress, ProgressSize } from '../Progress'; import { ProgressVariant, ProgressMeasureLocation } from '../ProgressContainer'; test('Simple progress', () => { const { asFragment } = render(<Progress value={33} id="progress-simple-example" />); expect(asFragment()).toMatchSnapshot(); }); test('no value specified', () => { const { asFragment } = render(<Progress id="no-value" />); expect(asFragment()).toMatchSnapshot(); }); test('additional label', () => { const { asFragment } = render(<Progress id="additional-label" value={33} label="Additional label" />); expect(asFragment()).toMatchSnapshot(); }); test('Progress with aria-valuetext', () => { const { asFragment } = render(<Progress value={33} id="progress-aria-valuetext" valueText="Descriptive text here" />); expect(asFragment()).toMatchSnapshot(); }); test('value lower than minValue', () => { const { asFragment } = render(<Progress value={33} id="lower-min-value" min={40} />); expect(asFragment()).toMatchSnapshot(); }); test('value higher than maxValue', () => { const { asFragment } = render(<Progress value={77} id="higher-max-value" max={60} />); expect(asFragment()).toMatchSnapshot(); }); test('value scaled with minValue', () => { const { asFragment } = render(<Progress min={10} value={50} id="scaled-min-value" />); expect(asFragment()).toMatchSnapshot(); }); test('value scaled with maxValue', () => { const { asFragment } = render(<Progress value={50} id="scaled-max-value" max={80} />); expect(asFragment()).toMatchSnapshot(); }); test('value scaled between minValue and maxValue', () => { const { asFragment } = render(<Progress min={10} value={50} id="scaled-range-value" max={80} />); expect(asFragment()).toMatchSnapshot(); }); describe('Progress size', () => { Object.keys(ProgressSize).forEach(oneSize => { test(oneSize, () => { const { asFragment } = render(<Progress id={`${oneSize}-progress`} value={33} size={oneSize as ProgressSize} />); expect(asFragment()).toMatchSnapshot(); }); }); }); describe('Progress variant', () => { Object.keys(ProgressVariant).forEach(oneVariant => { test(oneVariant, () => { const { asFragment } = render( <Progress id={`${oneVariant}-progress`} value={33} variant={oneVariant as ProgressVariant} /> ); expect(asFragment()).toMatchSnapshot(); }); }); }); describe('Progress measure location', () => { Object.keys(ProgressMeasureLocation).forEach(oneLocation => { test(oneLocation, () => { const { asFragment } = render( <Progress id={`${oneLocation}-progress`} value={33} measureLocation={oneLocation as ProgressMeasureLocation} /> ); expect(asFragment()).toMatchSnapshot(); }); }); test('inside and small should render large', () => { const { asFragment } = render( <Progress id="large-progress" value={33} measureLocation={ProgressMeasureLocation.inside} size={ProgressSize.sm} /> ); expect(asFragment()).toMatchSnapshot(); }); }); test('progress component generates console warning when no accessible name is provided', () => { const consoleWarnMock = jest.fn(); global.console = { warn: consoleWarnMock } as any; render(<Progress value={33} />); expect(consoleWarnMock).toHaveBeenCalled(); });
jelly/patternfly-react
packages/react-console/src/components/VncConsole/__tests__/VncConsole.test.tsx
<reponame>jelly/patternfly-react /* eslint-disable import/no-extraneous-dependencies */ import React from 'react'; import { render } from '@testing-library/react'; import { VncConsole } from '../../VncConsole'; test('placeholder render test', () => { const { asFragment } = render(<VncConsole host="my.unknown.host" />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/Card/examples/CardWithBodySectionFills.tsx
import React from 'react'; import { Card, CardTitle, CardBody, CardFooter } from '@patternfly/react-core'; export const CardWithBodySectionFills: React.FunctionComponent = () => ( <Card style={{ minHeight: '30em' }}> <CardTitle>Header</CardTitle> <CardBody isFilled={false}>Body pf-m-no-fill</CardBody> <CardBody isFilled={false}>Body pf-m-no-fill</CardBody> <CardBody>Body</CardBody> <CardFooter>Footer</CardFooter> </Card> );
jelly/patternfly-react
packages/react-core/src/components/DatePicker/examples/DatePickerMinMax.tsx
import React from 'react'; import { DatePicker } from '@patternfly/react-core'; export const DatePickerMinMax: React.FunctionComponent = () => { const minDate = new Date(2020, 2, 16); const maxDate = new Date(2020, 2, 20); const rangeValidator = (date: Date) => { if (date < minDate) { return 'Date is before the allowable range.'; } else if (date > maxDate) { return 'Date is after the allowable range.'; } return ''; }; return <DatePicker value="2020-03-17" validators={[rangeValidator]} />; };
jelly/patternfly-react
packages/react-core/src/components/Card/examples/CardWithMultipleBodySections.tsx
import React from 'react'; import { Card, CardTitle, CardBody, CardFooter } from '@patternfly/react-core'; export const CardWithMultipleBodySections: React.FunctionComponent = () => ( <Card> <CardTitle>Header</CardTitle> <CardBody>Body</CardBody> <CardBody>Body</CardBody> <CardBody>Body</CardBody> <CardFooter>Footer</CardFooter> </Card> );
jelly/patternfly-react
packages/react-core/src/layouts/Bullseye/index.ts
<gh_stars>100-1000 export * from './Bullseye';
jelly/patternfly-react
packages/react-core/src/components/OptionsMenu/__tests__/Generated/OptionsMenuToggleWithText.test.tsx
/** * This test was generated */ import * as React from 'react'; import { render } from '@testing-library/react'; import { OptionsMenuToggleWithText } from '../../OptionsMenuToggleWithText'; // any missing imports can usually be resolved by adding them here import {} from '../..'; it('OptionsMenuToggleWithText should match snapshot (auto-generated)', () => { const { asFragment } = render( <OptionsMenuToggleWithText parentId={"''"} toggleText={<div>ReactNode</div>} toggleTextClassName={"''"} toggleButtonContents={<div>ReactNode</div>} toggleButtonContentsClassName={"''"} onToggle={() => null as any} isOpen={false} isPlain={false} isActive={false} isDisabled={false} aria-haspopup={true} aria-label={"'Options menu'"} /> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-code-editor/src/components/CodeEditor/examples/CodeEditorSizeToFit.tsx
<reponame>jelly/patternfly-react<gh_stars>0 import React from 'react'; import { CodeEditor, Language } from '@patternfly/react-code-editor'; export const CodeEditorSizeToFit: React.FunctionComponent = () => { const onEditorDidMount = (editor, monaco) => { // eslint-disable-next-line no-console console.log(editor.getValue()); editor.layout(); editor.focus(); monaco.editor.getModels()[0].updateOptions({ tabSize: 5 }); }; const onChange = value => { // eslint-disable-next-line no-console console.log(value); }; return ( <CodeEditor code="Some example content" onChange={onChange} language={Language.javascript} onEditorDidMount={onEditorDidMount} height="sizeToFit" /> ); };
jelly/patternfly-react
packages/react-table/src/components/Table/examples/LegacyTableBasic.tsx
<filename>packages/react-table/src/components/Table/examples/LegacyTableBasic.tsx import React from 'react'; import { Table, TableHeader, TableBody, TableProps } from '@patternfly/react-table'; import { ToggleGroup, ToggleGroupItem, ToggleGroupItemProps } from '@patternfly/react-core'; interface Repository { name: string; branches: string; prs: string; workspaces: string; lastCommit: string; } type ExampleType = 'default' | 'compact' | 'compactBorderless'; export const LegacyTableBasic: React.FunctionComponent = () => { // In real usage, this data would come from some external source like an API via props. const repositories: Repository[] = [ { name: 'Repository one', branches: 'Branch one', prs: 'PR one', workspaces: 'Workspace one', lastCommit: 'Commit one' }, { name: 'Repository two', branches: 'Branch two', prs: 'PR two', workspaces: 'Workspace two', lastCommit: 'Commit two' }, { name: 'Repository three', branches: 'Branch three', prs: 'PR three', workspaces: 'Workspace three', lastCommit: 'Commit three' } ]; // 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); }; 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 ]); 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> <Table aria-label="Simple Table" variant={exampleChoice !== 'default' ? 'compact' : undefined} borders={exampleChoice !== 'compactBorderless'} cells={columns} rows={rows} > <TableHeader /> <TableBody /> </Table> </React.Fragment> ); };
jelly/patternfly-react
packages/react-core/src/components/Masthead/MastheadMain.tsx
<gh_stars>100-1000 import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Masthead/masthead'; import { css } from '@patternfly/react-styles'; export interface MastheadMainProps extends React.DetailedHTMLProps<React.HTMLProps<HTMLDivElement>, HTMLDivElement> { /** Content rendered inside of the masthead main block. */ children?: React.ReactNode; /** Additional classes added to the masthead main. */ className?: string; } export const MastheadMain: React.FunctionComponent<MastheadMainProps> = ({ children, className, ...props }: MastheadMainProps) => ( <div className={css(styles.mastheadMain, className)} {...props}> {children} </div> ); MastheadMain.displayName = 'MastheadMain';
jelly/patternfly-react
packages/react-core/src/components/DescriptionList/examples/DescriptionListIconsOnTerms.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { Button, DescriptionList, DescriptionListTerm, DescriptionListGroup, DescriptionListDescription } from '@patternfly/react-core'; import PlusCircleIcon from '@patternfly/react-icons/dist/esm/icons/plus-circle-icon'; import CubeIcon from '@patternfly/react-icons/dist/esm/icons/cube-icon'; import BookIcon from '@patternfly/react-icons/dist/esm/icons/book-icon'; import KeyIcon from '@patternfly/react-icons/dist/esm/icons/key-icon'; import GlobeIcon from '@patternfly/react-icons/dist/esm/icons/globe-icon'; import FlagIcon from '@patternfly/react-icons/dist/esm/icons/flag-icon'; export const DescriptionListIconsOnTerms: React.FunctionComponent = () => ( <DescriptionList> <DescriptionListGroup> <DescriptionListTerm icon={<CubeIcon />}>Name</DescriptionListTerm> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm icon={<BookIcon />}>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm icon={<KeyIcon />}>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm icon={<GlobeIcon />}>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm icon={<FlagIcon />}>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> );
jelly/patternfly-react
packages/react-core/src/components/Spinner/__tests__/Spinner.test.tsx
<gh_stars>0 import * as React from 'react'; import { render } from '@testing-library/react'; import { Spinner } from '../Spinner'; test('simple spinner', () => { const { asFragment } = render(<Spinner />); expect(asFragment()).toMatchSnapshot(); }); test('small spinner', () => { const { asFragment } = render(<Spinner size="sm" />); expect(asFragment()).toMatchSnapshot(); }); test('medium spinner', () => { const { asFragment } = render(<Spinner size="md" />); expect(asFragment()).toMatchSnapshot(); }); test('large spinner', () => { const { asFragment } = render(<Spinner size="lg" />); expect(asFragment()).toMatchSnapshot(); }); test('extra large spinner', () => { const { asFragment } = render(<Spinner size="xl" />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/Card/__tests__/CardHeader.test.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { render } from '@testing-library/react'; import { CardHeader } from '../CardHeader'; describe('CardHeader', () => { test('onExpand adds the toggle button', () => { const { asFragment } = render(<CardHeader onExpand={jest.fn()} />); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-charts/src/components/ChartLegendTooltip/ChartLegendTooltipLabel.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import { ChartLegendTooltipLabel } from './ChartLegendTooltipLabel'; Object.values([true, false]).forEach(() => { test('ChartLegendTooltipLabel', () => { const { asFragment } = render(<ChartLegendTooltipLabel />); expect(asFragment()).toMatchSnapshot(); }); }); test('renders component text', () => { const legendData = [ { name: 'Cats' }, { name: 'Dogs', symbol: { type: 'dash' } }, { name: 'Birds' }, { name: 'Mice' } ]; const { asFragment } = render(<ChartLegendTooltipLabel legendData={legendData} text={['1, 2, 3, 4']} />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-integration/cypress/integration/duallistselectorbasic.spec.ts
<reponame>jelly/patternfly-react describe('Dual List Selector BasicDemo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/dual-list-selector-basic-demo-nav-link'); }); it('Verify existence', () => { cy.get('.pf-c-dual-list-selector').should('exist'); }); it('Verify default aria-labels, status, and titles', () => { cy.get('.pf-m-available .pf-c-dual-list-selector__title-text').contains('Available options'); cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('0 of 4 items selected'); cy.get('.pf-m-available .pf-c-dual-list-selector__tools-filter input').should( 'have.attr', 'aria-label', 'Available search input' ); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(1) .should('have.attr', 'aria-label', 'Add all'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(0) .should('have.attr', 'aria-label', 'Add selected') .and('have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(3) .should('have.attr', 'aria-label', 'Remove selected') .and('have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(2) .should('have.attr', 'aria-label', 'Remove all') .and('have.attr', 'disabled'); cy.get('.pf-m-chosen .pf-c-dual-list-selector__title-text').contains('Chosen options'); cy.get('.pf-m-chosen .pf-c-dual-list-selector__status-text').contains('0 of 0 items selected'); cy.get('.pf-m-chosen .pf-c-dual-list-selector__tools-filter input').should( 'have.attr', 'aria-label', 'Chosen search input' ); }); it('Verify default value content', () => { cy.get('.pf-c-dual-list-selector__list') .first() .should('have.value', ''); cy.get('.pf-c-dual-list-selector__list li').should('have.length', 4); }); it('Verify selecting options', () => { cy.get('.pf-c-dual-list-selector__list-item .pf-m-selected').should('not.exist'); cy.get('.pf-c-dual-list-selector__list-item') .eq(0) .click(); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(0) .and('not.have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__list-item .pf-m-selected').should('exist'); cy.get('.pf-c-dual-list-selector__list-item') .eq(1) .click(); cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('2 of 4 items selected'); cy.get('.pf-c-dual-list-selector__list-item .pf-m-selected').should('have.length', 2); cy.get('.pf-c-dual-list-selector__list-item') .eq(0) .click(); cy.get('.pf-c-dual-list-selector__list-item .pf-m-selected').should('have.length', 1); cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('1 of 4 items selected'); }); it('Verify selecting and choosing options', () => { cy.get('.pf-c-dual-list-selector__controls-item') .eq(0) .click(); cy.get('.pf-c-dual-list-selector__list') .eq(0) .find('li') .should('have.length', 3); cy.get('.pf-c-dual-list-selector__list') .eq(1) .find('li') .should('have.length', 1); cy.get('.pf-c-dual-list-selector__list-item') .eq(1) .click(); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(1) .should('not.have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(0) .should('not.have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(3) .should('have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(2) .should('not.have.attr', 'disabled'); cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('1 of 3 items selected'); cy.get('.pf-m-chosen .pf-c-dual-list-selector__status-text').contains('0 of 1 items selected'); cy.get('.pf-c-dual-list-selector__controls-item') .eq(0) .click(); cy.get('.pf-c-tooltip').should('exist'); cy.get('.pf-c-dual-list-selector__list') .eq(0) .find('li') .should('have.length', 2); cy.get('.pf-c-dual-list-selector__list') .eq(1) .find('li') .should('have.length', 2); cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('0 of 2 items selected'); cy.get('.pf-m-chosen .pf-c-dual-list-selector__status-text').contains('0 of 2 items selected'); }); it('Verify removing all options', () => { cy.get('.pf-c-dual-list-selector__controls-item') .eq(2) .click(); cy.get('.pf-c-tooltip').should('exist'); cy.get('.pf-c-dual-list-selector__list') .eq(0) .find('li') .should('have.length', 4); cy.get('.pf-c-dual-list-selector__list') .eq(1) .find('li') .should('have.length', 0); }); it('Verify choosing all options', () => { cy.get('.pf-c-dual-list-selector__controls-item') .eq(1) .click(); cy.get('.pf-c-tooltip').should('exist'); cy.get('.pf-c-dual-list-selector__list') .eq(0) .find('li') .should('have.length', 0); cy.get('.pf-c-dual-list-selector__list') .eq(1) .find('li') .should('have.length', 4); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(1) .should('have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(0) .should('have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(3) .should('have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(2) .should('not.have.attr', 'disabled'); cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('0 of 0 items selected'); cy.get('.pf-m-chosen .pf-c-dual-list-selector__status-text').contains('0 of 4 items selected'); }); it('Verify chosen search works', () => { cy.get('.pf-c-dual-list-selector__list') .eq(1) .find('li') .should('have.length', 4); cy.get('.pf-c-dual-list-selector__tools-filter .pf-m-search') .eq(1) .type('Option 1'); cy.get('.pf-c-dual-list-selector__list') .eq(1) .find('li') .should('have.length', 1); }); it('Verify removing all options', () => { cy.get('.pf-c-dual-list-selector__tools-filter .pf-m-search') .eq(1) .type('{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}'); cy.get('.pf-c-dual-list-selector__controls-item') .eq(2) .click(); cy.get('.pf-c-dual-list-selector__list') .eq(0) .find('li') .should('have.length', 4); cy.get('.pf-c-dual-list-selector__list') .eq(1) .find('li') .should('have.length', 0); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(1) .should('not.have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(0) .should('have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(3) .should('have.attr', 'disabled'); cy.get('.pf-c-dual-list-selector__controls-item button') .eq(2) .should('have.attr', 'disabled'); cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('0 of 4 items selected'); cy.get('.pf-m-chosen .pf-c-dual-list-selector__status-text').contains('0 of 0 items selected'); }); it('Verify available search works', () => { cy.get('.pf-c-dual-list-selector__list') .eq(0) .find('li') .should('have.length', 4); cy.get('.pf-c-dual-list-selector__tools-filter .pf-m-search') .eq(0) .type('Option 3'); cy.get('.pf-c-dual-list-selector__list') .eq(0) .find('li') .should('have.length', 1); }); });
jelly/patternfly-react
packages/react-topology/src/components/edges/terminals/ConnectorCross.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 { getConnectorRotationAngle, getConnectorStartPoint } from './terminalUtils'; interface ConnectorCrossProps { startPoint: Point; endPoint: Point; className?: string; isTarget?: boolean; size?: number; dragRef?: ConnectDragSource; } const ConnectorCross: React.FunctionComponent<ConnectorCrossProps> = ({ startPoint, endPoint, className = '', isTarget = true, size = 14, dragRef }) => { if (!startPoint || !endPoint) { return null; } const width = size / 4; const yDelta = size / 2; const connectorStartPoint = getConnectorStartPoint(startPoint, endPoint, size); const angleDeg = getConnectorRotationAngle(startPoint, endPoint); const classNames = css( styles.topologyConnectorArrow, styles.topologyConnectorCross, className, !isTarget && 'pf-m-source', dragRef && 'pf-m-draggable' ); return ( <g transform={`translate(${connectorStartPoint[0]}, ${connectorStartPoint[1]}) rotate(${angleDeg})`} ref={dragRef} className={classNames} > <rect x={0} y={-yDelta} width={size} height={size} fillOpacity={0} strokeOpacity={0} /> {isTarget ? ( <> <line x1={width} y1={yDelta} x2={width} y2={-yDelta} /> <line x1={2 * width} y1={yDelta} x2={2 * width} y2={-yDelta} /> </> ) : ( <rect x={width} y={-yDelta} width={width} height={size} /> )} </g> ); }; export default ConnectorCross;
jelly/patternfly-react
packages/react-icons/src/__tests__/createIcon.test.tsx
<reponame>jelly/patternfly-react<filename>packages/react-icons/src/__tests__/createIcon.test.tsx<gh_stars>0 import React from 'react'; import { render, screen } from '@testing-library/react'; import { createIcon, IconSize } from '../createIcon'; const iconDef = { name: 'IconName', width: 10, height: 20, svgPath: 'svgPath' }; const SVGIcon = createIcon(iconDef); test('sets correct viewBox', () => { render(<SVGIcon />); expect(screen.getByRole('img', { hidden: true })).toHaveAttribute( 'viewBox', `0 0 ${iconDef.width} ${iconDef.height}` ); }); test('sets correct svgPath', () => { render(<SVGIcon />); expect( screen .getByRole('img', { hidden: true }) .querySelector('path') ).toHaveAttribute('d', iconDef.svgPath); }); test('height and width are set from size', () => { render(<SVGIcon size={IconSize.sm} />); const svg = screen.getByRole('img', { hidden: true }); expect(svg).toHaveAttribute('width', '1em'); expect(svg).toHaveAttribute('height', '1em'); }); test('aria-hidden is true if no title is specified', () => { render(<SVGIcon />); expect(screen.getByRole('img', { hidden: true })).toHaveAttribute('aria-hidden', 'true'); }); test('title is not renderd if a title is not passed', () => { render(<SVGIcon />); expect(screen.getByRole('img', { hidden: true }).querySelector('title')).toBeNull(); }); test('aria-labelledby is null if a title is not passed', () => { render(<SVGIcon />); expect(screen.getByRole('img', { hidden: true })).not.toHaveAttribute('aria-labelledby'); }); test('title is rendered', () => { const title = 'icon title'; render(<SVGIcon title={title} />); expect(screen.getByText(title)).toBeInTheDocument(); }); test('aria-labelledby matches title id', () => { render(<SVGIcon title="icon title" />); const svg = screen.getByRole('img', { hidden: true }); const labelledby = svg.getAttribute('aria-labelledby'); const titleId = svg.querySelector('title').getAttribute('id'); expect(labelledby).toEqual(titleId); }); test('additional props should be spread to the root svg element', () => { render(<SVGIcon data-testid="icon" />); expect(screen.getByTestId('icon')).toBeInTheDocument(); });
jelly/patternfly-react
packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyReadOnlyExpandedByDefault.tsx
import React from 'react'; import { ClipboardCopy, ClipboardCopyVariant } from '@patternfly/react-core'; export const ClipboardCopyReadOnlyExpandedByDefault: React.FunctionComponent = () => ( <ClipboardCopy isReadOnly isExpanded hoverTip="Copy" clickTip="Copied" variant={ClipboardCopyVariant.expansion}> 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. </ClipboardCopy> );
jelly/patternfly-react
packages/react-core/src/components/Panel/Panel.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Panel/panel'; import { css } from '@patternfly/react-styles'; export interface PanelProps extends React.HTMLProps<HTMLDivElement> { /** Content rendered inside the panel */ children?: React.ReactNode; /** Class to add to outer div */ className?: string; /** Adds panel variant styles */ variant?: 'raised' | 'bordered'; /** Flag to add scrollable styling to the panel */ isScrollable?: boolean; } export const Panel: React.FunctionComponent<PanelProps> = ({ className, children, variant, isScrollable, ...props }: PanelProps) => ( <div className={css( styles.panel, variant === 'raised' && styles.modifiers.raised, variant === 'bordered' && styles.modifiers.bordered, isScrollable && styles.modifiers.scrollable, className )} {...props} > {children} </div> ); Panel.displayName = 'Panel';
jelly/patternfly-react
packages/react-log-viewer/src/LogViewer/LogViewerSearch.tsx
import React, { useContext, useEffect, useState } from 'react'; import { NUMBER_INDEX_DELTA, DEFAULT_FOCUS, DEFAULT_INDEX, DEFAULT_SEARCH_INDEX, DEFAULT_MATCH } from './utils/constants'; import { SearchInput, SearchInputProps } from '@patternfly/react-core'; import { LogViewerToolbarContext, LogViewerContext } from './LogViewerContext'; import { escapeString, searchForKeyword, searchedKeyWordType } from './utils/utils'; export interface LogViewerSearchProps extends SearchInputProps { /** Place holder text inside of searchbar */ placeholder: string; /** Minimum number of characters required for searching */ minSearchChars: number; } export const LogViewerSearch: React.FunctionComponent<LogViewerSearchProps> = ({ placeholder = 'Search', minSearchChars = 1, ...props }) => { const [indexAdjuster, setIndexAdjuster] = useState(0); const { searchedWordIndexes, scrollToRow, setSearchedInput, setCurrentSearchedItemCount, setRowInFocus, setSearchedWordIndexes, currentSearchedItemCount, searchedInput, itemCount } = useContext(LogViewerToolbarContext); const { parsedData } = useContext(LogViewerContext); const defaultRowInFocus = { rowIndex: DEFAULT_FOCUS, matchIndex: DEFAULT_MATCH }; /* Defaulting the first focused row that contain searched keywords */ useEffect(() => { if (hasFoundResults) { setIndexAdjuster(1); } else { setIndexAdjuster(0); } }, [searchedWordIndexes]); /* Updating searchedResults context state given changes in searched input */ useEffect(() => { let foundKeywordIndexes: (searchedKeyWordType | null)[] = []; const adjustedSearchedInput = escapeString(searchedInput); if (adjustedSearchedInput !== '' && adjustedSearchedInput.length >= minSearchChars) { foundKeywordIndexes = searchForKeyword(adjustedSearchedInput, parsedData, itemCount || parsedData.length); if (foundKeywordIndexes.length !== 0) { setSearchedWordIndexes(foundKeywordIndexes); scrollToRow(foundKeywordIndexes[DEFAULT_SEARCH_INDEX]); setCurrentSearchedItemCount(DEFAULT_INDEX); } } if (!adjustedSearchedInput) { setRowInFocus(defaultRowInFocus); } }, [searchedInput]); const hasFoundResults = searchedWordIndexes.length > 0 && searchedWordIndexes[0]?.rowIndex !== -1; /* Clearing out the search input */ const handleClear = (): void => { setSearchedInput(''); setCurrentSearchedItemCount(DEFAULT_INDEX); setSearchedWordIndexes([]); setRowInFocus(defaultRowInFocus); }; /* Moving focus over to next row containing searched word */ const handleNextSearchItem = (): void => { const adjustedSearchedItemCount = (currentSearchedItemCount + NUMBER_INDEX_DELTA) % searchedWordIndexes.length; setCurrentSearchedItemCount(adjustedSearchedItemCount); scrollToRow(searchedWordIndexes[adjustedSearchedItemCount]); }; /* Moving focus over to next row containing searched word */ const handlePrevSearchItem = (): void => { let adjustedSearchedItemCount = currentSearchedItemCount - NUMBER_INDEX_DELTA; if (adjustedSearchedItemCount < DEFAULT_INDEX) { adjustedSearchedItemCount += searchedWordIndexes.length; } setCurrentSearchedItemCount(adjustedSearchedItemCount); scrollToRow(searchedWordIndexes[adjustedSearchedItemCount]); }; return ( <SearchInput placeholder={placeholder} value={searchedInput} resultsCount={`${currentSearchedItemCount + indexAdjuster} / ${hasFoundResults ? searchedWordIndexes.length : 0}`} {...props} onChange={(input, event) => { props.onChange && props.onChange(input, event); setSearchedInput(input); }} onNextClick={event => { props.onNextClick && props.onNextClick(event); handleNextSearchItem(); }} onPreviousClick={event => { props.onPreviousClick && props.onPreviousClick(event); handlePrevSearchItem(); }} onClear={event => { props.onClear && props.onClear(event); handleClear(); }} /> ); }; LogViewerSearch.displayName = 'LogViewerSearch';
jelly/patternfly-react
packages/react-topology/src/components/edges/DefaultConnectorTag.tsx
<filename>packages/react-topology/src/components/edges/DefaultConnectorTag.tsx import * as React from 'react'; import Point from '../../geom/Point'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; import { StatusModifier, useSize } from '../../utils'; import { NodeStatus } from '../../types'; interface DefaultConnectorTagProps { className?: string; startPoint: Point; endPoint: Point; tag: string; status?: NodeStatus; paddingX?: number; paddingY?: number; } const DefaultConnectorTag: React.FunctionComponent<DefaultConnectorTagProps> = ({ className, startPoint, endPoint, tag, status, paddingX = 4, paddingY = 2, ...other }) => { const [textSize, textRef] = useSize([tag, className]); const { width, height, startX, startY } = React.useMemo(() => { if (!textSize) { return { width: 0, height: 0, startX: 0, startY: 0 }; } const width = textSize ? textSize.width + paddingX * 2 : 0; const height = textSize ? textSize.height + paddingY * 2 : 0; const startX = -width / 2; const startY = -height / 2; return { width, height, startX, startY }; }, [textSize, paddingX, paddingY]); return ( <g className={css(styles.topologyEdgeTag, className, StatusModifier[status])} transform={`translate(${startPoint.x + (endPoint.x - startPoint.x) * 0.5}, ${startPoint.y + (endPoint.y - startPoint.y) * 0.5})`} > {textSize && ( <rect className={css(styles.topologyEdgeTagBackground)} x={startX} y={startY} width={width} height={height} rx={3} ry={3} /> )} <text dy="0.35em" {...other} ref={textRef} x={startX + paddingX} y={0}> {tag} </text> </g> ); }; export default DefaultConnectorTag;
jelly/patternfly-react
packages/react-core/src/components/AboutModal/__tests__/AboutModal.test.tsx
<filename>packages/react-core/src/components/AboutModal/__tests__/AboutModal.test.tsx import * as React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { AboutModal, AboutModalProps } from '../AboutModal'; const props: AboutModalProps = { onClose: jest.fn(), children: 'modal content', productName: 'Product Name', trademark: 'Trademark and copyright information here', brandImageSrc: 'brandImg...', brandImageAlt: 'Brand Image' }; describe('AboutModal', () => { test('closes with escape', () => { render(<AboutModal {...props} isOpen />); userEvent.type(screen.getByRole('dialog'), '{esc}'); expect(props.onClose).toHaveBeenCalled(); }); test('does not render the modal when isOpen is not specified', () => { render(<AboutModal {...props} />); expect(screen.queryByRole('dialog')).toBeNull(); }); test('Each modal is given new aria-describedby and aria-labelledby', () => { const first = new AboutModal(props); const second = new AboutModal(props); expect(first.ariaLabelledBy).not.toBe(second.ariaLabelledBy); expect(first.ariaDescribedBy).not.toBe(second.ariaDescribedBy); }); test('Console error is generated when the logoImageSrc is provided without logoImageAlt', () => { const noImgAltrops = { onClose: jest.fn(), children: 'modal content', productName: 'Product Name', trademark: 'Trademark and copyright information here', brandImageSrc: 'brandImg...', logoImageSrc: 'logoImg...' } as any; const myMock = jest.fn() as any; global.console = { error: myMock } as any; render(<AboutModal {...noImgAltrops}>Test About Modal</AboutModal>); expect(myMock).toHaveBeenCalled(); }); });