repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/themes/donut-threshold-theme.ts
/* eslint-disable camelcase */ import chart_donut_threshold_first_Color from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_first_Color'; import chart_donut_threshold_second_Color from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_second_Color'; import chart_donut_threshold_third_Color from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_third_Color'; import chart_donut_threshold_dynamic_pie_Height from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_dynamic_pie_Height'; import chart_donut_threshold_dynamic_pie_Padding from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_dynamic_pie_Padding'; import chart_donut_threshold_dynamic_pie_Width from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_dynamic_pie_Width'; import chart_donut_threshold_static_pie_Height from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_static_pie_Height'; import chart_donut_threshold_static_pie_angle_Padding from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_static_pie_angle_Padding'; import chart_donut_threshold_static_pie_Padding from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_static_pie_Padding'; import chart_donut_threshold_static_pie_Width from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_static_pie_Width'; // Donut threshold dynamic theme export const DonutThresholdDynamicTheme = { legend: { colorScale: [chart_donut_threshold_second_Color.value, chart_donut_threshold_third_Color.value] }, pie: { height: chart_donut_threshold_dynamic_pie_Height.value, padding: chart_donut_threshold_dynamic_pie_Padding.value, width: chart_donut_threshold_dynamic_pie_Width.value } }; // Donut threshold static theme export const DonutThresholdStaticTheme = { pie: { colorScale: [ chart_donut_threshold_first_Color.value, chart_donut_threshold_second_Color.value, chart_donut_threshold_third_Color.value ], height: chart_donut_threshold_static_pie_Height.value, padAngle: chart_donut_threshold_static_pie_angle_Padding.value, padding: chart_donut_threshold_static_pie_Padding.value, width: chart_donut_threshold_static_pie_Width.value } };
jelly/patternfly-react
packages/react-core/src/components/Brand/Brand.tsx
<filename>packages/react-core/src/components/Brand/Brand.tsx import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Brand/brand'; import { setBreakpointCssVars } from '../../helpers'; export interface BrandProps extends React.DetailedHTMLProps<React.ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement> { /** Transforms the Brand into a <picture> element from an <img> element. Container for <source> child elements. */ children?: React.ReactNode; /** Additional classes added to the either type of Brand. */ className?: string; /** Attribute that specifies the URL of a <img> Brand. For a <picture> Brand this specifies the fallback <img> URL. */ src?: string; /** Attribute that specifies the alt text of a <img> Brand. For a <picture> Brand this specifies the fallback <img> alt text. */ alt: string; /** Widths at various breakpoints for a <picture> Brand. */ widths?: { default?: string; sm?: string; md?: string; lg?: string; xl?: string; '2xl'?: string; }; /** Heights at various breakpoints for a <picture> Brand. */ heights?: { default?: string; sm?: string; md?: string; lg?: string; xl?: string; '2xl'?: string; }; } export const Brand: React.FunctionComponent<BrandProps> = ({ className = '', src = '', alt, children, widths, heights, style, ...props }: BrandProps) => { if (children !== undefined && widths !== undefined) { style = { ...style, ...setBreakpointCssVars(widths, '--pf-c-brand--Width') }; } if (children !== undefined && heights !== undefined) { style = { ...style, ...setBreakpointCssVars(heights, '--pf-c-brand--Height') }; } return ( /** the brand component currently contains no styling the 'pf-c-brand' string will be used for the className */ children !== undefined ? ( <picture className={css(styles.brand, styles.modifiers.picture, className)} style={style} {...props}> {children} <img src={src} alt={alt} /> </picture> ) : ( <img {...props} className={css(styles.brand, className)} src={src} alt={alt} /> ) ); }; Brand.displayName = 'Brand';
jelly/patternfly-react
packages/react-core/src/components/Form/__tests__/FormSection.test.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import { FormSection } from '../FormSection'; import { render } from '@testing-library/react'; test('Check form section example against snapshot', () => { const Section = <FormSection />; const { asFragment } = render(Section); expect(asFragment()).toMatchSnapshot(); }); test('Check form section example with title', () => { const Section = <FormSection title="Title" titleElement="h4" />; const { asFragment } = render(Section); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/Brand/examples/BrandBasic.tsx
import React from 'react'; import { Brand } from '@patternfly/react-core'; import pfLogo from './pfLogo.svg'; export const BrandBasic: React.FunctionComponent = () => <Brand src={pfLogo} alt="Patternfly Logo" />;
jelly/patternfly-react
packages/react-topology/src/Visualization.ts
import { ComponentType } from 'react'; import { action, computed, observable } from 'mobx'; import * as _ from 'lodash'; import { Controller, Graph, Edge, Node, ComponentFactory, GraphElement, ElementFactory, ElementModel, isEdge, isNode, Model, EventListener, ModelKind, LayoutFactory, Layout, ViewPaddingSettings } from './types'; import defaultElementFactory from './elements/defaultElementFactory'; import Stateful from './utils/Stateful'; export class Visualization extends Stateful implements Controller { @observable.shallow elements: { [id: string]: GraphElement } = {}; @observable.ref private graph?: Graph; @observable private viewConstraintsEnabled: boolean = true; @observable.ref private viewPaddingSettings: ViewPaddingSettings = { paddingPercentage: 50 }; @computed private get viewPadding(): number { const { padding, paddingPercentage } = this.viewPaddingSettings; if (paddingPercentage) { const graph = this.graph; if (!graph) { return 0; } const { width: viewWidth, height: viewHeight } = graph.getBounds(); return Math.max(viewWidth, viewHeight) * graph.getScale() * (paddingPercentage / 100); } return padding; } private layoutFactories: LayoutFactory[] = []; private componentFactories: ComponentFactory[] = []; private elementFactories: ElementFactory[] = [defaultElementFactory]; private eventListeners: { [type: string]: EventListener[] } = {}; @observable.shallow private readonly store = {}; getStore<S = {}>(): S { return this.store as S; } @action fromModel(model: Model, merge: boolean = true): void { const oldGraph = this.graph; // If not merging, clear out the old elements if (!merge) { _.forIn(this.elements, element => this.removeElement(element)); } // Create the graph if given in the model if (model.graph) { this.graph = this.createElement<Graph>(ModelKind.graph, model.graph); if (!merge && oldGraph) { this.graph.setDimensions(oldGraph.getDimensions()); } } // Create elements const validIds: string[] = []; const idToElement: { [id: string]: ElementModel } = {}; model.nodes && model.nodes.forEach(n => { idToElement[n.id] = n; this.createElement<Node>(ModelKind.node, n); validIds.push(n.id); }); model.edges && model.edges.forEach(e => { idToElement[e.id] = e; this.createElement<Edge>(ModelKind.edge, e); validIds.push(e.id); }); // merge data if (model.graph && this.graph) { this.graph.setModel(model.graph); } validIds.push(this.graph.getId()); const processed: { [id: string]: boolean } = {}; // process bottom up const processElement = (element: ElementModel): void => { if (element.children) { element.children.forEach(id => processElement(idToElement[id])); } if (!processed[element.id]) { processed[element.id] = true; this.elements[element.id].setModel(element); } }; model.nodes && model.nodes.forEach(processElement); model.edges && model.edges.forEach(processElement); // remove all stale elements if (merge) { _.forIn(this.elements, element => { if (!validIds.includes(element.getId())) { this.removeElement(element); } }); if (oldGraph && oldGraph !== this.graph) { this.removeElement(oldGraph); } } if (this.graph) { this.parentOrphansToGraph(this.graph, validIds); } } hasGraph(): boolean { return !!this.graph; } getGraph(): Graph { if (!this.graph) { throw new Error('Graph has not been set.'); } return this.graph; } @action setGraph(graph: Graph) { if (this.graph !== graph) { if (this.graph) { this.graph.setController(undefined); } this.graph = graph; graph.setController(this); // TODO clean up and populate registries } } getElements(): GraphElement[] { return _.values(this.elements); } toModel(): Model { const graph = this.getGraph(); const nodes = this.getElements().filter(n => isNode(n)) as Node[]; const edges = this.getElements().filter(e => isEdge(e)) as Edge[]; return { graph: graph.toModel(), nodes: nodes.map(n => n.toModel()), edges: edges.map(e => e.toModel()) }; } addElement(element: GraphElement): void { if (this.elements[element.getId()]) { throw new Error(`Duplicate element for ID '${element.getId()}`); } element.setController(this); this.elements[element.getId()] = element; } removeElement(element: GraphElement): void { if (this.elements[element.getId()]) { element.remove(); // unparent all of the element's children such that they can be reparented element .getChildren() .slice() .forEach(child => child.remove()); element.destroy(); element.setController(undefined); delete this.elements[element.getId()]; } } getElementById(id: string): GraphElement | undefined { return this.elements[id]; } getNodeById(id: string): Node | undefined { const node = this.elements[id]; if (node && isNode(node)) { return node; } return undefined; } getEdgeById(id: string): Edge | undefined { const edge = this.elements[id]; if (edge && isEdge(edge)) { return edge; } return undefined; } getComponent(kind: ModelKind, type: string): ComponentType<{ element: GraphElement }> { for (const factory of this.componentFactories) { const component = factory(kind, type); if (component) { return component; } } throw new Error(`Could not find component for: Kind '${kind}', Type '${type}'`); } registerLayoutFactory(factory: LayoutFactory) { this.layoutFactories.unshift(factory); } getLayout(type: string): Layout | undefined { for (const factory of this.layoutFactories) { const layout = factory(type, this.getGraph()); if (layout) { return layout; } } throw new Error(`Could not find layout for type: ${type}`); } setRenderConstraint(constrained: boolean, viewPadding?: ViewPaddingSettings) { this.viewConstraintsEnabled = constrained; // only update the view padding if given, this makes for ease of turning on/off w/o losing settings if (viewPadding !== undefined) { this.viewPaddingSettings = viewPadding; } } shouldRenderNode(node: Node): boolean { if (!this.viewConstraintsEnabled) { return true; } return this.graph.isNodeInView(node, { padding: this.viewPadding }); } registerComponentFactory(factory: ComponentFactory) { this.componentFactories.unshift(factory); } registerElementFactory(factory: ElementFactory): void { this.elementFactories.unshift(factory); } addEventListener<L extends EventListener = EventListener>(type: string, listener: L): Controller { if (!this.eventListeners[type]) { this.eventListeners[type] = [listener]; } else { this.eventListeners[type].push(listener); } return this; } removeEventListener(type: string, listener: EventListener): Controller { if (!this.eventListeners[type]) { return this; } const listeners = this.eventListeners[type]; const l: EventListener[] = []; for (let i = 0, { length } = listeners; i < length; i++) { if (listeners[i] !== listener) { l.push(listeners[i]); } } if (l.length) { this.eventListeners[type] = l; } else { delete this.eventListeners[type]; } return this; } fireEvent(type: string, ...args: any): void { const listeners = this.eventListeners[type]; if (listeners) { for (let i = 0, { length } = listeners; i < length; i++) { listeners[i](...args); } } } private createElement<E extends GraphElement>(kind: ModelKind, elementModel: ElementModel): E { const existingElement = this.elements[elementModel.id]; if (existingElement) { return existingElement as E; } for (const factory of this.elementFactories) { const element = factory(kind, elementModel.type); if (element) { this.initElement(element, elementModel); // cast to return type return element as E; } } throw new Error(`Could not create element for: ${JSON.stringify(elementModel)}`); } private initElement(element: GraphElement, model: ElementModel): void { // set require fields element.setId(model.id); element.setType(model.type); element.setController(this); this.addElement(element); } private parentOrphansToGraph(graph: Graph, validIds: string[]): void { this.getElements().forEach((element: GraphElement) => { if (element !== this.graph && (!element.hasParent() || !validIds.includes(element.getParent().getId()))) { graph.appendChild(element); } }); } }
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/themes/dark/cyan-color-theme.ts
<reponame>jelly/patternfly-react /* eslint-disable camelcase */ import chart_color_cyan_100 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_100'; import chart_color_cyan_200 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_200'; import chart_color_cyan_300 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_300'; import chart_color_cyan_400 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_400'; import chart_color_cyan_500 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_500'; import { ColorTheme } from '../color-theme'; // Color scale // See https://docs.google.com/document/d/1cw10pJFXWruB1SA8TQwituxn5Ss6KpxYPCOYGrH8qAY/edit const COLOR_SCALE = [ chart_color_cyan_300.value, chart_color_cyan_100.value, chart_color_cyan_500.value, chart_color_cyan_200.value, chart_color_cyan_400.value ]; export const DarkCyanColorTheme = ColorTheme({ COLOR_SCALE });
jelly/patternfly-react
packages/react-table/src/components/Table/utils/formatters.test.tsx
<reponame>jelly/patternfly-react import { defaultTitle } from './formatters'; describe('formatters', () => { test('defaultTitle', () => { expect(defaultTitle('test')).toBe('test'); expect(defaultTitle({ title: 'test' })).toBe('test'); }); });
jelly/patternfly-react
packages/react-core/src/components/FormSelect/__tests__/FormSelect.test.tsx
<filename>packages/react-core/src/components/FormSelect/__tests__/FormSelect.test.tsx<gh_stars>0 import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { FormSelect } from '../FormSelect'; import { FormSelectOption } from '../FormSelectOption'; import { FormSelectOptionGroup } from '../FormSelectOptionGroup'; import { ValidatedOptions } from '../../../helpers/constants'; const props = { options: [ { value: 'please choose', label: 'Please Choose', disabled: true }, { value: 'mr', label: 'Mr', disabled: false }, { value: 'miss', label: 'Miss', disabled: false }, { value: 'mrs', label: 'Mrs', disabled: false }, { value: 'ms', label: 'Ms', disabled: false }, { value: 'dr', label: 'Dr', disabled: false }, { value: 'other', label: 'Other', disabled: true } ], value: 'mrs' }; const groupedProps = { groups: [ { groupLabel: 'Group1', disabled: false, options: [ { value: '1', label: 'The First Option', disabled: false }, { value: '2', label: 'Second option is selected by default', disabled: false } ] }, { groupLabel: 'Group2', disabled: false, options: [ { value: '3', label: 'The Third Option', disabled: false }, { value: '4', label: 'The Fourth option', disabled: false } ] }, { groupLabel: 'Group3', disabled: true, options: [ { value: '5', label: 'The Fifth Option', disabled: false }, { value: '6', label: 'The Sixth option', disabled: false } ] } ], value: '2' }; describe('FormSelect', () => { test('Simple FormSelect input', () => { const { asFragment } = render( <FormSelect value={props.value} aria-label="simple FormSelect"> {props.options.map((option, index) => ( <FormSelectOption isDisabled={option.disabled} key={index} value={option.value} label={option.label} /> ))} </FormSelect> ); expect(asFragment()).toMatchSnapshot(); }); test('Grouped FormSelect input', () => { const { asFragment } = render( <FormSelect value={groupedProps.value} aria-label="grouped FormSelect"> {groupedProps.groups.map((group, index) => ( <FormSelectOptionGroup isDisabled={group.disabled} key={index} label={group.groupLabel}> {group.options.map((option, i) => ( <FormSelectOption isDisabled={option.disabled} key={i} value={option.value} label={option.label} /> ))} </FormSelectOptionGroup> ))} </FormSelect> ); expect(asFragment()).toMatchSnapshot(); }); test('Disabled FormSelect input ', () => { const { asFragment } = render( <FormSelect isDisabled aria-label="disabled FormSelect"> <FormSelectOption key={1} value={props.options[1].value} label={props.options[1].label} /> </FormSelect> ); expect(asFragment()).toMatchSnapshot(); }); test('FormSelect input with aria-label does not generate console error', () => { const myMock = jest.fn() as any; global.console = { error: myMock } as any; const { asFragment } = render( <FormSelect aria-label="label"> <FormSelectOption key={1} value={props.options[1].value} label={props.options[1].label} /> </FormSelect> ); expect(asFragment()).toMatchSnapshot(); expect(myMock).not.toHaveBeenCalled(); }); test('FormSelect input with id does not generate console error', () => { const myMock = jest.fn() as any; global.console = { error: myMock } as any; const { asFragment } = render( <FormSelect id="id" aria-label="label"> <FormSelectOption key={1} value={props.options[1].value} label={props.options[1].label} /> </FormSelect> ); expect(asFragment()).toMatchSnapshot(); expect(myMock).not.toHaveBeenCalled(); }); test('FormSelect input with no aria-label or id generates console error', () => { const myMock = jest.fn() as any; global.console = { error: myMock } as any; const { asFragment } = render( <FormSelect> <FormSelectOption key={1} value={props.options[1].value} label={props.options[1].label} /> </FormSelect> ); expect(asFragment()).toMatchSnapshot(); expect(myMock).toHaveBeenCalled(); }); test('invalid FormSelect input', () => { const { asFragment } = render( <FormSelect validated="error" aria-label="invalid FormSelect"> <FormSelectOption key={1} value={props.options[1].value} label={props.options[1].label} /> </FormSelect> ); expect(asFragment()).toMatchSnapshot(); }); test('validated success FormSelect input', () => { const { asFragment } = render( <FormSelect validated={ValidatedOptions.success} aria-label="validated FormSelect"> <FormSelectOption key={1} value={props.options[1].value} label={props.options[1].label} /> </FormSelect> ); const formSelect = screen.getByLabelText('validated FormSelect'); expect(formSelect).toHaveClass('pf-m-success'); expect(asFragment()).toMatchSnapshot(); }); test('validated warning FormSelect input', () => { const { asFragment } = render( <FormSelect validated={ValidatedOptions.warning} aria-label="validated FormSelect"> <FormSelectOption key={1} value={props.options[1].value} label={props.options[1].label} /> </FormSelect> ); const formSelect = screen.getByLabelText('validated FormSelect'); expect(formSelect).toHaveClass('pf-m-warning'); expect(asFragment()).toMatchSnapshot(); }); test('required FormSelect input', () => { render( <FormSelect isRequired aria-label="required FormSelect"> <FormSelectOption key={1} value={props.options[1].value} label={props.options[1].label} /> </FormSelect> ); expect(screen.getByLabelText('required FormSelect')).toHaveAttribute('required'); }); test('FormSelect passes value and event to onChange handler', () => { const myMock = jest.fn(); render( <FormSelect onChange={myMock} aria-label="Some label"> <FormSelectOption key={1} value={props.options[1].value} label={props.options[1].label} /> </FormSelect> ); userEvent.selectOptions(screen.getByLabelText('Some label'), 'Mr'); expect(myMock).toHaveBeenCalled(); expect(myMock.mock.calls[0][0]).toEqual('mr'); }); });
jelly/patternfly-react
packages/react-topology/src/layouts/ColaGroupsNode.ts
<filename>packages/react-topology/src/layouts/ColaGroupsNode.ts import * as webcola from 'webcola'; import { isNode, Node } from '../types'; import { LayoutNode } from './LayoutNode'; import { Point } from '../geom'; export class ColaGroupsNode extends LayoutNode implements webcola.Node { // fixed is used by Cola during node additions: 1 for fixed public fixed: number = 0; constructor(node: Node, distance: number, index: number = -1) { super(node, distance, index); // TODO: Investigate why the issue with rectangular nodes causing the layout to become vertical // may need to do more here like what is done in ColaNode } setFixed(fixed: boolean): void { super.setFixed(fixed); this.fixed = fixed ? 1 : 0; } update() { if (!this.isFixed && this.xx != null && this.yy != null) { if (this.node.isGroup()) { const prevLocation = this.node.getBounds().getCenter(); const xOffset = this.xx - prevLocation.x; const yOffset = this.yy - prevLocation.y; this.node.getChildren().forEach(child => { if (isNode(child)) { const node = child as Node; const position = node.getPosition(); node.setPosition(new Point(position.x + xOffset, position.y + yOffset)); } }); } else { this.setPosition(this.xx, this.yy); } } this.xx = undefined; this.yy = undefined; } get width(): number { return this.nodeBounds.width + this.distance * 2; } get height(): number { return this.nodeBounds.height + this.distance * 2; } get radius(): number { const bounds = this.nodeBounds; return Math.max(bounds.width, bounds.height) / 2; } get collisionRadius(): number { return this.radius + this.distance; } }
jelly/patternfly-react
packages/react-core/src/components/DragDrop/__tests__/DragDrop.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { DragDrop, Draggable, Droppable } from '../'; test('renders some divs', () => { const { asFragment } = render( <DragDrop> <Droppable droppableId="dropzone"> <Draggable id="draggable1">item 1</Draggable> <Draggable id="draggable2">item 2</Draggable> </Droppable> </DragDrop> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-integration/cypress/integration/toolbar.spec.ts
describe('Data Toolbar Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/toolbar-demo-nav-link'); }); it('Verify widths styling mapped ', () => { cy.get('#width-item').should( 'have.attr', 'style', '--pf-c-toolbar__item--Width:100px; --pf-c-toolbar__item--Width-on-sm:80px; --pf-c-toolbar__item--Width-on-md:150px; --pf-c-toolbar__item--Width-on-lg:200px; --pf-c-toolbar__item--Width-on-xl:250px; --pf-c-toolbar__item--Width-on-2xl:300px;' ); }); it('Verify no inset applied for default viewport size (1200) ', () => { cy.get('#toolbar-no-inset.pf-m-inset-none').should('exist'); }); it('Verify Small inset applied for default viewport size (1200) ', () => { cy.get('#toolbar-sm-inset.pf-m-inset-sm').should('exist'); }); it('Verify Medium inset applied for default viewport size (1200) ', () => { cy.get('#toolbar-md-inset.pf-m-inset-md').should('exist'); }); it('Verify Large inset applied for default viewport size (1200) ', () => { cy.get('#toolbar-lg-inset.pf-m-inset-lg').should('exist'); }); it('Verify Extra Large inset applied for default viewport size (1200) ', () => { cy.get('#toolbar-xl-inset.pf-m-inset-xl').should('exist'); }); it('Verify 2XL inset applied for default viewport size (1200) ', () => { // 2xl should only be added for viewport size >= 1450 cy.get('#toolbar-2xl-inset.pf-m-inset-2xl').should('not.exist'); }); describe('Toggle group and filter chips are appropriately responsive', () => { context('wide viewport', () => { beforeEach(() => { cy.viewport(1200, 800); }); it('displays toggle group contents', () => { cy.get('#demo-toggle-group #toolbar-demo-search').should('be.visible'); cy.get('#demo-toggle-group #toolbar-demo-filters').should('be.visible'); cy.get('.pf-c-toolbar__expandable-content').should('not.be.visible'); }); it('displays filter chips', () => { cy.get('.pf-m-chip-group').should('be.visible'); cy.get('.pf-m-filters-applied-message').should('not.exist'); cy.get('.pf-c-toolbar__item .pf-c-button').should('be.visible'); cy.get('.pf-c-toolbar__item .pf-c-chip-group__close').should('be.visible'); cy.get('.pf-c-toolbar__item .pf-c-button').contains('Clear filters'); }); }); context('narrow viewport', () => { beforeEach(() => { cy.viewport(768, 800); }); it('displays toggle icon', () => { cy.get('#demo-toggle-group .pf-c-toolbar__toggle').should('be.visible'); cy.get('#demo-toggle-group #toolbar-demo-search').should('not.be.visible'); cy.get('#demo-toggle-group #toolbar-demo-filters').should('not.be.visible'); cy.get('.pf-c-toolbar__expandable-content').should('not.be.visible'); }); it('displays X filters applied message', () => { cy.get('.pf-m-chip-container .pf-m-chip-group').should('not.exist'); cy.get('.pf-c-toolbar__item').should('contain.text', 'filters applied'); cy.get('.pf-c-toolbar__item').should('contain.text', 'Applied filters: '); cy.get('.pf-c-toolbar__item .pf-c-button').should('be.visible'); cy.get('.pf-c-toolbar__item .pf-c-chip-group__close').should('not.be.visible'); cy.get('.pf-c-toolbar__item .pf-c-button').contains('Clear filters'); }); }); }); describe('Toggle group toggles appropriately when toggle not managed by consumer', () => { beforeEach(() => { cy.viewport(768, 800); }); it('Verify toggle dropdown', () => { cy.get('#demo-toggle-group .pf-c-toolbar__toggle').should('be.visible'); }); xit('Verify expandable content expanded', () => { cy.get('#demo-toggle-group .pf-c-toolbar__toggle button') .last() .click(); cy.get('.pf-c-toolbar__expandable-content').should('have.class', 'pf-m-expanded'); cy.get('.pf-c-toolbar__expandable-content').should('be.visible'); cy.get('.pf-m-chip-container').should('be.visible'); cy.get('.pf-c-toolbar__item .pf-c-button').should('be.visible'); cy.get('.pf-c-toolbar__item .pf-c-chip-group__close').should('be.visible'); cy.get('.pf-c-toolbar__item .pf-c-button').contains('Clear filters'); cy.get('#demo-toggle-group .pf-c-toolbar__toggle button') .last() .click(); cy.get('.pf-c-toolbar__expandable-content').should('not.have.class', 'pf-m-expanded'); cy.get('.pf-c-toolbar__expandable-content').should('not.be.visible'); cy.get('.pf-m-chip-container').should('not.be.visible'); cy.get('.pf-c-toolbar__item .pf-c-button').should('be.visible'); cy.get('.pf-c-toolbar__item .pf-c-chip-group__close').should('not.be.visible'); cy.get('.pf-c-toolbar__item .pf-c-button').contains('Clear filters'); }); }); });
jelly/patternfly-react
packages/react-core/src/components/List/__tests__/List.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import BookOpen from '@patternfly/react-icons/dist/esm/icons/book-open-icon'; import Key from '@patternfly/react-icons/dist/esm/icons/key-icon'; import Desktop from '@patternfly/react-icons/dist/esm/icons/desktop-icon'; import { List, ListVariant, ListComponent, OrderType } from '../List'; import { ListItem } from '../ListItem'; const ListItems = () => ( <List> <ListItem>First</ListItem> <ListItem>Second</ListItem> <ListItem>Third</ListItem> </List> ); describe('List', () => { test('simple list', () => { const { asFragment } = render( <List> <ListItems /> </List> ); expect(asFragment()).toMatchSnapshot(); }); test('inline list', () => { const { asFragment } = render( <List variant={ListVariant.inline}> <ListItems /> </List> ); expect(asFragment()).toMatchSnapshot(); }); test('ordered list', () => { const { asFragment } = render( <List component={ListComponent.ol}> <ListItem>Apple</ListItem> <ListItem>Banana</ListItem> <ListItem>Orange</ListItem> </List> ); expect(asFragment()).toMatchSnapshot(); }); test('ordered list starts with 2nd item', () => { render( <List component={ListComponent.ol} start={2}> <ListItem>Banana</ListItem> <ListItem>Orange</ListItem> </List> ); expect(screen.getByRole('list')).toHaveAttribute('start', '2'); }); test('ordered list items will be numbered with uppercase letters', () => { render( <List component={ListComponent.ol} type={OrderType.uppercaseLetter}> <ListItem>Banana</ListItem> <ListItem>Orange</ListItem> </List> ); expect(screen.getByRole('list')).toHaveAttribute('type', 'A'); }); test('inlined ordered list', () => { render( <List variant={ListVariant.inline} component={ListComponent.ol}> <ListItem>Apple</ListItem> <ListItem>Banana</ListItem> <ListItem>Orange</ListItem> </List> ); expect(screen.getByRole('list')).toHaveClass('pf-m-inline'); }); test('bordered list', () => { render( <List isBordered> <ListItems /> </List> ); expect(screen.getAllByRole('list')[0]).toHaveClass('pf-m-bordered'); }); test('plain list', () => { render( <List isPlain> <ListItems /> </List> ); expect(screen.getAllByRole('list')[0]).toHaveClass('pf-m-plain'); }); test('icon list', () => { const { asFragment } = render( <List isPlain> <ListItem icon={<BookOpen />}>Apple</ListItem> <ListItem icon={<Key />}>Banana</ListItem> <ListItem icon={<Desktop />}>Orange</ListItem> </List> ); expect(asFragment()).toMatchSnapshot(); }); test('icon large list', () => { const { asFragment } = render( <List iconSize="large"> <ListItem icon={<BookOpen />}>Apple</ListItem> <ListItem icon={<Key />}>Banana</ListItem> <ListItem icon={<Desktop />}>Orange</ListItem> </List> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/Button/examples/ButtonVariations.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { Button } from '@patternfly/react-core'; import TimesIcon from '@patternfly/react-icons/dist/esm/icons/times-icon'; import PlusCircleIcon from '@patternfly/react-icons/dist/esm/icons/plus-circle-icon'; import ExternalLinkSquareAltIcon from '@patternfly/react-icons/dist/esm/icons/external-link-square-alt-icon'; import CopyIcon from '@patternfly/react-icons/dist/esm/icons/copy-icon'; export const ButtonVariations: React.FunctionComponent = () => ( <React.Fragment> <Button variant="primary">Primary</Button> <Button variant="secondary">Secondary</Button>{' '} <Button variant="secondary" isDanger> Danger Secondary </Button>{' '} <Button variant="tertiary">Tertiary</Button> <Button variant="danger">Danger</Button>{' '} <Button variant="warning">Warning</Button> <br /> <br /> <Button variant="link" icon={<PlusCircleIcon />}> Link </Button>{' '} <Button variant="link" icon={<ExternalLinkSquareAltIcon />} iconPosition="right"> Link </Button>{' '} <Button variant="link" isInline> Inline link </Button>{' '} <Button variant="link" isDanger> Danger link </Button> <br /> <br /> <Button variant="plain" aria-label="Action"> <TimesIcon /> </Button> <br /> <br /> <Button variant="control">Control</Button>{' '} <Button variant="control" aria-label="Copy"> <CopyIcon /> </Button> </React.Fragment> );
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/__tests__/MultipleFileUploadButton.test.tsx
<gh_stars>0 import React from 'react'; import { render } from '@testing-library/react'; import { MultipleFileUploadButton } from '../MultipleFileUploadButton'; describe('MultipleFileUploadButton', () => { test('renders with expected class names', () => { const { asFragment } = render(<MultipleFileUploadButton>Foo</MultipleFileUploadButton>); expect(asFragment()).toMatchSnapshot(); }); test('renders custom class names', () => { const { asFragment } = render(<MultipleFileUploadButton className="test">Foo</MultipleFileUploadButton>); expect(asFragment()).toMatchSnapshot(); }); test('renders with aria-label applied to the button', () => { const { asFragment } = render(<MultipleFileUploadButton aria-label="test">Foo</MultipleFileUploadButton>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/AboutModal/index.ts
export * from './AboutModal';
jelly/patternfly-react
packages/react-core/src/components/Nav/examples/NavDrilldown.tsx
import React from 'react'; import { Nav, MenuContent, MenuItem, MenuList, DrilldownMenu, Menu } from '@patternfly/react-core'; interface MenuHeights { [menuId: string]: number; } const subMenuTwo: JSX.Element = ( <DrilldownMenu id="subMenu-2"> <MenuItem itemId="subMenu-2-breadcrumb" direction="up"> SubMenu 1 - Item 1 </MenuItem> <MenuItem itemId="subMenu-2_item-1" to="#subMenu-2_item-1"> SubMenu 2 - Item 1 </MenuItem> <MenuItem itemId="subMenu-2_item-2" to="#subMenu-2_item-2"> SubMenu 2 - Item 2 </MenuItem> <MenuItem itemId="subMenu-2_item-3" to="#subMenu-2_item-3"> SubMenu 2 - Item 3 </MenuItem> </DrilldownMenu> ); const subMenuOne: JSX.Element = ( <DrilldownMenu id="subMenu-1"> <MenuItem itemId="subMenu-1-breadcrumb" direction="up"> Item 1 </MenuItem> <MenuItem itemId="subMenu-1_item-1" description="SubMenu 2" direction="down" drilldownMenu={subMenuTwo}> SubMenu 1 - Item 1 </MenuItem> <MenuItem itemId="subMenu-1_item-2" to="#subMenu-1_item-2"> SubMenu 1 - Item 2 </MenuItem> <MenuItem itemId="subMenu-1_item-3" to="#subMenu-1_item-3"> SubMenu 1 - Item 3 </MenuItem> </DrilldownMenu> ); export const NavLevelThreeDrill: React.FunctionComponent = () => { const [menuDrilledIn, setMenuDrilledIn] = React.useState<string[]>([]); const [drilldownPath, setDrilldownPath] = React.useState<string[]>([]); const [menuHeights, setMenuHeights] = React.useState<MenuHeights>({}); const [activeMenu, setActiveMenu] = React.useState('rootMenu'); const onDrillIn = (fromItemId: string, toItemId: string, itemId: string) => { setMenuDrilledIn(prevMenuDrilledIn => [...prevMenuDrilledIn, fromItemId]); setDrilldownPath(prevDrilldownPath => [...prevDrilldownPath, itemId]); setActiveMenu(toItemId); }; const onDrillOut = (toItemId: string, _itemId: string) => { setMenuDrilledIn(prevMenuDrilledIn => prevMenuDrilledIn.slice(0, prevMenuDrilledIn.length - 1)); setDrilldownPath(prevDrilldownPath => prevDrilldownPath.slice(0, prevDrilldownPath.length - 1)); setActiveMenu(toItemId); }; const onGetMenuHeight = (menuId: string, height: number) => { if (!menuHeights[menuId] && menuId !== 'rootMenu') { setMenuHeights(prevMenuHeights => ({ ...prevMenuHeights, [menuId]: height })); } }; return ( <Nav> <Menu id="rootMenu" containsDrilldown drilldownItemPath={drilldownPath} drilledInMenus={menuDrilledIn} activeMenu={activeMenu} onDrillIn={onDrillIn} onDrillOut={onDrillOut} onGetMenuHeight={onGetMenuHeight} > <MenuContent menuHeight={`${menuHeights[activeMenu]}px`}> <MenuList> <MenuItem itemId="item-1" direction="down" description="SubMenu 1" drilldownMenu={subMenuOne}> Item 1 </MenuItem> <MenuItem itemId="item-2" to="#item-2"> Item 2 </MenuItem> <MenuItem itemId="item-3" to="#item-3"> Item 3 </MenuItem> </MenuList> </MenuContent> </Menu> </Nav> ); };
jelly/patternfly-react
packages/react-table/src/components/TableComposable/examples/ComposableTableCellWidth.tsx
import React from 'react'; import { TableComposable, Thead, Tr, Th, Tbody, Td } from '@patternfly/react-table'; interface Repository { name: string; branches: string | null; prs: string | null; workspaces: string; lastCommit: string; } export const ComposableTableCellWidth: React.FunctionComponent = () => { // In real usage, this data would come from some external source like an API via props. const repositories: Repository[] = [ { name: 'one', branches: 'two', prs: 'three', workspaces: 'four', lastCommit: 'five' }, { name: 'one - 2', branches: null, prs: null, workspaces: 'four - 2', lastCommit: 'five - 2' }, { name: 'one - 3', branches: 'two - 3', prs: 'three - 3', workspaces: 'four - 3', lastCommit: 'five - 3' } ]; const columnNames = { name: 'Repositories', branches: 'Branches', prs: 'Pull requests', workspaces: 'Workspaces', lastCommit: 'Last commit' }; return ( <TableComposable aria-label="Cell widths"> <Thead> <Tr> <Th width={15}>{columnNames.name}</Th> <Th width={15}>{columnNames.branches}</Th> <Th width={40} visibility={['hiddenOnMd', 'visibleOnLg']}> {columnNames.prs} </Th> <Th width={15}>{columnNames.workspaces}</Th> <Th width={15}>{columnNames.lastCommit}</Th> </Tr> </Thead> <Tbody> {repositories.map(repo => ( <Tr key={repo.name}> <Td dataLabel={columnNames.name}>{repo.name}</Td> <Td dataLabel={columnNames.branches}>{repo.branches}</Td> <Td dataLabel={columnNames.prs} visibility={['hiddenOnMd', 'visibleOnLg']}> {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/Card/examples/CardSelectable.tsx
import React from 'react'; import { Card, CardHeader, CardActions, CardTitle, CardBody, Dropdown, DropdownItem, DropdownSeparator, KebabToggle } from '@patternfly/react-core'; export const CardSelectable: React.FunctionComponent = () => { const [selected, setSelected] = React.useState<string>(''); const [isKebabOpen, setIsKebabOpen] = React.useState<boolean>(false); const onKeyDown = (event: React.KeyboardEvent) => { if (event.target !== event.currentTarget) { return; } if ([' ', 'Enter'].includes(event.key)) { event.preventDefault(); const newSelected = event.currentTarget.id === selected ? null : event.currentTarget.id; setSelected(newSelected); } }; const onClick = (event: React.MouseEvent) => { const newSelected = event.currentTarget.id === selected ? null : event.currentTarget.id; setSelected(newSelected); }; const onToggle = ( isOpen: boolean, event: MouseEvent | TouchEvent | KeyboardEvent | React.KeyboardEvent<any> | React.MouseEvent<HTMLButtonElement> ) => { event.stopPropagation(); setIsKebabOpen(isOpen); }; const onSelect = (event: React.SyntheticEvent<HTMLDivElement>) => { event.stopPropagation(); setIsKebabOpen(false); }; 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 ( <React.Fragment> <Card id="selectable-first-card" onKeyDown={onKeyDown} onClick={onClick} isSelectableRaised isSelected={selected === 'selectable-first-card'} > <CardHeader> <CardActions> <Dropdown onSelect={onSelect} toggle={<KebabToggle onToggle={onToggle} />} isOpen={isKebabOpen} isPlain dropdownItems={dropdownItems} position={'right'} /> </CardActions> </CardHeader> <CardTitle>First card</CardTitle> <CardBody>This is a selectable card. Click me to select me. Click again to deselect me.</CardBody> </Card> <br /> <Card id="selectable-second-card" onKeyDown={onKeyDown} onClick={onClick} isSelectableRaised isSelected={selected === 'selectable-second-card'} > <CardTitle>Second card</CardTitle> <CardBody>This is a selectable card. Click me to select me. Click again to deselect me.</CardBody> </Card> <br /> <Card id="selectable-third-card" isSelectableRaised isDisabledRaised> <CardTitle>Third card</CardTitle> <CardBody>This is a raised but disabled card.</CardBody> </Card> </React.Fragment> ); };
jelly/patternfly-react
packages/react-topology/src/components/nodes/shapes/shapeUtils.ts
import * as React from 'react'; import { Node, NodeShape, PointTuple, TopologyQuadrant } from '../../../types'; import { polygonHull } from 'd3-polygon'; import { hullPath, pointTuplesToPath } from '../../../utils'; import { Ellipse, Hexagon, Octagon, Rectangle, Trapezoid, Rhombus, Stadium } from './index'; const TWO_PI = Math.PI * 2; export const HEXAGON_CORNER_RADIUS = 6; export const OCTAGON_CORNER_RADIUS = 4; export const RHOMBUS_CORNER_RADIUS = 10; export const TRAPEZOID_CORNER_RADIUS = 10; export const LOWER_LEFT_RADIANS = (3 * Math.PI) / 4; export const LOWER_RIGHT_RADIANS = Math.PI / 4; export const UPPER_LEFT_RADIANS = (5 * Math.PI) / 4; export const UPPER_RIGHT_RADIANS = (7 * Math.PI) / 4; export const DEFAULT_DECORATOR_RADIUS = 12; export const DEFAULT_DECORATOR_PADDING = 4; export interface ShapeProps { className?: string; element: Node; width: number; height: number; filter?: string; sides?: number; cornerRadius?: number; dndDropRef?: (node: SVGElement | null) => void; } const quadrantRadians = (quadrant: TopologyQuadrant): number => { switch (quadrant) { case TopologyQuadrant.upperRight: return UPPER_RIGHT_RADIANS; case TopologyQuadrant.lowerRight: return LOWER_RIGHT_RADIANS; case TopologyQuadrant.upperLeft: return UPPER_LEFT_RADIANS; case TopologyQuadrant.lowerLeft: return LOWER_LEFT_RADIANS; } return UPPER_RIGHT_RADIANS; }; export const getPointsForSides = (numSides: number, size: number, padding = 0): PointTuple[] => { const points: PointTuple[] = []; const angle = TWO_PI / numSides; const radius = size / 2; for (let point = 0; point < numSides; point++) { points.push([ radius + (radius - padding) * Math.cos(angle * point), radius + (radius - padding) * Math.sin(angle * point) ]); } return points; }; export const getHullPath = (points: PointTuple[], padding: number): string => { const hullPoints: PointTuple[] = polygonHull(points); return hullPath(hullPoints, padding); }; export const getPathForSides = (numSides: number, size: number, padding = 0): string => { const points = getPointsForSides(numSides, size, padding); if (!padding) { return pointTuplesToPath(points); } return getHullPath(points, padding); }; export const getShapeComponent = (node: Node): React.FunctionComponent<ShapeProps> => { switch (node.getNodeShape()) { case NodeShape.circle: case NodeShape.ellipse: return Ellipse; case NodeShape.stadium: return Stadium; case NodeShape.rhombus: return Rhombus; case NodeShape.trapezoid: return Trapezoid; case NodeShape.rect: return Rectangle; case NodeShape.hexagon: return Hexagon; case NodeShape.octagon: return Octagon; default: return Ellipse; } }; export const getDefaultShapeDecoratorCenter = (quadrant: TopologyQuadrant, node: Node): { x: number; y: number } => { const { width, height } = node.getDimensions(); const shape = node.getNodeShape(); const nodeCenterX = width / 2; const nodeCenterY = height / 2; let deltaX = width / 2; let deltaY = height / 2; switch (shape) { case NodeShape.circle: case NodeShape.ellipse: return { x: nodeCenterX + Math.cos(quadrantRadians(quadrant)) * deltaX, y: nodeCenterY + Math.sin(quadrantRadians(quadrant)) * deltaY }; case NodeShape.rect: break; case NodeShape.rhombus: deltaX = width / 3; deltaY = height / 3; break; case NodeShape.trapezoid: if (quadrant === TopologyQuadrant.upperRight || quadrant === TopologyQuadrant.upperLeft) { deltaX = deltaX * 0.875 - TRAPEZOID_CORNER_RADIUS; } break; case NodeShape.hexagon: deltaX = deltaX * 0.75 - HEXAGON_CORNER_RADIUS; deltaY = deltaY * 0.75; break; case NodeShape.octagon: deltaX = deltaX - OCTAGON_CORNER_RADIUS; deltaY = deltaY - height / 5; break; default: break; } switch (quadrant) { case TopologyQuadrant.upperRight: return { x: nodeCenterX + deltaX, y: nodeCenterY - deltaY }; case TopologyQuadrant.lowerRight: return { x: nodeCenterX + deltaX, y: nodeCenterY + deltaY }; case TopologyQuadrant.upperLeft: return { x: nodeCenterX - deltaX, y: nodeCenterY - deltaY }; case TopologyQuadrant.lowerLeft: return { x: nodeCenterX - deltaX, y: nodeCenterY + deltaY }; default: return { x: nodeCenterX, y: nodeCenterY }; } };
jelly/patternfly-react
packages/react-console/src/components/SerialConsole/__tests__/XTerm.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { XTerm } from '../XTerm'; describe('XTerm', () => { beforeAll(() => { window.HTMLCanvasElement.prototype.getContext = () => ({ canvas: {}, createLinearGradient: jest.fn(), fillRect: jest.fn() } as any); global.window.matchMedia = () => ({ addListener: jest.fn(), removeListener: jest.fn(), matches: true, media: undefined, onchange: jest.fn(), addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn() }); }); test('Render empty XTerm component', () => { const { asFragment } = render(<XTerm cols={15} rows={60} onTitleChanged={jest.fn()} onData={jest.fn()} />); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-integration/cypress/integration/tablecompoundexpandable.spec.ts
<filename>packages/react-integration/cypress/integration/tablecompoundexpandable.spec.ts describe('Table Compound Expandable Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/table-compound-expandable-demo-nav-link'); }); it('Verify table string', () => { cy.get('caption').contains('Compound expandable table'); }); it('Test expandable/collapsible', () => { cy.get('button.pf-c-table__button') .first() .click(); cy.get('button.pf-c-table__button') .eq(1) .click(); cy.get('button.pf-c-table__button') .eq(2) .click(); cy.get('button.pf-c-table__button') .first() .click(); cy.get('button.pf-c-table__button') .eq(3) .click(); cy.get('button.pf-c-table__button') .eq(3) .click(); cy.get('button.pf-c-table__button') .eq(4) .click(); cy.get('button.pf-c-table__button') .eq(4) .click(); }); });
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/AccordionDemo/AccordionDemo.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { Accordion, AccordionItem, AccordionContent, AccordionToggle, AccordionExpandedContentBody, Stack, StackItem, Button } from '@patternfly/react-core'; interface AccordionDemoState { expanded: string; } export class AccordionDemo extends React.Component<null, AccordionDemoState> { static displayName = 'AccordionDemo'; state: AccordionDemoState = { expanded: '' }; componentDidMount() { window.scrollTo(0, 0); } onToggle = (id: string) => { const { expanded } = this.state; this.setState({ expanded: id !== expanded ? id : '' }); }; render() { const { expanded } = this.state; return ( <Stack hasGutter> <StackItem> <Accordion id="accordion-example"> <AccordionItem> <AccordionToggle onClick={() => this.onToggle('item-1')} isExpanded={expanded === 'item-1'} id="item-1"> Item One </AccordionToggle> <AccordionContent isHidden={expanded !== 'item-1'} id="item-1-content"> <p> Item One Content: 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={() => this.onToggle('item-2')} isExpanded={expanded === 'item-2'} id="item-2"> Item Two </AccordionToggle> <AccordionContent isHidden={expanded !== 'item-2'} id="item-2-content"> <p> Item Two Content: 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={() => this.onToggle('item-3')} isExpanded={expanded === 'item-3'} id="item-3"> Item Three </AccordionToggle> <AccordionContent isHidden={expanded !== 'item-3'} id="item-3-content"> <p> Item Three Content: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </AccordionContent> </AccordionItem> </Accordion> </StackItem> <StackItem> <Accordion id="accordion-example-no-box-shadow"> <AccordionItem> <AccordionToggle onClick={() => this.onToggle('item-1')} isExpanded={expanded === 'item-1'} id="item-1"> Item One </AccordionToggle> <AccordionContent isHidden={expanded !== 'item-1'} id="item-1-content"> <p> Item One Content: 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={() => this.onToggle('item-2')} isExpanded={expanded === 'item-2'} id="item-2"> Item Two </AccordionToggle> <AccordionContent isHidden={expanded !== 'item-2'} id="item-2-content"> <p> Item Two Content: 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={() => this.onToggle('item-3')} isExpanded={expanded === 'item-3'} id="item-3"> Item Three </AccordionToggle> <AccordionContent isHidden={expanded !== 'item-3'} id="item-3-content"> <p> Item Three Content: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </AccordionContent> </AccordionItem> </Accordion> </StackItem> <StackItem> <Accordion id="accordion-bordered" isBordered displaySize="large"> <AccordionItem> <AccordionToggle onClick={() => { this.onToggle('ex-toggle1'); }} isExpanded={expanded === 'ex-toggle1'} id="ex-toggle1" > Item One </AccordionToggle> <AccordionContent id="ex-expand1" isHidden={expanded !== 'ex-toggle1'}> <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={() => { this.onToggle('ex-toggle2'); }} isExpanded={expanded === 'ex-toggle2'} id="ex-toggle2" > Item Two </AccordionToggle> <AccordionContent id="ex-expand2" isHidden={expanded !== 'ex-toggle2'}> <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={() => { this.onToggle('ex-toggle3'); }} isExpanded={expanded === 'ex-toggle3'} id="ex-toggle3" > Item Three </AccordionToggle> <AccordionContent id="ex-expand3" isHidden={expanded !== 'ex-toggle3'}> <p>Morbi vitae urna quis nunc convallis hendrerit. Aliquam congue orci quis ultricies tempus.</p> </AccordionContent> </AccordionItem> <AccordionItem> <AccordionToggle onClick={() => { this.onToggle('ex-toggle4'); }} isExpanded={expanded === 'ex-toggle4'} id="ex-toggle4" > Item Four </AccordionToggle> <AccordionContent id="ex-expand4" isHidden={expanded !== 'ex-toggle4'} isCustomContent> <AccordionExpandedContentBody> 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. </AccordionExpandedContentBody> <AccordionExpandedContentBody> <Button variant="link" isLarge isInline> Call to action </Button> </AccordionExpandedContentBody> </AccordionContent> </AccordionItem> <AccordionItem> <AccordionToggle onClick={() => { this.onToggle('ex-toggle5'); }} isExpanded={expanded === 'ex-toggle5'} id="ex-toggle5" > Item Five </AccordionToggle> <AccordionContent id="ex-expand5" isHidden={expanded !== 'ex-toggle5'}> <p>Vivamus finibus dictum ex id ultrices. Mauris dictum neque a iaculis blandit.</p> </AccordionContent> </AccordionItem> </Accordion> </StackItem> </Stack> ); } }
jelly/patternfly-react
packages/react-core/src/components/LoginPage/__tests__/LoginMainBody.test.tsx
<gh_stars>0 import * as React from 'react'; import { render } from '@testing-library/react'; import { LoginMainBody } from '../LoginMainBody'; describe('LoginMainBody', () => { test('renders with PatternFly Core styles', () => { const { asFragment } = render(<LoginMainBody />); expect(asFragment()).toMatchSnapshot(); }); test('className is added to the root element', () => { const { asFragment } = render(<LoginMainBody className="extra-class" />); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/themes/donut-utilization-theme.ts
/* eslint-disable camelcase */ import chart_donut_threshold_first_Color from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_first_Color'; import chart_donut_threshold_second_Color from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_second_Color'; import chart_donut_threshold_third_Color from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_third_Color'; import chart_donut_utilization_dynamic_pie_Height from '@patternfly/react-tokens/dist/esm/chart_donut_utilization_dynamic_pie_Height'; import chart_donut_utilization_dynamic_pie_angle_Padding from '@patternfly/react-tokens/dist/esm/chart_donut_utilization_dynamic_pie_angle_Padding'; import chart_donut_utilization_dynamic_pie_Padding from '@patternfly/react-tokens/dist/esm/chart_donut_utilization_dynamic_pie_Padding'; import chart_donut_utilization_dynamic_pie_Width from '@patternfly/react-tokens/dist/esm/chart_donut_utilization_dynamic_pie_Width'; import chart_donut_utilization_static_pie_Padding from '@patternfly/react-tokens/dist/esm/chart_donut_utilization_static_pie_Padding'; // Donut utilization dynamic theme export const DonutUtilizationDynamicTheme = { pie: { height: chart_donut_utilization_dynamic_pie_Height.value, padding: chart_donut_utilization_dynamic_pie_Padding.value, padAngle: chart_donut_utilization_dynamic_pie_angle_Padding.value, width: chart_donut_utilization_dynamic_pie_Width.value } }; // Donut utilization static theme export const DonutUtilizationStaticTheme = { legend: { colorScale: [ chart_donut_threshold_first_Color.value, chart_donut_threshold_second_Color.value, chart_donut_threshold_third_Color.value ] }, pie: { colorScale: [chart_donut_threshold_first_Color.value], padding: chart_donut_utilization_static_pie_Padding.value } };
jelly/patternfly-react
packages/react-core/src/components/Brand/examples/BrandResponsive.tsx
import React from 'react'; import { Brand } from '@patternfly/react-core'; import logoXl from './pf-c-brand--logo-on-xl.svg'; import logoLg from './pf-c-brand--logo-on-lg.svg'; import logoMd from './pf-c-brand--logo-on-md.svg'; import logoSm from './pf-c-brand--logo-on-sm.svg'; import logo from './pf-c-brand--logo.svg'; import logoBase from './pf-c-brand--logo-base.jpg'; export const BrandBasic: React.FunctionComponent = () => ( <Brand src={logoBase} alt="Fallback patternfly default logo" widths={{ default: '40px', sm: '60px', md: '220px' }}> <source media="(min-width: 1200px)" srcSet={logoXl} /> <source media="(min-width: 992px)" srcSet={logoLg} /> <source media="(min-width: 768px)" srcSet={logoMd} /> <source media="(min-width: 576px)" srcSet={logoSm} /> <source srcSet={logo} /> </Brand> );
jelly/patternfly-react
packages/react-core/src/layouts/Bullseye/__tests__/Bullseye.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import { Bullseye } from '../Bullseye'; describe('Bullseye', () => { test('renders with PatternFly Core styles', () => { const { asFragment } = render(<Bullseye />); expect(asFragment()).toMatchSnapshot(); }); test('className is added to the root element', () => { render(<Bullseye className="extra-class" data-testid="test-id" />); expect(screen.getByTestId('test-id')).toHaveClass('extra-class'); }); test('allows passing in a string as the component', () => { const component = 'button'; render(<Bullseye component={component} />); expect(screen.getByRole('button')).toBeInTheDocument(); }); test('allows passing in a React Component as the component', () => { const Component: React.FunctionComponent = () => <div>Some text</div>; render(<Bullseye component={(Component as unknown) as keyof JSX.IntrinsicElements} />); expect(screen.getByText('Some text')).toBeInTheDocument(); }); });
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/index.ts
export * from './MultipleFileUpload'; export * from './MultipleFileUploadMain'; export * from './MultipleFileUploadStatus'; export * from './MultipleFileUploadStatusItem';
jelly/patternfly-react
packages/react-code-editor/src/components/CodeEditor/__test__/CodeEditor.test.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { render } from '@testing-library/react'; import { CodeEditor, Language } from '../CodeEditor'; describe('CodeEditor', () => { beforeAll(() => { window.HTMLCanvasElement.prototype.getContext = () => ({} as any); }); test('matches snapshot without props', () => { const { asFragment } = render(<CodeEditor />); expect(asFragment()).toMatchSnapshot(); }); test('matches snapshot with all props', () => { const { asFragment } = render( <CodeEditor isReadOnly isDarkTheme isLineNumbersVisible={false} isUploadEnabled isLanguageLabelVisible isDownloadEnabled isCopyEnabled height="400px" code={'test'} language={Language.javascript} /> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-topology/src/layouts/GridGroup.ts
<filename>packages/react-topology/src/layouts/GridGroup.ts import { LayoutGroup } from './LayoutGroup'; export class GridGroup extends LayoutGroup {}
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/utils/withTopologySetup.tsx
import * as React from 'react'; import { VisualizationProvider, VisualizationSurface } from '@patternfly/react-topology'; const withTopologySetup = (WrappedComponent: React.ComponentType) => () => ( <VisualizationProvider> <WrappedComponent /> <VisualizationSurface /> </VisualizationProvider> ); export default withTopologySetup;
jelly/patternfly-react
packages/react-topology/src/geom/__tests__/Dimensions.spec.ts
import Dimensions from '../Dimensions'; describe('Dimensions', () => { it('should provide an empty instance', () => { expect(Dimensions.EMPTY).toEqual({ width: 0, height: 0 }); }); it('should re-use single use instance', () => { expect(Dimensions.singleUse()).toBe(Dimensions.singleUse()); expect(Dimensions.singleUse()).toEqual({ width: 0, height: 0 }); expect(Dimensions.singleUse(1)).toEqual({ width: 1, height: 0 }); expect(Dimensions.singleUse(1, 2)).toEqual({ width: 1, height: 2 }); }); it('should create a new Dimensions from existing Dimensions', () => { const d1 = new Dimensions(5, 10); const d2 = Dimensions.fromDimensions(d1); expect(d1).not.toBe(d2); expect(d1).toEqual(d2); }); it('should create a Dimensions', () => { expect(new Dimensions()).toEqual({ width: 0, height: 0 }); expect(new Dimensions(1)).toEqual({ width: 1, height: 0 }); expect(new Dimensions(1, 2)).toEqual({ width: 1, height: 2 }); }); it('should be empty if no height or width', () => { expect(new Dimensions().isEmpty()).toBe(true); expect(new Dimensions(1, 0).isEmpty()).toBe(true); expect(new Dimensions(0, 1).isEmpty()).toBe(true); expect(new Dimensions(1, 1).isEmpty()).toBe(false); }); it('should set size', () => { const d = new Dimensions(8, 9); expect(d.setSize(2, 3)).toBe(d); expect(d).toEqual({ width: 2, height: 3 }); }); it('should scale Dimensions', () => { const d = new Dimensions(4, 6); expect(d.scale(2)).toBe(d); expect(d).toEqual({ width: 8, height: 12 }); d.scale(0.5, 2); expect(d).toEqual({ width: 4, height: 24 }); }); it('should resize the Dimensions', () => { const d = new Dimensions(8, 9); expect(d.resize(2, 3)).toBe(d); expect(d).toEqual({ width: 10, height: 12 }); }); it('should expand the Dimensions in size', () => { const d = new Dimensions(8, 9); expect(d.expand(4, 5)).toBe(d); expect(d).toEqual({ width: 16, height: 19 }); }); it('should clone Dimensions', () => { const d1 = new Dimensions(5, 10); const d2 = d1.clone(); expect(d1).not.toBe(d2); expect(d1).toEqual(d2); }); it('should check Dimensions equality', () => { const d1 = new Dimensions(5, 10); const d2 = new Dimensions(5, 10); const d3 = new Dimensions(1, 2); expect(d1.equals(d2)).toBe(true); expect(d1.equals(d3)).toBe(false); }); });
jelly/patternfly-react
packages/react-core/src/components/Checkbox/examples/CheckboxWithBody.tsx
<reponame>jelly/patternfly-react<gh_stars>0 import React from 'react'; import { Checkbox } from '@patternfly/react-core'; export const CheckboxWithBody: React.FunctionComponent = () => ( <Checkbox id="body-check-1" label="Checkbox with body" body="This is where custom content goes." /> );
jelly/patternfly-react
packages/react-core/src/components/Dropdown/DropdownMenu.tsx
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import styles from '@patternfly/react-styles/css/components/Dropdown/dropdown'; import { css } from '@patternfly/react-styles'; import { keyHandler, formatBreakpointMods } from '../../helpers/util'; import { DropdownPosition, DropdownArrowContext, DropdownContext } from './dropdownConstants'; export interface DropdownMenuProps { /** Anything which can be rendered as dropdown items */ children?: React.ReactNode; /** Classess applied to root element of dropdown menu */ className?: string; /** Flag to indicate if menu is opened */ isOpen?: boolean; /** @deprecated - no longer used */ openedOnEnter?: boolean; /** Flag to indicate if the first dropdown item should gain initial focus, set false when adding * a specific auto-focus item (like a current selection) otherwise leave as true */ autoFocus?: boolean; /** Indicates which component will be used as dropdown menu */ component?: React.ReactNode; /** Indicates where menu will be alligned horizontally */ position?: DropdownPosition | 'right' | 'left'; /** Indicates how the menu will align at screen size breakpoints */ alignments?: { sm?: 'right' | 'left'; md?: 'right' | 'left'; lg?: 'right' | 'left'; xl?: 'right' | 'left'; '2xl'?: 'right' | 'left'; }; /** Flag to indicate if menu is grouped */ isGrouped?: boolean; // Function to call on component mount setMenuComponentRef?: any; } export interface DropdownMenuItem extends React.HTMLAttributes<any> { isDisabled: boolean; disabled: boolean; isHovered: boolean; ref: HTMLElement; } export class DropdownMenu extends React.Component<DropdownMenuProps> { static displayName = 'DropdownMenu'; context!: React.ContextType<typeof DropdownContext>; refsCollection = [] as HTMLElement[][]; static defaultProps: DropdownMenuProps = { className: '', isOpen: true, openedOnEnter: false, autoFocus: true, position: DropdownPosition.left, component: 'ul', isGrouped: false, setMenuComponentRef: null }; componentDidMount() { document.addEventListener('keydown', this.onKeyDown); const { autoFocus } = this.props; if (autoFocus) { // Focus first non-disabled element const focusTargetCollection = this.refsCollection.find(ref => ref && ref[0] && !ref[0].hasAttribute('disabled')); const focusTarget = focusTargetCollection && focusTargetCollection[0]; if (focusTarget && focusTarget.focus) { setTimeout(() => focusTarget.focus()); } } } componentWillUnmount = () => { document.removeEventListener('keydown', this.onKeyDown); }; static validToggleClasses = [styles.dropdownToggle, styles.dropdownToggleButton] as string[]; static focusFirstRef = (refCollection: HTMLElement[]) => { if (refCollection && refCollection[0] && refCollection[0].focus) { setTimeout(() => refCollection[0].focus()); } }; onKeyDown = (event: any) => { if ( !this.props.isOpen || !Array.from(document.activeElement.classList).find(className => DropdownMenu.validToggleClasses.concat(this.context.toggleClass).includes(className) ) ) { return; } const refs = this.refsCollection; if (event.key === 'ArrowDown') { const firstFocusTargetCollection = refs.find(ref => ref && ref[0] && !ref[0].hasAttribute('disabled')); DropdownMenu.focusFirstRef(firstFocusTargetCollection); event.stopPropagation(); } else if (event.key === 'ArrowUp') { const collectionLength = refs.length; const lastFocusTargetCollection = refs.slice(collectionLength - 1, collectionLength); const lastFocusTarget = lastFocusTargetCollection && lastFocusTargetCollection[0]; DropdownMenu.focusFirstRef(lastFocusTarget); event.stopPropagation(); } }; shouldComponentUpdate() { // reset refsCollection before updating to account for child removal between mounts this.refsCollection = [] as HTMLElement[][]; return true; } childKeyHandler = (index: number, innerIndex: number, position: string, custom = false) => { keyHandler( index, innerIndex, position, this.refsCollection, this.props.isGrouped ? this.refsCollection : React.Children.toArray(this.props.children), custom ); }; sendRef = (index: number, nodes: any[], isDisabled: boolean, isSeparator: boolean) => { this.refsCollection[index] = []; nodes.map((node, innerIndex) => { if (!node) { this.refsCollection[index][innerIndex] = null; } else if (!node.getAttribute) { // eslint-disable-next-line react/no-find-dom-node this.refsCollection[index][innerIndex] = ReactDOM.findDOMNode(node) as HTMLElement; } else if (isSeparator) { this.refsCollection[index][innerIndex] = null; } else { this.refsCollection[index][innerIndex] = node; } }); }; extendChildren() { const { children, isGrouped } = this.props; if (isGrouped) { let index = 0; return React.Children.map(children, groupedChildren => { const group = groupedChildren as React.ReactElement; const props: { children?: React.ReactNode } = {}; if (group.props && group.props.children) { if (Array.isArray(group.props.children)) { props.children = React.Children.map(group.props.children, option => React.cloneElement(option as React.ReactElement, { index: index++ }) ); } else { props.children = React.cloneElement(group.props.children as React.ReactElement, { index: index++ }); } } return React.cloneElement(group, props); }); } return React.Children.map(children, (child, index) => React.cloneElement(child as React.ReactElement, { index }) ); } render() { const { className, isOpen, position, children, component, isGrouped, setMenuComponentRef, // eslint-disable-next-line @typescript-eslint/no-unused-vars openedOnEnter, alignments, ...props } = this.props; return ( <DropdownArrowContext.Provider value={{ keyHandler: this.childKeyHandler, sendRef: this.sendRef }} > {component === 'div' ? ( <DropdownContext.Consumer> {({ onSelect, menuClass }) => ( <div className={css( menuClass, position === DropdownPosition.right && styles.modifiers.alignRight, formatBreakpointMods(alignments, styles, 'align-'), className )} hidden={!isOpen} onClick={event => onSelect && onSelect(event)} ref={setMenuComponentRef} > {children} </div> )} </DropdownContext.Consumer> ) : ( (isGrouped && ( <DropdownContext.Consumer> {({ menuClass, menuComponent }) => { const MenuComponent = (menuComponent || 'div') as any; return ( <MenuComponent {...props} className={css( menuClass, position === DropdownPosition.right && styles.modifiers.alignRight, formatBreakpointMods(alignments, styles, 'align-'), className )} hidden={!isOpen} role="menu" ref={setMenuComponentRef} > {this.extendChildren()} </MenuComponent> ); }} </DropdownContext.Consumer> )) || ( <DropdownContext.Consumer> {({ menuClass, menuComponent }) => { const MenuComponent = (menuComponent || component) as any; return ( <MenuComponent {...props} className={css( menuClass, position === DropdownPosition.right && styles.modifiers.alignRight, formatBreakpointMods(alignments, styles, 'align-'), className )} hidden={!isOpen} role="menu" ref={setMenuComponentRef} > {this.extendChildren()} </MenuComponent> ); }} </DropdownContext.Consumer> ) )} </DropdownArrowContext.Provider> ); } } DropdownMenu.contextType = DropdownContext;
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/utils/mergePaddingObject.ts
<filename>packages/react-core/src/helpers/Popper/thirdparty/popper-core/utils/mergePaddingObject.ts // @ts-nocheck import { SideObject } from '../types'; import getFreshSideObject from './getFreshSideObject'; /** * @param paddingObject */ export default function mergePaddingObject(paddingObject: Partial<SideObject>): SideObject { return { ...getFreshSideObject(), ...paddingObject }; }
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/JumpLinksDemo/JumpLinksDemo.tsx
import { Title, JumpLinks, JumpLinksItem, PageSection, PageGroup } from '@patternfly/react-core'; import React from 'react'; export const JumpLinksDemo = () => { const headings = [1, 2, 3, 4, 5]; return ( <React.Fragment> <PageSection sticky="top"> <JumpLinks isCentered label="Jump to section" scrollableSelector="#scrollable-element"> {headings.map(i => ( <JumpLinksItem key={i} id={`#heading-${i}`} href={`#heading-${i}`}> {`Heading ${i}`} </JumpLinksItem> ))} </JumpLinks> </PageSection> <PageGroup hasOverflowScroll id="scrollable-element"> <PageSection> {headings.map(i => ( <div key={i} style={{ maxWidth: '800px', marginBottom: '32px' }}> <Title headingLevel="h2" size={'2xl'} id={`heading-${i}`} tabIndex={-1}> {`Heading ${i}`} </Title> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <br /> <p> At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat. </p> <br /> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </div> ))} </PageSection> </PageGroup> </React.Fragment> ); };
jelly/patternfly-react
packages/react-integration/cypress/integration/selectfiltering.spec.ts
<filename>packages/react-integration/cypress/integration/selectfiltering.spec.ts function checkFiltering() { cy.get('.pf-c-form-control').type('run'); cy.get('#Running').should('exist'); cy.get('#Hewlett-Packard').should('not.exist'); cy.get('.pf-c-form-control').type('{backspace}{backspace}{backspace}degr'); cy.get('#Running').should('not.exist'); cy.get('#Degraded').should('exist'); cy.get('#Degraded').click(); cy.get('#filter-select').click(); } describe('Select with Filtering Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/select-demo-filtering-nav-link'); }); it('Verify Checkbox Select with filtering chips', () => { cy.get('#filter-select').click(); cy.get('#Running').click(); cy.get('.pf-c-select__toggle') .contains('1') .should('exist'); }); it('Verify Checkbox Select with filtering works', () => { checkFiltering(); cy.get('.pf-c-select__toggle') .contains('2') .should('exist'); }); it('Verify Single Select with filtering works', () => { cy.get('#single-toggle').click(); cy.get('#filter-select').click(); checkFiltering(); }); });
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/MastheadDemo/MastheadDemo.tsx
import React from 'react'; import { Masthead, MastheadToggle, MastheadMain, MastheadBrand, MastheadContent, Button, Toolbar, ToolbarContent, ToolbarGroup, ToolbarItem, ContextSelector, ContextSelectorItem, Dropdown, DropdownToggle, KebabToggle, DropdownSeparator, DropdownItem } from '@patternfly/react-core'; import imgBrand from '@patternfly/react-core/src/demos/examples/pfColorLogo.svg'; import BarsIcon from '@patternfly/react-icons/dist/js/icons/bars-icon'; import CaretDownIcon from '@patternfly/react-icons/dist/js/icons/caret-down-icon'; export class MastheadDemo extends React.Component { displayName = 'MastheadDemo'; items = [ 'My Project', 'OpenShift Cluster', 'Production Ansible', 'AWS', 'Azure', 'My Project 2', 'OpenShift Cluster ', 'Production Ansible 2 ', 'AWS 2', 'Azure 2' ]; state = { isOpen: false, isDropdownOpen: false, isKebabOpen: false, selected: this.items[0], searchValue: '', filteredItems: this.items }; onToggle = (event: any, isOpen: boolean) => { this.setState({ isOpen }); }; onDropdownToggle = (isDropdownOpen: boolean) => { this.setState({ isDropdownOpen }); }; onKebabToggle = (isKebabOpen: boolean) => { this.setState({ isKebabOpen }); }; onSelect = (event: any, value: string) => { this.setState({ selected: value, isOpen: !this.state.isOpen }); }; onDropdownSelect = () => { this.setState({ isDropdownOpen: !this.state.isDropdownOpen }); }; onKebabSelect = () => { this.setState({ isKebabOpen: !this.state.isKebabOpen }); }; onSearchInputChange = (value: string) => { this.setState({ searchValue: value }); }; onSearchButtonClick = () => { const filtered = this.state.searchValue === '' ? this.items : this.items.filter(str => str.toLowerCase().indexOf(this.state.searchValue.toLowerCase()) !== -1); this.setState({ filteredItems: filtered || [] }); }; render() { const { isOpen, isDropdownOpen, isKebabOpen, selected, searchValue, filteredItems } = this.state; const dropdownItems = [ <DropdownItem key="link">Link</DropdownItem>, <DropdownItem key="action" component="button"> Action </DropdownItem>, <DropdownItem key="disabled link" isDisabled href="www.google.com"> Disabled Link </DropdownItem>, <DropdownItem key="disabled action" isAriaDisabled component="button" tooltip="Tooltip for disabled item" tooltipProps={{ position: 'top' }} > Disabled Action </DropdownItem>, <DropdownSeparator key="separator" />, <DropdownItem key="separated link">Separated Link</DropdownItem>, <DropdownItem key="separated action" component="button"> Separated Action </DropdownItem> ]; return ( <Masthead id="basic"> <MastheadToggle> <Button variant="plain" onClick={() => {}} aria-label="Global navigation"> <BarsIcon /> </Button> </MastheadToggle> <MastheadMain> <MastheadBrand> <img src={imgBrand} alt="Patternfly logo" /> </MastheadBrand> </MastheadMain> <MastheadContent> <Toolbar id="toolbar"> <ToolbarContent> <ToolbarItem> <ContextSelector toggleText={selected} onSearchInputChange={this.onSearchInputChange} isOpen={isOpen} searchInputValue={searchValue} onToggle={this.onToggle} onSelect={this.onSelect} onSearchButtonClick={this.onSearchButtonClick} screenReaderLabel="Selected Project:" isFullHeight > {filteredItems.map((item, index) => ( <ContextSelectorItem key={index}>{item}</ContextSelectorItem> ))} </ContextSelector> </ToolbarItem> <ToolbarGroup alignment={{ default: 'alignRight' }}> <ToolbarItem visibility={{ default: 'hidden', lg: 'visible' }}> <Dropdown onSelect={this.onDropdownSelect} toggle={ <DropdownToggle id="toggle-id" onToggle={this.onDropdownToggle} toggleIndicator={CaretDownIcon}> Dropdown </DropdownToggle> } isOpen={isDropdownOpen} dropdownItems={dropdownItems} isFullHeight /> </ToolbarItem> <ToolbarItem> <Dropdown onSelect={this.onKebabSelect} toggle={<KebabToggle onToggle={this.onKebabToggle} id="toggle-id-kebab" />} isOpen={isKebabOpen} isPlain dropdownItems={dropdownItems} /> </ToolbarItem> </ToolbarGroup> </ToolbarContent> </Toolbar> </MastheadContent> </Masthead> ); } } export default MastheadDemo;
jelly/patternfly-react
packages/react-core/src/components/Toolbar/examples/ToolbarCustomChipGroupContent.tsx
import React from 'react'; import { Toolbar, ToolbarItem, ToolbarContent, ToolbarFilter, ToolbarToggleGroup, ToolbarGroup, Button, Select, SelectOption, SelectVariant } from '@patternfly/react-core'; import FilterIcon from '@patternfly/react-icons/dist/esm/icons/filter-icon'; import EditIcon from '@patternfly/react-icons/dist/esm/icons/edit-icon'; import CloneIcon from '@patternfly/react-icons/dist/esm/icons/clone-icon'; import SyncIcon from '@patternfly/react-icons/dist/esm/icons/sync-icon'; export const ToolbarCustomChipGroupContent: React.FunctionComponent = () => { const [statusIsExpanded, setStatusIsExpanded] = React.useState<boolean>(false); const [riskIsExpanded, setRiskIsExpanded] = React.useState<boolean>(false); const [filters, setFilters] = React.useState({ risk: ['Low'], status: ['New', 'Pending'] }); const onDelete = (type: string, id: string) => { if (type === 'Risk') { setFilters({ risk: filters.risk.filter((fil: string) => fil !== id), status: filters.status }); } else if (type === 'Status') { setFilters({ risk: filters.risk, status: filters.status.filter((fil: string) => fil !== id) }); } else { setFilters({ risk: [], status: [] }); } }; const onDeleteGroup = (type: string) => { if (type === 'Risk') { setFilters({ risk: [], status: filters.status }); } else if (type === 'Status') { setFilters({ risk: filters.risk, status: [] }); } }; const onSelect = (type: 'Risk' | 'Status', event: React.MouseEvent | React.ChangeEvent, selection: string) => { const checked = (event.target as any).checked; if (type === 'Risk') { setFilters({ risk: checked ? [...filters.risk, selection] : filters.risk.filter((fil: string) => fil !== selection), status: filters.status }); } else if (type === 'Status') { setFilters({ risk: filters.risk, status: checked ? [...filters.status, selection] : filters.status.filter((fil: string) => fil !== selection) }); } }; const statusMenuItems = [ <SelectOption key="statusNew" value="New" />, <SelectOption key="statusPending" value="Pending" />, <SelectOption key="statusRunning" value="Running" />, <SelectOption key="statusCancelled" value="Cancelled" /> ]; const riskMenuItems = [ <SelectOption key="riskLow" value="Low" />, <SelectOption key="riskMedium" value="Medium" />, <SelectOption key="riskHigh" value="High" /> ]; const toggleGroupItems = ( <React.Fragment> <ToolbarGroup variant="filter-group"> <ToolbarFilter chips={filters.status} deleteChip={(category, chip) => onDelete(category as string, chip as string)} deleteChipGroup={category => onDeleteGroup(category as string)} categoryName="Status" > <Select variant={SelectVariant.checkbox} aria-label="Status" onToggle={(isExpanded: boolean) => setStatusIsExpanded(isExpanded)} onSelect={(event, selection) => onSelect('Status', event, selection as string)} selections={filters.status} isOpen={statusIsExpanded} placeholderText="Status" > {statusMenuItems} </Select> </ToolbarFilter> <ToolbarFilter chips={filters.risk} deleteChip={(category, chip) => onDelete(category as string, chip as string)} deleteChipGroup={category => onDeleteGroup(category as string)} categoryName="Risk" > <Select variant={SelectVariant.checkbox} aria-label="Risk" onToggle={(isExpanded: boolean) => setRiskIsExpanded(isExpanded)} onSelect={(event, selection) => onSelect('Risk', event, selection as string)} selections={filters.risk} isOpen={riskIsExpanded} placeholderText="Risk" > {riskMenuItems} </Select> </ToolbarFilter> </ToolbarGroup> </React.Fragment> ); const toolbarItems = ( <React.Fragment> <ToolbarToggleGroup toggleIcon={<FilterIcon />} breakpoint="xl"> {toggleGroupItems} </ToolbarToggleGroup> <ToolbarGroup variant="icon-button-group"> <ToolbarItem> <Button variant="plain" aria-label="edit"> <EditIcon /> </Button> </ToolbarItem> <ToolbarItem> <Button variant="plain" aria-label="clone"> <CloneIcon /> </Button> </ToolbarItem> <ToolbarItem> <Button variant="plain" aria-label="sync"> <SyncIcon /> </Button> </ToolbarItem> </ToolbarGroup> </React.Fragment> ); const customChipGroupContent = ( <React.Fragment> <ToolbarItem> <Button variant="link" onClick={() => {}} isInline> Save filters </Button> </ToolbarItem> <ToolbarItem> <Button variant="link" onClick={() => onDelete('', '')} isInline> Clear all filters </Button> </ToolbarItem> </React.Fragment> ); return ( <Toolbar id="toolbar-with-filter" className="pf-m-toggle-group-container" collapseListedFiltersBreakpoint="xl" customChipGroupContent={customChipGroupContent} > <ToolbarContent>{toolbarItems}</ToolbarContent> </Toolbar> ); };
jelly/patternfly-react
packages/react-topology/src/components/nodes/shapes/Trapezoid.tsx
import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; import * as React from 'react'; import { PointTuple } from '../../../types'; import { getHullPath, TRAPEZOID_CORNER_RADIUS, ShapeProps } from './shapeUtils'; import { usePolygonAnchor } from '../../../behavior'; const TOP_INSET_AMOUNT = 1 / 8; const getTrapezoidPoints = (width: number, height: number, padding: number, outline: boolean = false): PointTuple[] => { const yPadding = outline ? 0 : padding; const topXPadding = outline ? padding / 4 : padding; const bottomXPadding = outline ? -padding / 4 : padding; return [ [width * TOP_INSET_AMOUNT + topXPadding, yPadding], [width - width * TOP_INSET_AMOUNT - topXPadding, yPadding], [width - bottomXPadding, height - yPadding], [bottomXPadding, height - yPadding] ]; }; type TrapezoidProps = ShapeProps & { cornerRadius?: number; }; const Trapezoid: React.FunctionComponent<TrapezoidProps> = ({ className = css(styles.topologyNodeBackground), width, height, filter, cornerRadius = TRAPEZOID_CORNER_RADIUS, dndDropRef }) => { const [polygonPoints, points] = React.useMemo(() => { const polygonPoints: PointTuple[] = getTrapezoidPoints(width, height, cornerRadius, true); const path = cornerRadius ? getHullPath(getTrapezoidPoints(width, height, cornerRadius), cornerRadius) : polygonPoints.map(p => `${p[0]},${p[1]}`).join(' '); return [polygonPoints, path]; }, [height, cornerRadius, width]); usePolygonAnchor(polygonPoints); return cornerRadius ? ( <path className={className} ref={dndDropRef} d={points} filter={filter} /> ) : ( <polygon className={className} ref={dndDropRef} points={points} filter={filter} /> ); }; export default Trapezoid;
jelly/patternfly-react
packages/react-core/src/components/DescriptionList/examples/DescriptionListWithTermHelpText.tsx
<filename>packages/react-core/src/components/DescriptionList/examples/DescriptionListWithTermHelpText.tsx import React from 'react'; import { Button, DescriptionList, DescriptionListGroup, DescriptionListDescription, DescriptionListTermHelpText, DescriptionListTermHelpTextButton, Popover } from '@patternfly/react-core'; import PlusCircleIcon from '@patternfly/react-icons/dist/esm/icons/plus-circle-icon'; export const DescriptionListWithTermHelpText: React.FunctionComponent = () => ( <DescriptionList> <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> );
jelly/patternfly-react
packages/react-core/src/components/TreeView/TreeViewSearch.tsx
<reponame>jelly/patternfly-react<filename>packages/react-core/src/components/TreeView/TreeViewSearch.tsx import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/TreeView/tree-view'; import formStyles from '@patternfly/react-styles/css/components/FormControl/form-control'; export interface TreeViewSearchProps extends React.HTMLProps<HTMLInputElement> { /** Callback for search input */ onSearch?: (event: React.ChangeEvent<HTMLInputElement>) => void; /** Id for the search input */ id?: string; /** Name for the search input */ name?: string; /** Accessible label for the search input */ 'aria-label'?: string; /** Classes applied to the wrapper for the search input */ className?: string; } export const TreeViewSearch: React.FunctionComponent<TreeViewSearchProps> = ({ className, onSearch, id, name, 'aria-label': ariaLabel, ...props }: TreeViewSearchProps) => ( <div className={css(styles.treeViewSearch, className)}> <input className={css(formStyles.formControl, formStyles.modifiers.search)} onChange={onSearch} id={id} name={name} aria-label={ariaLabel} type="search" {...props} /> </div> ); TreeViewSearch.displayName = 'TreeViewSearch';
jelly/patternfly-react
packages/react-table/src/components/TableComposable/examples/ComposableTableSortableCustom.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { TableComposable, Thead, Tr, Th, Tbody, Td, ThProps } from '@patternfly/react-table'; import { Toolbar, ToolbarContent, ToolbarItem, OptionsMenu, OptionsMenuItemGroup, OptionsMenuItem, OptionsMenuSeparator, OptionsMenuToggle } from '@patternfly/react-core'; import SortAmountDownIcon from '@patternfly/react-icons/dist/esm/icons/sort-amount-down-icon'; interface Repository { name: string; branches: string; prs: string; workspaces: string; lastCommit: string; } export const ComposableTableSortableCustom: React.FunctionComponent = () => { // In real usage, this data would come from some external source like an API via props. const repositories: Repository[] = [ { name: 'one', branches: 'two', prs: 'a', workspaces: 'four', lastCommit: 'five' }, { name: 'a', branches: 'two', prs: 'k', workspaces: 'four', lastCommit: 'five' }, { name: 'p', branches: 'two', prs: 'b', workspaces: 'four', lastCommit: 'five' } ]; const columnNames = { name: 'Repositories', branches: 'Branches', prs: 'Pull requests', workspaces: 'Workspaces', lastCommit: 'Last commit' }; // Index of the currently sorted column // Note: if you intend to make columns reorderable, you may instead want to use a non-numeric key // as the identifier of the sorted column. See the "Compound expandable" example. const [activeSortIndex, setActiveSortIndex] = React.useState<number | null>(null); // Sort direction of the currently sorted column const [activeSortDirection, setActiveSortDirection] = React.useState<'asc' | 'desc' | null>(null); // Sort dropdown expansion const [isSortDropdownOpen, setIsSortDropdownOpen] = React.useState(false); // Since OnSort specifies sorted columns by index, we need sortable values for our object by column index. // This example is trivial since our data objects just contain strings, but if the data was more complex // this would be a place to return simplified string or number versions of each column to sort by. const getSortableRowValues = (repo: Repository): (string | number)[] => { const { name, branches, prs, workspaces, lastCommit } = repo; return [name, branches, prs, workspaces, lastCommit]; }; // Note that we perform the sort as part of the component's render logic and not in onSort. // We shouldn't store the list of data in state because we don't want to have to sync that with props. let sortedRepositories = repositories; if (activeSortIndex !== null) { sortedRepositories = repositories.sort((a, b) => { const aValue = getSortableRowValues(a)[activeSortIndex]; const bValue = getSortableRowValues(b)[activeSortIndex]; if (typeof aValue === 'number') { // Numeric sort if (activeSortDirection === 'asc') { return (aValue as number) - (bValue as number); } return (bValue as number) - (aValue as number); } else { // String sort if (activeSortDirection === 'asc') { return (aValue as string).localeCompare(bValue as string); } return (bValue as string).localeCompare(aValue as string); } }); } const getSortParams = (columnIndex: number): ThProps['sort'] => ({ sortBy: { index: activeSortIndex, direction: activeSortDirection }, onSort: (_event, index, direction) => { setActiveSortIndex(index); setActiveSortDirection(direction); }, columnIndex }); return ( <React.Fragment> <Toolbar id="toolbar"> <ToolbarContent> <ToolbarItem> <OptionsMenu id="options-menu-multiple-options-example" menuItems={[ <OptionsMenuItemGroup key="first group" aria-label="Sort column"> {Object.values(columnNames).map((columnName, columnIndex) => ( <OptionsMenuItem key={columnName} isSelected={activeSortIndex === columnIndex} onSelect={() => { setActiveSortIndex(columnIndex); setActiveSortDirection(activeSortDirection !== null ? activeSortDirection : 'asc'); }} > {columnName} </OptionsMenuItem> ))} </OptionsMenuItemGroup>, <OptionsMenuSeparator key="separator" />, <OptionsMenuItemGroup key="second group" aria-label="Sort direction"> <OptionsMenuItem onSelect={() => setActiveSortDirection('asc')} isSelected={activeSortDirection === 'asc'} id="ascending" key="ascending" > Ascending </OptionsMenuItem> <OptionsMenuItem onSelect={() => setActiveSortDirection('desc')} isSelected={activeSortDirection === 'desc'} id="descending" key="descending" > Descending </OptionsMenuItem> </OptionsMenuItemGroup> ]} isOpen={isSortDropdownOpen} toggle={ <OptionsMenuToggle hideCaret onToggle={() => setIsSortDropdownOpen(!isSortDropdownOpen)} toggleTemplate={<SortAmountDownIcon />} /> } isPlain isGrouped /> </ToolbarItem> </ToolbarContent> </Toolbar> <TableComposable aria-label="Sortable table custom toolbar"> <Thead> <Tr> <Th sort={getSortParams(0)}>{columnNames.name}</Th> <Th sort={getSortParams(1)}>{columnNames.branches}</Th> <Th sort={getSortParams(2)} info={{ tooltip: 'More information ' }}> {columnNames.prs} </Th> <Th sort={getSortParams(3)}>{columnNames.workspaces}</Th> <Th sort={getSortParams(4)}>{columnNames.lastCommit}</Th> </Tr> </Thead> <Tbody> {sortedRepositories.map((repo, rowIndex) => ( <Tr key={rowIndex}> <Td dataLabel={columnNames.name}>{repo.name}</Td> <Td dataLabel={columnNames.branches}>{repo.branches}</Td> <Td dataLabel={columnNames.prs}>{repo.prs}</Td> <Td dataLabel={columnNames.workspaces}>{repo.workspaces}</Td> <Td dataLabel={columnNames.lastCommit}>{repo.lastCommit}</Td> </Tr> ))} </Tbody> </TableComposable> </React.Fragment> ); };
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/MultipleFileUpload.tsx
<gh_stars>0 import * as React from 'react'; import Dropzone, { DropzoneProps, DropFileEventHandler } from 'react-dropzone'; import styles from '@patternfly/react-styles/css/components/MultipleFileUpload/multiple-file-upload'; import { css } from '@patternfly/react-styles'; export interface MultipleFileUploadProps extends Omit<React.HTMLProps<HTMLDivElement>, 'value'> { /** Content rendered inside the multi upload field */ children?: React.ReactNode; /** Class to add to outer div */ className?: string; /** Optional extra props to customize react-dropzone. */ dropzoneProps?: DropzoneProps; /** Flag setting the component to horizontal styling mode */ isHorizontal?: boolean; /** When files are dropped or uploaded this callback will be called with all accepted files */ onFileDrop?: (data: File[]) => void; } export const MultipleFileUploadContext = React.createContext({ open: () => {} }); export const MultipleFileUpload: React.FunctionComponent<MultipleFileUploadProps> = ({ className, children, dropzoneProps = {}, isHorizontal, onFileDrop = () => {}, ...props }: MultipleFileUploadProps) => { const onDropAccepted: DropFileEventHandler = (acceptedFiles: File[], event) => { onFileDrop(acceptedFiles); // allow users to set a custom drop accepted handler rather than using on data change dropzoneProps.onDropAccepted && dropzoneProps.onDropAccepted(acceptedFiles, event); }; const onDropRejected: DropFileEventHandler = (rejectedFiles, event) => { dropzoneProps.onDropRejected && dropzoneProps?.onDropRejected(rejectedFiles, event); }; return ( <Dropzone multiple={true} {...dropzoneProps} onDropAccepted={onDropAccepted} onDropRejected={onDropRejected}> {({ getRootProps, getInputProps, isDragActive, open }) => { const rootProps = getRootProps({ ...props, onClick: event => event.preventDefault() // Prevents clicking TextArea from opening file dialog }); const inputProps = getInputProps(); return ( <MultipleFileUploadContext.Provider value={{ open }}> <div className={css( styles.multipleFileUpload, isDragActive && styles.modifiers.dragOver, isHorizontal && styles.modifiers.horizontal, className )} {...rootProps} {...props} > <input /* hidden, necessary for react-dropzone */ {...inputProps} /> {children} </div> </MultipleFileUploadContext.Provider> ); }} </Dropzone> ); }; MultipleFileUpload.displayName = 'MultipleFileUpload';
jelly/patternfly-react
packages/react-topology/src/layouts/ConcentricLink.ts
import { LayoutLink } from './LayoutLink'; export class ConcentricLink extends LayoutLink {}
jelly/patternfly-react
packages/react-core/src/helpers/useInterval.ts
import * as React from 'react'; /** This is a custom React hook in a format suggest by <NAME> in a blog post here: * https://overreacted.io/making-setinterval-declarative-with-react-hooks/. It allows setInterval to be used * declaratively in functional React components. */ export function useInterval(callback: () => void, delay: number | null) { const savedCallback = React.useRef(() => {}); React.useEffect(() => { savedCallback.current = callback; }, [callback]); React.useEffect(() => { function tick() { savedCallback.current(); } if (delay !== null) { const id = setInterval(tick, delay); return () => clearInterval(id); } }, [delay]); }
jelly/patternfly-react
packages/react-topology/src/behavior/useSelection.tsx
<filename>packages/react-topology/src/behavior/useSelection.tsx<gh_stars>0 import * as React from 'react'; import { action, computed } from 'mobx'; import { observer } from 'mobx-react'; import { EventListener } from '../types'; import ElementContext from '../utils/ElementContext'; export const SELECTION_EVENT = 'selection'; export const SELECTION_STATE = 'selectedIds'; export type SelectionEventListener = EventListener<[string[]]>; interface SelectionHandlerState { [SELECTION_STATE]?: string[]; } export type OnSelect = (e: React.MouseEvent) => void; interface Options { multiSelect?: boolean; controlled?: boolean; raiseOnSelect?: boolean; } export const useSelection = ({ multiSelect, controlled, raiseOnSelect = true }: Options = {}): [boolean, OnSelect] => { const element = React.useContext(ElementContext); const elementRef = React.useRef(element); elementRef.current = element; const selected = React.useMemo( () => computed(() => { const { selectedIds } = element.getController().getState<SelectionHandlerState>(); return !!selectedIds && selectedIds.includes(element.getId()); }), [element] ); const onSelect = React.useCallback( action((e: React.MouseEvent): void => { e.stopPropagation(); const id = elementRef.current.getId(); const state = elementRef.current.getController().getState<SelectionHandlerState>(); const idx = state.selectedIds ? state.selectedIds.indexOf(id) : -1; let selectedIds: string[]; let raise = false; if (multiSelect && (e.ctrlKey || e.metaKey)) { if (!state.selectedIds) { raise = true; selectedIds = [id]; } else { selectedIds = [...state.selectedIds]; if (idx === -1) { raise = true; selectedIds.push(id); } else { selectedIds.splice(idx, 1); } } } else if (idx === -1 || multiSelect) { raise = true; selectedIds = [id]; } else { selectedIds = []; } if (!controlled) { state.selectedIds = selectedIds; } elementRef.current.getController().fireEvent(SELECTION_EVENT, selectedIds); if (raiseOnSelect && raise) { elementRef.current.raise(); } }), [multiSelect, controlled, raiseOnSelect] ); return [selected.get(), onSelect]; }; export interface WithSelectionProps { selected: boolean; onSelect: OnSelect; } export const withSelection = (options?: Options) => <P extends WithSelectionProps>( WrappedComponent: React.ComponentType<Partial<P>> ) => { const Component: React.FunctionComponent<Omit<P, keyof WithSelectionProps>> = props => { const [selected, onSelect] = useSelection(options); return <WrappedComponent {...(props as any)} selected={selected} onSelect={onSelect} />; }; Component.displayName = `withSelection(${WrappedComponent.displayName || WrappedComponent.name})`; return observer(Component); };
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/MultipleFileUploadButton.tsx
<filename>packages/react-core/src/components/MultipleFileUpload/MultipleFileUploadButton.tsx<gh_stars>0 import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/MultipleFileUpload/multiple-file-upload'; import { css } from '@patternfly/react-styles'; import { MultipleFileUploadContext } from './MultipleFileUpload'; import { Button } from '../Button'; export interface MultipleFileUploadButtonProps extends React.HTMLProps<HTMLDivElement> { /** Class to add to outer div */ className?: string; /** Aria-label for the button */ 'aria-label'?: string; } export const MultipleFileUploadButton: React.FunctionComponent<MultipleFileUploadButtonProps> = ({ className, 'aria-label': ariaLabel, ...props }: MultipleFileUploadButtonProps) => { const { open } = React.useContext(MultipleFileUploadContext); return ( <div className={css(styles.multipleFileUploadUpload, className)} {...props}> <Button variant="secondary" aria-label={ariaLabel} onClick={open}> Upload </Button> </div> ); }; MultipleFileUploadButton.displayName = 'MultipleFileUploadButton';
jelly/patternfly-react
packages/react-core/src/components/Menu/Menu.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Menu/menu'; import { css } from '@patternfly/react-styles'; import { getOUIAProps, OUIAProps, getDefaultOUIAId } from '../../helpers'; import { MenuContext } from './MenuContext'; import { canUseDOM } from '../../helpers/util'; import { KeyboardHandler } from '../../helpers'; export interface MenuProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'ref' | 'onSelect'>, OUIAProps { /** Anything that can be rendered inside of the Menu */ children?: React.ReactNode; /** Additional classes added to the Menu */ className?: string; /** ID of the menu */ id?: string; /** Callback for updating when item selection changes. You can also specify onClick on the MenuItem. */ onSelect?: (event?: React.MouseEvent, itemId?: string | number) => void; /** Single itemId for single select menus, or array of itemIds for multi select. You can also specify isSelected on the MenuItem. */ selected?: any | any[]; /** Callback called when an MenuItems's action button is clicked. You can also specify it within a MenuItemAction. */ onActionClick?: (event?: any, itemId?: any, actionId?: any) => void; /** Search input of menu */ hasSearchInput?: boolean; /** A callback for when the input value changes. */ onSearchInputChange?: ( event: React.FormEvent<HTMLInputElement> | React.SyntheticEvent<HTMLButtonElement>, value: string ) => void; /** Accessibility label */ 'aria-label'?: string; /** @beta Indicates if menu contains a flyout menu */ containsFlyout?: boolean; /** @beta Indicating that the menu should have nav flyout styling */ isNavFlyout?: boolean; /** @beta Indicates if menu contains a drilldown menu */ containsDrilldown?: boolean; /** @beta Indicates if a menu is drilled into */ isMenuDrilledIn?: boolean; /** @beta Indicates the path of drilled in menu itemIds */ drilldownItemPath?: string[]; /** @beta Array of menus that are drilled in */ drilledInMenus?: string[]; /** @beta Callback for drilling into a submenu */ onDrillIn?: (fromItemId: string, toItemId: string, itemId: string) => void; /** @beta Callback for drilling out of a submenu */ onDrillOut?: (toItemId: string, itemId: string) => void; /** @beta Callback for collecting menu heights */ onGetMenuHeight?: (menuId: string, height: number) => void; /** @beta ID of parent menu for drilldown menus */ parentMenu?: string; /** @beta ID of the currently active menu for the drilldown variant */ activeMenu?: string; /** @beta itemId of the currently active item. You can also specify isActive on the MenuItem. */ activeItemId?: string | number; /** @hide Forwarded ref */ innerRef?: React.Ref<HTMLDivElement>; /** Internal flag indicating if the Menu is the root of a menu tree */ isRootMenu?: boolean; /** Indicates if the menu should be without the outer box-shadow */ isPlain?: boolean; /** Indicates if the menu should be srollable */ isScrollable?: boolean; } export interface MenuState { searchInputValue: string | null; ouiaStateId: string; transitionMoveTarget: HTMLElement; flyoutRef: React.Ref<HTMLLIElement> | null; disableHover: boolean; } class MenuBase extends React.Component<MenuProps, MenuState> { static displayName = 'Menu'; static contextType = MenuContext; context!: React.ContextType<typeof MenuContext>; private menuRef = React.createRef<HTMLDivElement>(); private activeMenu = null as Element; static defaultProps: MenuProps = { ouiaSafe: true, isRootMenu: true, isPlain: false, isScrollable: false }; constructor(props: MenuProps) { super(props); if (props.innerRef) { this.menuRef = props.innerRef as React.RefObject<HTMLDivElement>; } } state: MenuState = { ouiaStateId: getDefaultOUIAId(Menu.displayName), searchInputValue: '', transitionMoveTarget: null, flyoutRef: null, disableHover: false }; allowTabFirstItem() { // Allow tabbing to first menu item const current = this.menuRef.current; if (current) { const first = current.querySelector('ul button, ul a') as HTMLButtonElement | HTMLAnchorElement; if (first) { first.tabIndex = 0; } } } componentDidMount() { if (this.context) { this.setState({ disableHover: this.context.disableHover }); } if (canUseDOM) { window.addEventListener('transitionend', this.props.isRootMenu ? this.handleDrilldownTransition : null); } this.allowTabFirstItem(); } componentWillUnmount() { if (canUseDOM) { window.removeEventListener('transitionend', this.handleDrilldownTransition); } } componentDidUpdate(prevProps: MenuProps) { if (prevProps.children !== this.props.children) { this.allowTabFirstItem(); } } handleDrilldownTransition = (event: TransitionEvent) => { const current = this.menuRef.current; if ( !current || (current !== (event.target as HTMLElement).closest('.pf-c-menu') && !Array.from(current.getElementsByClassName('pf-c-menu')).includes( (event.target as HTMLElement).closest('.pf-c-menu') )) ) { return; } if (this.state.transitionMoveTarget) { this.state.transitionMoveTarget.focus(); this.setState({ transitionMoveTarget: null }); } else { const nextMenu = current.querySelector('#' + this.props.activeMenu) || current || null; const nextTarget = Array.from(nextMenu.getElementsByTagName('UL')[0].children).filter( el => !(el.classList.contains('pf-m-disabled') || el.classList.contains('pf-c-divider')) )[0].firstChild; (nextTarget as HTMLElement).focus(); (nextTarget as HTMLElement).tabIndex = 0; } }; handleExtraKeys = (event: KeyboardEvent) => { const isDrilldown = this.props.containsDrilldown; const activeElement = document.activeElement; if ( (event.target as HTMLElement).closest('.pf-c-menu') !== this.activeMenu && !(event.target as HTMLElement).classList.contains('pf-c-breadcrumb__link') ) { this.activeMenu = (event.target as HTMLElement).closest('.pf-c-menu'); this.setState({ disableHover: true }); } if ((event.target as HTMLElement).tagName === 'INPUT') { return; } const parentMenu = this.activeMenu; const key = event.key; const isFromBreadcrumb = activeElement.classList.contains('pf-c-breadcrumb__link') || activeElement.classList.contains('pf-c-dropdown__toggle'); if (key === ' ' || key === 'Enter') { event.preventDefault(); if (isDrilldown && !isFromBreadcrumb) { const isDrillingOut = activeElement.closest('li').classList.contains('pf-m-current-path'); if (isDrillingOut && parentMenu.parentElement.tagName === 'LI') { (activeElement as HTMLElement).tabIndex = -1; (parentMenu.parentElement.firstChild as HTMLElement).tabIndex = 0; this.setState({ transitionMoveTarget: parentMenu.parentElement.firstChild as HTMLElement }); } else { if (activeElement.nextElementSibling && activeElement.nextElementSibling.classList.contains('pf-c-menu')) { const childItems = Array.from( activeElement.nextElementSibling.getElementsByTagName('UL')[0].children ).filter(el => !(el.classList.contains('pf-m-disabled') || el.classList.contains('pf-c-divider'))); (activeElement as HTMLElement).tabIndex = -1; (childItems[0].firstChild as HTMLElement).tabIndex = 0; this.setState({ transitionMoveTarget: childItems[0].firstChild as HTMLElement }); } } } (document.activeElement as HTMLElement).click(); } }; createNavigableElements = () => { const isDrilldown = this.props.containsDrilldown; return isDrilldown ? Array.from(this.activeMenu.getElementsByTagName('UL')[0].children).filter( el => !(el.classList.contains('pf-m-disabled') || el.classList.contains('pf-c-divider')) ) : Array.from(this.activeMenu.getElementsByTagName('LI')).filter( el => !(el.classList.contains('pf-m-disabled') || el.classList.contains('pf-c-divider')) ); }; render() { const { 'aria-label': ariaLabel, id, children, className, onSelect, selected = null, onActionClick, ouiaId, ouiaSafe, containsFlyout, isNavFlyout, containsDrilldown, isMenuDrilledIn, isPlain, isScrollable, drilldownItemPath, drilledInMenus, onDrillIn, onDrillOut, onGetMenuHeight, parentMenu = null, activeItemId = null, /* eslint-disable @typescript-eslint/no-unused-vars */ innerRef, isRootMenu, activeMenu, /* eslint-enable @typescript-eslint/no-unused-vars */ ...props } = this.props; const _isMenuDrilledIn = isMenuDrilledIn || (drilledInMenus && drilledInMenus.includes(id)) || false; return ( <MenuContext.Provider value={{ menuId: id, parentMenu: parentMenu || id, onSelect, onActionClick, activeItemId, selected, drilledInMenus, drilldownItemPath, onDrillIn, onDrillOut, onGetMenuHeight, flyoutRef: this.state.flyoutRef, setFlyoutRef: flyoutRef => this.setState({ flyoutRef }), disableHover: this.state.disableHover }} > {isRootMenu && ( <KeyboardHandler containerRef={(this.menuRef as React.RefObject<HTMLDivElement>) || null} additionalKeyHandler={this.handleExtraKeys} createNavigableElements={this.createNavigableElements} isActiveElement={(element: Element) => document.activeElement.parentElement === element || (document.activeElement.closest('ol') && document.activeElement.closest('ol').firstChild === element) } getFocusableElement={(navigableElement: Element) => navigableElement.firstChild as Element} noHorizontalArrowHandling={ document.activeElement && (document.activeElement.classList.contains('pf-c-breadcrumb__link') || document.activeElement.classList.contains('pf-c-dropdown__toggle')) } noEnterHandling noSpaceHandling /> )} <div id={id} className={css( styles.menu, isPlain && styles.modifiers.plain, isScrollable && styles.modifiers.scrollable, containsFlyout && styles.modifiers.flyout, isNavFlyout && styles.modifiers.nav, containsDrilldown && styles.modifiers.drilldown, _isMenuDrilledIn && styles.modifiers.drilledIn, className )} aria-label={ariaLabel} ref={this.menuRef} {...getOUIAProps(Menu.displayName, ouiaId !== undefined ? ouiaId : this.state.ouiaStateId, ouiaSafe)} {...props} > {children} </div> </MenuContext.Provider> ); } } export const Menu = React.forwardRef((props: MenuProps, ref: React.Ref<HTMLDivElement>) => ( <MenuBase {...props} innerRef={ref} /> )); Menu.displayName = 'Menu';
jelly/patternfly-react
packages/react-charts/src/components/ChartDonutUtilization/ChartDonutThreshold.tsx
import * as React from 'react'; import { AnimatePropTypeInterface, CategoryPropType, Data, DataGetterPropType, EventCallbackInterface, EventPropTypeInterface, Helpers, NumberOrCallback, OriginType, PaddingProps, SliceNumberOrCallback, SortOrderPropType, StringOrNumberOrCallback, StringOrNumberOrList, VictoryStyleInterface } from 'victory-core'; import { SliceProps, VictoryPie } from 'victory-pie'; import hoistNonReactStatics from 'hoist-non-react-statics'; import { ChartContainer } from '../ChartContainer'; import { ChartDonut, ChartDonutProps } from '../ChartDonut'; import { ChartDonutStyles, ChartThemeDefinition } from '../ChartTheme'; import { getDonutThresholdDynamicTheme, getDonutThresholdStaticTheme, getPaddingForSide } from '../ChartUtils'; export enum ChartDonutThresholdDonutOrientation { left = 'left', right = 'right', top = 'top' } export enum ChartDonutThresholdLabelOrientation { horizontal = 'horizontal', vertical = 'vertical' } export enum ChartDonutThresholdLabelPosition { centroid = 'centroid', endAngle = 'endAngle', startAngle = 'startAngle' } export enum ChartDonutThresholdSortOrder { ascending = 'ascending', descending = 'descending' } export enum ChartDonutThresholdSubTitlePosition { bottom = 'bottom', center = 'center', right = 'right' } /** * See https://github.com/FormidableLabs/victory/blob/master/packages/victory-core/src/index.d.ts * and https://github.com/FormidableLabs/victory/blob/master/packages/victory-pie/src/index.d.ts */ export interface ChartDonutThresholdProps extends ChartDonutProps { /** * Specifies the tooltip capability of the container component. A value of true allows the chart to add a * ChartTooltip component to the labelComponent property. This is a shortcut to display tooltips when the labels * property is also provided. */ allowTooltip?: boolean; /** * The animate prop specifies props for VictoryAnimation to use. * The animate prop should also be used to specify enter and exit * transition configurations with the `onExit` and `onEnter` namespaces respectively. * * @propType boolean | object * @example * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} */ animate?: boolean | AnimatePropTypeInterface; /** * The ariaDesc prop specifies the description of the chart/SVG to assist with * accessibility for screen readers. * * Note: Overridden by the desc prop of containerComponent */ ariaDesc?: string; /** * The ariaTitle prop specifies the title to be applied to the SVG to assist * accessibility for screen readers. * * Note: Overridden by the title prop of containerComponent */ ariaTitle?: string; /** * The categories prop specifies how categorical data for a chart should be ordered. * This prop should be given as an array of string values, or an object with * these arrays of values specified for x and y. If this prop is not set, * categorical data will be plotted in the order it was given in the data array * * @propType string[] | { x: string[], y: string[] } * @example ["dogs", "cats", "mice"] */ categories?: CategoryPropType; /** * The utilization donut chart to render with the threshold donut chart * * Note: This prop should not be set manually. * * @hide */ children?: React.ReactElement<any>; /** * The colorScale prop is an optional prop that defines the color scale the pie * will be created on. This prop should be given as an array of CSS colors, or as a string * corresponding to one of the built in color scales. ChartDonutThreshold will automatically assign * values from this color scale to the pie slices unless colors are explicitly provided in the * data object */ colorScale?: string[]; /** * The constrainToVisibleArea prop determines whether to coerce tooltips so that they fit within the visible area of * the chart. When this prop is set to true, tooltip pointers will still point to the correct data point, but the * center of the tooltip will be shifted to fit within the overall width and height of the svg Victory renders. */ constrainToVisibleArea?: boolean; /** * The containerComponent prop takes an entire component which will be used to * create a container element for standalone charts. * The new element created from the passed containerComponent wil be provided with * these props from ChartDonutThreshold: height, width, children * (the chart itself) and style. Props that are not provided by the * child chart component include title and desc, both of which * are intended to add accessibility to Victory components. The more descriptive these props * are, the more accessible your data will be for people using screen readers. * Any of these props may be overridden by passing in props to the supplied component, * or modified or ignored within the custom component itself. If a dataComponent is * not provided, ChartDonutThreshold will use the default ChartContainer component. * * @example <ChartContainer title="Chart of Dog Breeds" desc="This chart shows ..." /> */ containerComponent?: React.ReactElement<any>; /** * Set the cornerRadius for every dataComponent (Slice by default) within ChartDonutThreshold * * @propType number | Function */ cornerRadius?: SliceNumberOrCallback<SliceProps, 'cornerRadius'>; /** * The data prop specifies the data to be plotted, * where data X-value is the slice label (string or number), * and Y-value is the corresponding number value represented by the slice * Data should be in the form of a single data point. * The data point may be any format you wish (depending on the `x` and `y` accessor props), * but by default, an object with x and y properties is expected. * * Note: The Y-value is expected to represent a percentage * * @example data={[{ x: 'Warning at 60%', y: 60 }, { x: 'Danger at 90%', y: 90 }]} */ data?: any[]; /** * The dataComponent prop takes an entire, HTML-complete data component which will be used to * create slices for each datum in the pie chart. The new element created from the passed * dataComponent will have the property datum set by the pie chart for the point it renders; * properties style and pathFunction calculated by ChartDonutThreshold; an index property set * corresponding to the location of the datum in the data provided to the pie; events bound to * the ChartDonutThreshold; and the d3 compatible slice object. * If a dataComponent is not provided, ChartDonutThreshold's Slice component will be used. */ dataComponent?: React.ReactElement<any>; /** * The desc prop specifies the description of the chart/SVG to assist with * accessibility for screen readers. The more info about the chart provided in * the description, the more usable it will be for people using screen readers. * This prop defaults to an empty string. * * Note: Overridden by containerComponent * * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are * not represented above 5% each." */ desc?: string; /** * The overall end angle of the pie in degrees. This prop is used in conjunction with * startAngle to create a pie that spans only a segment of a circle. */ endAngle?: number; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data * * @propType number | string | Function */ eventKey?: StringOrNumberOrCallback; /** * The event prop takes an array of event objects. Event objects are composed of * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace * for a given component, so "data" and "labels" are all valid targets for ChartDonutThreshold * events. The eventKey may optionally be used to select a single element by index rather than * an entire set. The eventHandlers object should be given as an object whose keys are standard * event names (i.e. onClick) and whose values are event callbacks. The return value * of an event handler is used to modify elemnts. The return value should be given * as an object or an array of objects with optional target and eventKey keys, * and a mutation key whose value is a function. The target and eventKey keys * will default to those corresponding to the element the event handler was attached to. * The mutation function will be called with the calculated props for the individual selected * element (i.e. a single bar), and the object returned from the mutation function * will override the props of the selected element via object assignment. * * @propType object[] * @example * events={[ * { * target: "data", * eventKey: 1, * eventHandlers: { * onClick: () => { * return [ * { * eventKey: 2, * mutation: (props) => { * return {style: merge({}, props.style, {fill: "orange"})}; * } * }, { * eventKey: 2, * target: "labels", * mutation: () => { * return {text: "hey"}; * } * } * ]; * } * } * } * ]} */ events?: EventPropTypeInterface<'data' | 'labels' | 'parent', StringOrNumberOrCallback | string[] | number[]>[]; /** * ChartDonutThreshold uses the standard externalEventMutations prop. * * @propType object[] */ externalEventMutations?: EventCallbackInterface<string | string[], StringOrNumberOrList>[]; /** * The groupComponent prop takes an entire component which will be used to * create group elements for use within container elements. This prop defaults * to a <g> tag on web, and a react-native-svg <G> tag on mobile */ groupComponent?: React.ReactElement<any>; /** * Specifies the height the svg viewBox of the chart container. This value should be given as a number of pixels. * * Because Victory renders responsive containers, the width and height props do not determine the width and * height of the chart in number of pixels, but instead define an aspect ratio for the chart. The exact number of * pixels will depend on the size of the container the chart is rendered into. Typically, the parent container is set * to the same height in order to maintain the aspect ratio. */ height?: number; /** * When creating a donut chart, this prop determines the number of pixels between * the center of the chart and the inner edge. * * @propType number | Function */ innerRadius?: NumberOrCallback; /** * Invert the threshold color scale used to represent warnings, errors, etc. */ invert?: boolean; /** * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. * If this prop is not set, the label radius will default to the radius of the pie + label padding. * * @propType number | Function */ labelRadius?: number | ((props: SliceProps) => number); /** * The labels prop defines labels that will appear above each bar in your chart. * This prop should be given as an array of values or as a function of data. * If given as an array, the number of elements in the array should be equal to * the length of the data array. Labels may also be added directly to the data object * like data={[{x: 1, y: 1, label: "first"}]}. * * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title */ labels?: string[] | number[] | ((data: any) => string | number | null); /** * The name prop is used to reference a component instance when defining shared events. */ name?: string; /** * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. * * Note: It will not typically be necessary to set an origin prop manually * * @propType { x: number, y: number } */ origin?: OriginType; /** * The padAngle prop determines the amount of separation between adjacent data slices * in number of degrees * * @propType number | Function */ padAngle?: NumberOrCallback; /** * The padding props specifies the amount of padding in number of pixels between * the edge of the chart and any rendered child components. This prop can be given * as a number or as an object with padding specified for top, bottom, left * and right. * * @propType number | { top: number, bottom: number, left: number, right: number } */ padding?: PaddingProps; /** * Specifies the radius of the chart. If this property is not provided it is computed * from width, height, and padding props * * @propType number | Function */ radius?: NumberOrCallback; /** * The sharedEvents prop is used internally to coordinate events between components. * * Note: This prop should not be set manually. * * @hide */ sharedEvents?: { events: any[]; getEventState: Function }; /** * This will show the static, unused portion of the donut chart */ showStatic?: boolean; /** * Use the sortKey prop to indicate how data should be sorted. This prop * is given directly to the lodash sortBy function to be executed on the * final dataset. * * @propType number | string | Function | string[] */ sortKey?: DataGetterPropType; /** * The sortOrder prop specifies whether sorted data should be returned in 'ascending' or 'descending' order. * * @propType string */ sortOrder?: SortOrderPropType; /** * The standalone prop determines whether the component will render a standalone svg * or a <g> tag that will be included in an external svg. Set standalone to false to * compose ChartDonutThreshold with other components within an enclosing <svg> tag. */ standalone?: boolean; /** * The overall start angle of the pie in degrees. This prop is used in conjunction with * endAngle to create a pie that spans only a segment of a circle. */ startAngle?: number; /** * The style prop specifies styles for your pie. ChartDonutThreshold relies on Radium, * so valid Radium style objects should work for this prop. Height, width, and * padding should be specified via the height, width, and padding props. * * @propType { parent: object, data: object, labels: object } * @example {data: {stroke: "black"}, label: {fontSize: 10}} */ style?: VictoryStyleInterface; /** * The subtitle for the donut chart */ subTitle?: string; /** * The orientation of the subtitle position. Valid values are 'bottom', 'center', and 'right' */ subTitlePosition?: 'bottom' | 'center' | 'right'; /** * The theme prop takes a style object with nested data, labels, and parent objects. * You can create this object yourself, or you can use a theme provided by * When using ChartDonutThreshold as a solo component, implement the theme directly on * ChartDonutThreshold. If you are wrapping ChartDonutThreshold in ChartChart or ChartGroup, * please call the theme on the outermost wrapper component instead. * * @propType object */ theme?: ChartThemeDefinition; /** * Specifies the theme color. Valid values are 'blue', 'green', 'multi', etc. * * Note: Not compatible with theme prop * * @example themeColor={ChartThemeColor.blue} */ themeColor?: string; /** * Specifies the theme variant. Valid values are 'dark' or 'light' * * Note: Not compatible with theme prop * * @example themeVariant={ChartThemeVariant.light} */ themeVariant?: string; /** * The title for the donut chart */ title?: string; /** * Specifies the width of the svg viewBox of the chart container. This value should be given as a number of pixels. * * Because Victory renders responsive containers, the width and height props do not determine the width and * height of the chart in number of pixels, but instead define an aspect ratio for the chart. The exact number of * pixels will depend on the size of the container the chart is rendered into. Typically, the parent container is set * to the same width in order to maintain the aspect ratio. */ width?: number; /** * The x prop specifies how to access the X value of each data point. * If given as a function, it will be run on each data point, and returned value will be used. * If given as an integer, it will be used as an array index for array-type data points. * If given as a string, it will be used as a property key for object-type data points. * If given as an array of strings, or a string containing dots or brackets, * it will be used as a nested object property path (for details see Lodash docs for _.get). * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). * * @propType number | string | Function | string[] * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) */ x?: DataGetterPropType; /** * The y prop specifies how to access the Y value of each data point. * If given as a function, it will be run on each data point, and returned value will be used. * If given as an integer, it will be used as an array index for array-type data points. * If given as a string, it will be used as a property key for object-type data points. * If given as an array of strings, or a string containing dots or brackets, * it will be used as a nested object property path (for details see Lodash docs for _.get). * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). * * @propType number | string | Function | string[] * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) */ y?: DataGetterPropType; } export const ChartDonutThreshold: React.FunctionComponent<ChartDonutThresholdProps> = ({ allowTooltip = true, ariaDesc, ariaTitle, children, constrainToVisibleArea = false, containerComponent = <ChartContainer />, data = [], invert = false, labels = [], // Don't show any tooltip labels by default, let consumer override if needed padding, radius, standalone = true, subTitlePosition = ChartDonutStyles.label.subTitlePosition as ChartDonutThresholdSubTitlePosition, themeColor, themeVariant, x, y, // destructure last theme = getDonutThresholdStaticTheme(themeColor, themeVariant, invert), height = theme.pie.height, width = theme.pie.width, ...rest }: ChartDonutThresholdProps) => { const defaultPadding = { bottom: getPaddingForSide('bottom', padding, theme.pie.padding), left: getPaddingForSide('left', padding, theme.pie.padding), right: getPaddingForSide('right', padding, theme.pie.padding), top: getPaddingForSide('top', padding, theme.pie.padding) }; const chartRadius = radius || Helpers.getRadius({ height, width, padding: defaultPadding }); // Returns computed data representing pie chart slices const getComputedData = () => { // Format and sort data. Sorting ensures thresholds are displayed in the correct order and simplifies calculations. const datum = Data.formatData(data, { x, y, ...rest }, ['x', 'y']).sort((a: any, b: any) => a._y - b._y); // Data must be offset so that the sum of all data point y-values (including the final slice) == 100. const [prev, computedData] = datum.reduce( (acc: [number, any], dataPoint: { _x: number | string; _y: number }) => [ dataPoint._y, // Set the previous value to current y value [ ...acc[1], { x: dataPoint._x, // Conditionally add x property only if it is in the original data object y: dataPoint._y - acc[0] // Must be offset by previous value } ] ], [0, []] ); return [ ...computedData, { y: prev ? 100 - prev : 0 } ]; }; // Render dynamic utilization donut cart const renderChildren = () => React.Children.toArray(children).map((child, index) => { if (React.isValidElement(child)) { const { data: childData, ...childProps } = child.props; const datum = Data.formatData([childData], childProps, ['x', 'y']); // Format child data independently of this component's props const dynamicTheme = childProps.theme || getDonutThresholdDynamicTheme(childProps.themeColor || themeColor, childProps.themeVariant || themeVariant); return React.cloneElement(child, { constrainToVisibleArea, data: childData, endAngle: 360 * (datum[0]._y ? datum[0]._y / 100 : 0), height, invert, key: `pf-chart-donut-threshold-child-${index}`, padding: defaultPadding, radius: chartRadius - 14, // Donut utilization radius is threshold radius minus 14px spacing showStatic: false, standalone: false, subTitlePosition: childProps.subTitlePosition || subTitlePosition, theme: dynamicTheme, width, ...childProps }); } return child; }); // Static threshold donut chart const chart = ( <ChartDonut allowTooltip={allowTooltip} constrainToVisibleArea={constrainToVisibleArea} data={getComputedData()} height={height} key="pf-chart-donut-threshold" labels={labels} padding={defaultPadding} standalone={false} theme={theme} width={width} {...rest} /> ); // Clone so users can override container props const container = React.cloneElement( containerComponent, { desc: ariaDesc, height, title: ariaTitle, width, theme, ...containerComponent.props }, [chart, renderChildren()] ); return standalone ? ( <React.Fragment>{container}</React.Fragment> ) : ( <React.Fragment> {chart} {renderChildren()} </React.Fragment> ); }; ChartDonutThreshold.displayName = 'ChartDonutThreshold'; // Note: VictoryPie.role must be hoisted hoistNonReactStatics(ChartDonutThreshold, VictoryPie);
jelly/patternfly-react
packages/react-topology/src/elements/defaultElementFactory.ts
import { ElementFactory, GraphElement, ModelKind } from '../types'; import BaseEdge from './BaseEdge'; import BaseGraph from './BaseGraph'; import BaseNode from './BaseNode'; const defaultElementFactory: ElementFactory = (kind: ModelKind): GraphElement | undefined => { switch (kind) { case ModelKind.graph: return new BaseGraph(); case ModelKind.node: return new BaseNode(); case ModelKind.edge: return new BaseEdge(); default: return undefined; } }; export default defaultElementFactory;
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/__tests__/MultipleFileUploadTitleTextSeparator.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import { MultipleFileUploadTitleTextSeparator } from '../MultipleFileUploadTitleTextSeparator'; describe('MultipleFileUploadTitleTextSeparator', () => { test('renders with expected class names', () => { const { asFragment } = render(<MultipleFileUploadTitleTextSeparator>Foo</MultipleFileUploadTitleTextSeparator>); expect(asFragment()).toMatchSnapshot(); }); test('renders custom class names', () => { const { asFragment } = render( <MultipleFileUploadTitleTextSeparator className="test">Foo</MultipleFileUploadTitleTextSeparator> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/DualListSelector/DualListSelectorPane.tsx
<gh_stars>100-1000 import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/DualListSelector/dual-list-selector'; import { css } from '@patternfly/react-styles'; import formStyles from '@patternfly/react-styles/css/components/FormControl/form-control'; import { DualListSelectorTree, DualListSelectorTreeItemData } from './DualListSelectorTree'; import { getUniqueId } from '../../helpers'; import { DualListSelectorListWrapper } from './DualListSelectorListWrapper'; import { DualListSelectorContext, DualListSelectorPaneContext } from './DualListSelectorContext'; import { DualListSelectorList } from './DualListSelectorList'; export interface DualListSelectorPaneProps { /** Additional classes applied to the dual list selector pane. */ className?: string; /** A dual list selector list or dual list selector tree to be rendered in the pane. */ children?: React.ReactNode; /** Flag indicating if this pane is the chosen pane. */ isChosen?: boolean; /** Status to display above the pane. */ status?: string; /** Title of the pane. */ title?: React.ReactNode; /** A search input placed above the list at the top of the pane, before actions. */ searchInput?: React.ReactNode; /** Actions to place above the pane. */ actions?: React.ReactNode[]; /** Id of the pane. */ id?: string; /** @hide Options to list in the pane. */ options?: React.ReactNode[]; /** @hide Options currently selected in the pane. */ selectedOptions?: string[] | number[]; /** @hide Callback for when an option is selected. Optionally used only when options prop is provided. */ onOptionSelect?: ( e: React.MouseEvent | React.ChangeEvent | React.KeyboardEvent, index: number, isChosen: boolean, id?: string, itemData?: any, parentData?: any ) => void; /** @hide Callback for when a tree option is checked. Optionally used only when options prop is provided. */ onOptionCheck?: ( evt: React.MouseEvent | React.ChangeEvent<HTMLInputElement> | React.KeyboardEvent, isChecked: boolean, itemData: DualListSelectorTreeItemData ) => void; /** @hide Flag indicating a dynamically built search bar should be included above the pane. */ isSearchable?: boolean; /** Flag indicating whether the component is disabled. */ isDisabled?: boolean; /** Callback for search input. To be used when isSearchable is true. */ onSearch?: (event: React.ChangeEvent<HTMLInputElement>) => void; /** @hide A callback for when the search input value for changes. To be used when isSearchable is true. */ onSearchInputChanged?: (value: string, event: React.FormEvent<HTMLInputElement>) => void; /** @hide Filter function for custom filtering based on search string. To be used when isSearchable is true. */ filterOption?: (option: React.ReactNode, input: string) => boolean; /** @hide Accessible label for the search input. To be used when isSearchable is true. */ searchInputAriaLabel?: string; /** @hide Callback for updating the filtered options in DualListSelector. To be used when isSearchable is true. */ onFilterUpdate?: (newFilteredOptions: React.ReactNode[], paneType: string, isSearchReset: boolean) => void; } export const DualListSelectorPane: React.FunctionComponent<DualListSelectorPaneProps> = ({ isChosen = false, className = '', status = '', actions, searchInput, children, onOptionSelect, onOptionCheck, title = '', options = [] as React.ReactNode[], selectedOptions = [], isSearchable = false, searchInputAriaLabel = '', onFilterUpdate, onSearchInputChanged, filterOption, id = getUniqueId('dual-list-selector-pane'), isDisabled = false, ...props }: DualListSelectorPaneProps) => { const [input, setInput] = React.useState(''); const { isTree } = React.useContext(DualListSelectorContext); // only called when search input is dynamically built const onChange = (e: React.ChangeEvent<HTMLInputElement>) => { const newValue = e.target.value; let filtered; if (isTree) { filtered = (options as DualListSelectorTreeItemData[]) .map(opt => Object.assign({}, opt)) .filter(item => filterInput(item as DualListSelectorTreeItemData, newValue)); } else { filtered = options.filter(option => { if (displayOption(option)) { return option; } }); } onFilterUpdate(filtered, isChosen ? 'chosen' : 'available', newValue === ''); if (onSearchInputChanged) { onSearchInputChanged(newValue, e); } setInput(newValue); }; // only called when options are passed via options prop and isTree === true const filterInput = (item: DualListSelectorTreeItemData, input: string): boolean => { if (filterOption) { return filterOption(item, input); } else { if (item.text.toLowerCase().includes(input.toLowerCase()) || input === '') { return true; } } if (item.children) { return ( (item.children = item.children.map(opt => Object.assign({}, opt)).filter(child => filterInput(child, input))) .length > 0 ); } }; // only called when options are passed via options prop and isTree === false const displayOption = (option: React.ReactNode) => { if (filterOption) { return filterOption(option, input); } else { return option .toString() .toLowerCase() .includes(input.toLowerCase()); } }; return ( <div className={css(styles.dualListSelectorPane, isChosen ? styles.modifiers.chosen : 'pf-m-available', className)} {...props} > {title && ( <div className={css(styles.dualListSelectorHeader)}> <div className="pf-c-dual-list-selector__title"> <div className={css(styles.dualListSelectorTitleText)}>{title}</div> </div> </div> )} {(actions || searchInput || isSearchable) && ( <div className={css(styles.dualListSelectorTools)}> {(isSearchable || searchInput) && ( <div className={css(styles.dualListSelectorToolsFilter)}> {searchInput ? ( searchInput ) : ( <input className={css(formStyles.formControl, formStyles.modifiers.search)} type="search" onChange={isDisabled ? undefined : onChange} aria-label={searchInputAriaLabel} disabled={isDisabled} /> )} </div> )} {actions && <div className={css(styles.dualListSelectorToolsActions)}>{actions}</div>} </div> )} {status && ( <div className={css(styles.dualListSelectorStatus)}> <div className={css(styles.dualListSelectorStatusText)} id={`${id}-status`}> {status} </div> </div> )} <DualListSelectorPaneContext.Provider value={{ isChosen }}> {!isTree && ( <DualListSelectorListWrapper aria-labelledby={`${id}-status`} options={options} selectedOptions={selectedOptions} onOptionSelect={( e: React.MouseEvent | React.ChangeEvent | React.KeyboardEvent, index: number, id: string ) => onOptionSelect(e, index, isChosen, id)} displayOption={displayOption} id={`${id}-list`} isDisabled={isDisabled} > {children} </DualListSelectorListWrapper> )} {isTree && ( <DualListSelectorListWrapper aria-labelledby={`${id}-status`} id={`${id}-list`}> {options.length > 0 ? ( <DualListSelectorList> <DualListSelectorTree data={ isSearchable ? (options as DualListSelectorTreeItemData[]) .map(opt => Object.assign({}, opt)) .filter(item => filterInput(item as DualListSelectorTreeItemData, input)) : (options as DualListSelectorTreeItemData[]) } onOptionCheck={onOptionCheck} id={`${id}-tree`} isDisabled={isDisabled} /> </DualListSelectorList> ) : ( children )} </DualListSelectorListWrapper> )} </DualListSelectorPaneContext.Provider> </div> ); }; DualListSelectorPane.displayName = 'DualListSelectorPane';
jelly/patternfly-react
packages/react-core/src/components/Checkbox/examples/CheckboxUncontrolled.tsx
<reponame>jelly/patternfly-react<filename>packages/react-core/src/components/Checkbox/examples/CheckboxUncontrolled.tsx<gh_stars>0 import React from 'react'; import { Checkbox } from '@patternfly/react-core'; export const CheckboxUncontrolled: React.FunctionComponent = () => ( <React.Fragment> <Checkbox label="Uncontrolled CheckBox 1" id="uncontrolled-check-1" /> <Checkbox label="Uncontrolled CheckBox 2" id="uncontrolled-check-2" /> </React.Fragment> );
jelly/patternfly-react
packages/react-core/src/components/Modal/__tests__/ModalBoxBody.test.tsx
<filename>packages/react-core/src/components/Modal/__tests__/ModalBoxBody.test.tsx import * as React from 'react'; import { render } from '@testing-library/react'; import { ModalBoxBody } from '../ModalBoxBody'; test('ModalBoxBody Test', () => { const { asFragment } = render( <ModalBoxBody id="id" className="test-box-class"> This is a ModalBox header </ModalBoxBody> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/Pagination/__tests__/Generated/ToggleTemplate.test.tsx
<filename>packages/react-core/src/components/Pagination/__tests__/Generated/ToggleTemplate.test.tsx /** * This test was generated */ import * as React from 'react'; import { render } from '@testing-library/react'; import { ToggleTemplate } from '../../ToggleTemplate'; // any missing imports can usually be resolved by adding them here import {} from '../..'; it('ToggleTemplate should match snapshot (auto-generated)', () => { const { asFragment } = render(<ToggleTemplate firstIndex={0} lastIndex={0} itemCount={0} itemsTitle={"'items'"} />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-code-editor/src/components/CodeEditor/examples/CodeEditorBasic.tsx
import React from 'react'; import { CodeEditor, Language } from '@patternfly/react-code-editor'; import { Checkbox } from '@patternfly/react-core'; export const CodeEditorBasic: React.FunctionComponent = () => { const [isDarkTheme, setIsDarkTheme] = React.useState(false); const [isLineNumbersVisible, setIsLineNumbersVisible] = React.useState(true); const [isReadOnly, setIsReadOnly] = React.useState(false); const [isMinimapVisible, setIsMinimapVisible] = React.useState(false); const toggleDarkTheme = checked => { setIsDarkTheme(checked); }; const toggleLineNumbers = checked => { setIsLineNumbersVisible(checked); }; const toggleReadOnly = checked => { setIsReadOnly(checked); }; const toggleMinimap = checked => { setIsMinimapVisible(checked); }; 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 ( <> <Checkbox label="Dark theme" isChecked={isDarkTheme} onChange={toggleDarkTheme} aria-label="dark theme checkbox" id="toggle-theme" name="toggle-theme" /> <Checkbox label="Line numbers" isChecked={isLineNumbersVisible} onChange={toggleLineNumbers} aria-label="line numbers checkbox" id="toggle-line-numbers" name="toggle-line-numbers" /> <Checkbox label="Read only" isChecked={isReadOnly} onChange={toggleReadOnly} aria-label="read only checkbox" id="toggle-read-only" name="toggle-read-only" /> <Checkbox label="Minimap" isChecked={isMinimapVisible} onChange={toggleMinimap} aria-label="display minimap checkbox" id="toggle-minimap" name="toggle-minimap" /> <CodeEditor isDarkTheme={isDarkTheme} isLineNumbersVisible={isLineNumbersVisible} isReadOnly={isReadOnly} isMinimapVisible={isMinimapVisible} isLanguageLabelVisible code="Some example content" onChange={onChange} language={Language.javascript} onEditorDidMount={onEditorDidMount} height="400px" /> </> ); };
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/MultipleFileUploadTitle.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/MultipleFileUpload/multiple-file-upload'; import { css } from '@patternfly/react-styles'; import { MultipleFileUploadTitleIcon } from './MultipleFileUploadTitleIcon'; import { MultipleFileUploadTitleText } from './MultipleFileUploadTitleText'; import { MultipleFileUploadTitleTextSeparator } from './MultipleFileUploadTitleTextSeparator'; export interface MultipleFileUploadTitleProps extends React.HTMLProps<HTMLDivElement> { /** Class to add to outer div */ className?: string; /** Content rendered inside the title icon div */ icon?: React.ReactNode; /** Content rendered inside the title text div */ text?: React.ReactNode; /** Content rendered inside the title text separator div */ textSeparator?: React.ReactNode; } export const MultipleFileUploadTitle: React.FunctionComponent<MultipleFileUploadTitleProps> = ({ className, icon, text = '', textSeparator = '', ...props }: MultipleFileUploadTitleProps) => ( <div className={css(styles.multipleFileUploadTitle, className)} {...props}> {icon && <MultipleFileUploadTitleIcon>{icon}</MultipleFileUploadTitleIcon>} {text && ( <MultipleFileUploadTitleText> {`${text} `} {textSeparator && <MultipleFileUploadTitleTextSeparator>{textSeparator}</MultipleFileUploadTitleTextSeparator>} </MultipleFileUploadTitleText> )} </div> ); MultipleFileUploadTitle.displayName = 'MultipleFileUploadTitle';
jelly/patternfly-react
packages/react-topology/src/utils/useSize.ts
import * as React from 'react'; interface Size { width: number; height: number; } const EMPTY: any[] = []; export const useSize = (dependencies: any[] = EMPTY): [Size | undefined, (node: SVGGraphicsElement) => void] => { const [size, setSize] = React.useState<Size>(); const sizeRef = React.useRef<Size | undefined>(); sizeRef.current = size; const callbackRef = React.useCallback((node: SVGGraphicsElement): void => { if (node != null) { const bb = node.getBBox(); if (!sizeRef.current || sizeRef.current.width !== bb.width || sizeRef.current.height !== bb.height) { setSize({ width: bb.width, height: bb.height }); } } // dynamic dependencies // eslint-disable-next-line react-hooks/exhaustive-deps }, dependencies); return [size, callbackRef]; };
jelly/patternfly-react
packages/react-core/src/components/LoginPage/__tests__/LoginFooterItem.test.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import { LoginFooterItem } from '../LoginFooterItem'; describe('LoginFooterItem', () => { test('renders with PatternFly Core styles', () => { const { asFragment } = render(<LoginFooterItem target="_self" href="#" />); expect(asFragment()).toMatchSnapshot(); }); test('className is added to the root element', () => { render(<LoginFooterItem className="extra-class" />); expect(screen.getByRole('link')).toHaveClass('extra-class'); }); test('with custom node', () => { const CustomNode = () => <div>My custom node</div>; render( <LoginFooterItem> <CustomNode /> </LoginFooterItem> ); expect(screen.getByText('My custom node')).toBeInTheDocument(); }); });
jelly/patternfly-react
packages/react-topology/src/components/defs/SVGDefsContext.ts
<gh_stars>100-1000 import { createContext, ReactNode } from 'react'; export interface SVGDefsContextProps { addDef(id: string, node: ReactNode): void; removeDef(id: string): void; } const SVGDefsContext = createContext<SVGDefsContextProps>(undefined as any); export default SVGDefsContext;
jelly/patternfly-react
packages/react-catalog-view-extension/src/components/CatalogTile/index.ts
<gh_stars>100-1000 export * from './CatalogTile'; export * from './CatalogTileBadge';
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/Groups.tsx
<reponame>jelly/patternfly-react<filename>packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/Groups.tsx import * as React from 'react'; import { observer } from 'mobx-react'; import { Model, Node, AnchorEnd, NodeShape, useSvgAnchor, withDragNode, WithDragNodeProps, useModel, useLayoutFactory, useComponentFactory, ComponentFactory } from '@patternfly/react-topology'; import defaultComponentFactory from './components/defaultComponentFactory'; import DefaultGroup from './components/DefaultGroup'; import DemoDefaultNode from './components/DemoDefaultNode'; import defaultLayoutFactory from './layouts/defaultLayoutFactory'; import withTopologySetup from './utils/withTopologySetup'; const GroupWithDecorator: React.FunctionComponent<{ element: Node } & WithDragNodeProps> = observer(props => { const trafficSourceRef = useSvgAnchor(AnchorEnd.source, 'traffic'); const b = props.element.getBounds(); return ( <DefaultGroup {...(props as any)}> <circle ref={trafficSourceRef} cx={b.x + b.width} cy={b.y} r="12.5" fill="lightblue" strokeWidth={1} stroke="#333333" /> </DefaultGroup> ); }); export const ComplexGroup = withTopologySetup(() => { useLayoutFactory(defaultLayoutFactory); useComponentFactory(defaultComponentFactory); useComponentFactory( React.useCallback<ComponentFactory>((kind, type) => { if (type === 'service') { return withDragNode()(GroupWithDecorator); } if (type === 'node') { return withDragNode()(DemoDefaultNode); } return undefined; }, []) ); useModel( React.useMemo( (): Model => ({ graph: { id: 'g1', type: 'graph', layout: 'Force' }, nodes: [ { id: 'gr1', type: 'group-hull', group: true, children: ['n1', 'n2', 's1'], style: { padding: 50 } }, { id: 's1', type: 'service', group: true, children: ['r1', 'r2'], shape: NodeShape.rect, style: { padding: 25 } }, { id: 's2', type: 'service', group: true, shape: NodeShape.rect, width: 100, height: 100, style: { padding: 25 } }, { id: 'n1', type: 'node', x: 100, y: 150, width: 100, height: 100 }, { id: 'n2', type: 'node', x: 450, y: 100, width: 100, height: 100 }, { id: 'r1', type: 'node', x: 250, y: 300, width: 100, height: 100 }, { id: 'r2', type: 'node', x: 370, y: 320, width: 100, height: 100 } ], edges: [ { id: 't1', type: 'traffic', source: 's1', target: 'r1' }, { id: 't2', type: 'traffic', source: 's1', target: 'r2' } ] }), [] ) ); return null; });
jelly/patternfly-react
packages/react-core/src/components/InputGroup/__tests__/InputGroupText.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import { InputGroupText, InputGroupTextVariant } from '../InputGroupText'; describe('InputGroupText', () => { test('renders', () => { render( <InputGroupText className="inpt-grp-text" variant={InputGroupTextVariant.plain} id="email-npt-grp"> @ </InputGroupText> ); expect(screen.getByText('@')).toBeInTheDocument(); }); });
jelly/patternfly-react
packages/react-topology/src/hooks/useLayoutFactory.tsx
import * as React from 'react'; import { LayoutFactory } from '../types'; import useVisualizationController from './useVisualizationController'; const useLayoutFactory = (factory: LayoutFactory): void => { const controller = useVisualizationController(); React.useEffect(() => { controller.registerLayoutFactory(factory); // TODO support unregister? }, [controller, factory]); }; export default useLayoutFactory;
jelly/patternfly-react
packages/react-integration/cypress/integration/card.spec.ts
<reponame>jelly/patternfly-react describe('Card Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/card-demo-nav-link'); }); it('Verify that selectable card can be selected and unselected with keyboard input', () => { cy.get('#selectableCard').focus(); cy.focused().should('have.class', 'pf-m-selectable'); cy.focused().should('not.have.class', 'pf-m-selected'); cy.focused().type('{enter}'); cy.focused().should('have.class', 'pf-m-selected'); cy.focused().type('{enter}'); cy.focused().should('not.have.class', 'pf-m-selected'); }); it('Verify that selectableRaised card can be selected and unselected with keyboard input', () => { cy.get('#selectableCardRaised').focus(); cy.focused().should('have.class', 'pf-m-selectable-raised'); cy.focused().should('not.have.class', 'pf-m-selected-raised'); cy.focused().type('{enter}'); cy.focused().should('have.class', 'pf-m-selected-raised'); cy.focused().type('{enter}'); cy.focused().should('not.have.class', 'pf-m-selected-raised'); }); it('Verify card is expandable', () => { cy.get('#expand-card').should('not.have.class', 'pf-m-expanded'); cy.get('#expand-card .pf-c-card__header').should('have.class', 'pf-m-toggle-right'); cy.get('.pf-c-card__header-toggle .pf-c-button').click(); cy.get('#expand-card').should('have.class', 'pf-m-expanded'); }); });
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TooltipDemo/TooltipDemo.tsx
import { Tooltip } from '@patternfly/react-core'; import React, { Component } from 'react'; export class TooltipDemo extends Component { tooltipRef: React.RefObject<HTMLButtonElement>; myTooltipProps = { content: <div>World</div>, children: <div id="tooltipTarget">Hello</div> }; constructor(props: any) { super(props); this.tooltipRef = React.createRef(); } componentDidMount() { window.scrollTo(0, 0); } render() { return ( <div> <Tooltip content={this.myTooltipProps.content}>{this.myTooltipProps.children}</Tooltip> <Tooltip content="test deprecated props" tippyProps={{ duration: 0, delay: 0 }} isAppLauncher> <button>Trigger</button> </Tooltip> <div> <button ref={this.tooltipRef} id="tooltip-ref"> Tooltip attached via react ref </button> <Tooltip content={<div>Tooltip attached via react ref</div>} reference={this.tooltipRef} /> </div> <div> <button id="tooltip-selector">Tooltip attached via selector ref</button> <Tooltip content={<div>Tooltip attached via selector ref</div>} reference={() => document.getElementById('tooltip-selector')} /> </div> </div> ); } }
jelly/patternfly-react
packages/react-table/src/components/TableComposable/OuterScrollContainer.tsx
<filename>packages/react-table/src/components/TableComposable/OuterScrollContainer.tsx import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Table/table-scrollable'; export interface OuterScrollContainerProps extends React.HTMLProps<HTMLDivElement> { /** Content rendered inside the outer scroll container */ children?: React.ReactNode; /** Additional classes added to the container */ className?: string; } export const OuterScrollContainer: React.FunctionComponent<OuterScrollContainerProps> = ({ children, className, ...props }: OuterScrollContainerProps) => ( <div className={css(className, styles.scrollOuterWrapper)} {...props}> {children} </div> ); OuterScrollContainer.displayName = 'OuterScrollContainer';
jelly/patternfly-react
packages/react-charts/src/components/ChartUtils/index.ts
<filename>packages/react-charts/src/components/ChartUtils/index.ts export * from './chart-container'; export * from './chart-domain'; export * from './chart-helpers'; export * from './chart-interactive-legend'; export * from './chart-label'; export * from './chart-legend'; export * from './chart-origin'; export * from './chart-padding'; export * from './chart-resize'; export * from './chart-theme'; export * from './chart-tooltip';
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/ConsolesDemo/ConsolesDemo.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import { AccessConsoles, SerialConsole, DesktopViewer, VncConsole } from '@patternfly/react-console'; import { debounce } from '@patternfly/react-core'; export const ConsolesDemo: React.FunctionComponent = () => { const [status, setStatus] = React.useState('disconnected'); const setConnected = React.useRef(debounce(() => setStatus('connected'), 3000)).current; const ref = React.createRef<any>(); return ( <div className="consoles-demo-area"> <AccessConsoles preselectedType="SerialConsole"> <SerialConsoleCustom type="SerialConsole" typeText="Serial Console pty2" /> <SerialConsole onConnect={() => { setStatus('loading'); setConnected(); }} status={status} onDisconnect={() => setStatus('disconnected')} onData={(data: string) => { ref.current.onDataReceived(data); }} ref={ref} /> <DesktopViewer spice={{ address: '127.0.0.1', port: '5900' }} vnc={{ address: '127.0.0.1', port: '5901' }} /> <VncConsole host="localhost" port="9090" encrypt shared /> </AccessConsoles> </div> ); }; ConsolesDemo.displayName = 'ConsolesDemo'; const SerialConsoleCustom: React.FunctionComponent<{ type: string; typeText: string }> = () => { const [status, setStatus] = React.useState('disconnected'); const setConnected = React.useRef(debounce(() => setStatus('connected'), 3000)).current; const ref2 = React.createRef<any>(); return ( <SerialConsole onConnect={() => { setStatus('loading'); setConnected(); }} onDisconnect={() => setStatus('disconnected')} onData={(data: string) => { ref2.current.onDataReceived(data); }} status={status} ref={ref2} /> ); };
jelly/patternfly-react
packages/react-topology/src/layouts/ColaGroupsLayout.ts
import * as webcola from 'webcola'; import * as d3 from 'd3'; import { action } from 'mobx'; import { Graph, Layout, Node } from '../types'; import { BaseLayout } from './BaseLayout'; import { LayoutLink } from './LayoutLink'; import { LayoutGroup } from './LayoutGroup'; import { LayoutNode } from './LayoutNode'; import { ColaGroupsNode } from './ColaGroupsNode'; import { ColaGroup } from './ColaGroup'; import { ColaLink } from './ColaLink'; import { ColaLayout } from './ColaLayout'; export interface ChildGroup { group: LayoutGroup; nodes: LayoutNode[]; edges: LayoutLink[]; groups: LayoutGroup[]; } class ColaGroupsLayout extends ColaLayout implements Layout { private layerNodes: LayoutNode[]; private layerGroupNodes: ChildGroup[]; private layerGroups: LayoutGroup[]; private layerEdges: LayoutLink[]; private layoutNodes: LayoutNode[]; private childLayouts: BaseLayout[]; protected initializeLayout(): void {} protected initializeColaGroupLayout(graph: Graph): void { this.d3Cola = webcola.d3adaptor(d3); this.d3Cola.handleDisconnected(true); this.d3Cola.avoidOverlaps(true); this.d3Cola.jaccardLinkLengths(40, 0.7); this.d3Cola.on('tick', () => { this.tickCount++; if (this.tickCount >= 1 || this.tickCount % this.options.simulationSpeed === 0) { action(() => this.nodes.forEach(d => d.update()))(); } if (this.colaOptions.maxTicks >= 0 && this.tickCount > this.colaOptions.maxTicks) { this.d3Cola.stop(); } }); this.d3Cola.on('end', () => { this.tickCount = 0; this.simulationRunning = false; action(() => { if (this.destroyed) { this.onEnd && this.onEnd(); return; } this.layoutNodes.forEach(d => { if (!this.simulationStopped) { d.update(); } d.setFixed(false); }); if (this.options.layoutOnDrag) { this.forceSimulation.useForceSimulation(this.nodes, this.edges, this.getFixedNodeDistance); } if (this.simulationStopped) { this.simulationStopped = false; if (this.restartOnEnd !== undefined) { this.startColaLayout(false, this.restartOnEnd); this.startLayout(graph, false, this.restartOnEnd, this.onEnd); delete this.restartOnEnd; } } else if (this.addingNodes) { // One round of simulation to adjust for new nodes this.forceSimulation.useForceSimulation(this.nodes, this.edges, this.getFixedNodeDistance); this.forceSimulation.restart(); } this.onEnd && this.onEnd(); })(); }); } protected createLayoutNode(node: Node, nodeDistance: number, index: number) { return new ColaGroupsNode(node, nodeDistance, index); } protected getAllLeaves(group: LayoutGroup): LayoutNode[] { const leaves = [...group.leaves]; group.groups?.forEach(subGroup => leaves.push(...this.getAllLeaves(subGroup))); return leaves; } protected getAllSubGroups(group: LayoutGroup): LayoutGroup[] { const groups = [...group.groups]; group.groups?.forEach(subGroup => groups.push(...this.getAllSubGroups(subGroup))); return groups; } protected isNodeInGroups(node: LayoutNode, groups: LayoutGroup[]): boolean { return !!groups.find(group => group.leaves.includes(node) || this.isNodeInGroups(node, group.groups)); } protected isNodeInChildGroups(node: LayoutNode, groups: ChildGroup[]): boolean { return !!groups.find(group => group.nodes.includes(node) || this.isNodeInGroups(node, group.groups)); } protected isSubGroup(group: ChildGroup, childGroups: ChildGroup[]): boolean { return !!childGroups.find(cg => cg.groups.includes(group.group)); } protected getNodeGroup(node: LayoutNode, childGroups: ChildGroup[]): ChildGroup | undefined { return childGroups.find(group => group.nodes.includes(node) || this.isNodeInGroups(node, group.groups)); } protected getGroupLayout( graph: Graph, group: LayoutGroup, nodes: LayoutNode[], edges: LayoutLink[], groups: LayoutGroup[] ): BaseLayout { const layout = new ColaGroupsLayout(graph, this.options); layout.setupLayout(graph, nodes, edges, groups); return layout; } protected setupLayout(graph: Graph, nodes: LayoutNode[], edges: LayoutLink[], groups: LayoutGroup[]): void { const constraints = this.getConstraints(nodes as ColaGroupsNode[], groups as ColaGroup[], edges); let childGroups = groups.reduce((acc, group) => { if ( !groups.find(g => group.element.getParent()?.getId() === g.element.getId()) && (group.groups.length || group.leaves.length) ) { const allLeaves = this.getAllLeaves(group); const groupEdges = edges.filter(edge => allLeaves.includes(edge.sourceNode) && allLeaves.includes(edge.target)); const groupGroups = this.getAllSubGroups(group); allLeaves.forEach((l, i) => { l.index = i; if (l.parent && !groupGroups.includes(l.parent)) { l.parent = undefined; } }); groupGroups.forEach((g, i) => { g.index = 2 * allLeaves.length + i; g.parent = undefined; }); acc.push({ group, nodes: allLeaves, edges: groupEdges, groups: groupGroups }); } return acc; }, [] as ChildGroup[]); const constrainedGroups = groups.filter(g => constraints.find(c => c.group === g.element.getId())); this.layerGroups = childGroups.filter(cg => constrainedGroups.includes(cg.group)).map(cg => cg.group); childGroups = childGroups.filter(cg => !this.layerGroups.includes(cg.group)); this.layerNodes = nodes.filter(node => !this.isNodeInChildGroups(node, childGroups)); this.layerGroupNodes = childGroups.filter(cg => !this.isSubGroup(cg, childGroups)); this.layerEdges = edges.reduce((acc, edge) => { const source = this.getNodeGroup(edge.sourceNode, childGroups); const target = this.getNodeGroup(edge.targetNode, childGroups); if (!source || !target || source !== target) { acc.push(edge); } return acc; }, [] as LayoutLink[]); this.childLayouts = childGroups.map(childGroup => this.getGroupLayout(graph, childGroup.group, childGroup.nodes, childGroup.edges, childGroup.groups) ); } private startChildLayout( graph: Graph, childLayout: BaseLayout, initialRun: boolean, addingNodes: boolean ): Promise<void> { return new Promise<void>(resolve => { childLayout.startLayout(graph, initialRun, addingNodes, () => { resolve(); }); }); } protected startColaLayout(initialRun: boolean, addingNodes: boolean): void { this.simulationRunning = true; this.tickCount = 0; this.addingNodes = addingNodes; const doStart = () => { this.initializeColaGroupLayout(this.graph); const { width, height } = this.graph.getBounds(); this.d3Cola.size([width, height]); this.layoutNodes = [...this.layerNodes]; this.layerGroupNodes.forEach(cg => { const layoutNode = this.createLayoutNode(cg.group.element, this.options.nodeDistance, cg.group.index); this.layoutNodes.push(layoutNode); this.layerEdges.forEach(edge => { if (cg.nodes.find(n => n.id === edge.sourceNode.id) || this.isNodeInGroups(edge.sourceNode, cg.groups)) { edge.sourceNode = layoutNode; } if (cg.nodes.find(n => n.id === edge.targetNode.id) || this.isNodeInGroups(edge.targetNode, cg.groups)) { edge.targetNode = layoutNode; } }); }); // Get any custom constraints const constraints = this.getConstraints( this.layoutNodes as ColaGroupsNode[], this.layerGroups as ColaGroup[], this.layerEdges ); this.d3Cola.constraints(constraints); this.d3Cola.nodes(this.layoutNodes); this.d3Cola.groups(this.layerGroups); this.d3Cola.links(this.layerEdges); this.d3Cola.alpha(0.2); this.d3Cola.start( addingNodes ? 0 : this.colaOptions.initialUnconstrainedIterations, addingNodes ? 0 : this.colaOptions.initialUserConstraintIterations, addingNodes ? 0 : this.colaOptions.initialAllConstraintsIterations, addingNodes ? 0 : this.colaOptions.gridSnapIterations, false, !addingNodes ); }; if (this.childLayouts?.length) { const runLayouts = (childLayouts: BaseLayout[]): Promise<void[]> => Promise.all( childLayouts.map(childLayout => this.startChildLayout(this.graph, childLayout, initialRun, addingNodes)) ); runLayouts(this.childLayouts) .then(() => { doStart(); }) .catch(() => {}); return; } doStart(); } } export { ColaGroupsLayout, ColaGroupsNode, ColaGroup, ColaLink };
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/SelectDemo/SelectViewMoreTypeaheadGroupedDemo.tsx
import React from 'react'; import { Select, SelectOption, SelectVariant, SelectGroup, StackItem, Title } from '@patternfly/react-core'; /* eslint-disable no-console */ interface TypeAheadOption { value?: string; disabled?: boolean; } /* eslint-disable no-console */ export interface SelectViewMoreTypeaheadGroupedDemoState { isOpen: boolean; selected: string[]; numOptions: number; isLoading: boolean; isCreatable: boolean; newOptions: boolean; options: TypeAheadOption[]; } export class SelectViewMoreTypeaheadGroupedDemo extends React.Component<SelectViewMoreTypeaheadGroupedDemoState> { static displayName = 'SelectViewMoreTypeaheadDemo'; state = { isOpen: false, selected: [] as string[], numOptions: 1, isLoading: false, isCreatable: false, newOptions: false, inputValuePersisted: false }; options = [ <SelectGroup label="Status" key="group1"> <SelectOption id={'option-grouped-1'} key={0} value="Running" /> <SelectOption id={'option-grouped-2'} key={1} value="Stopped" /> <SelectOption id={'option-grouped-3'} key={2} value="Down" /> <SelectOption id={'option-grouped-4'} key={3} value="Degraded" /> <SelectOption id={'option-grouped-5'} key={4} value="Needs Maintenance" /> </SelectGroup>, <SelectGroup label="Vendor Names" key="group2"> <SelectOption id={'option-grouped-6'} key={5} value="Dell" /> <SelectOption id={'option-grouped-7'} key={6} value="Samsung" isDisabled /> <SelectOption id={'option-grouped-8'} key={7} value="Hewlett-Packard" /> </SelectGroup> ]; onToggle = (isOpen: boolean) => { this.setState({ isOpen }); }; clearSelection = () => { this.setState({ selected: null, isOpen: false }); }; onSelect = (_event: React.MouseEvent | React.ChangeEvent, selection: string, isPlaceholder: boolean) => { if (isPlaceholder) { this.clearSelection(); } else { this.setState({ selected: selection, isOpen: false }); console.log('selected:', selection); } }; simulateNetworkCall = (callback: any) => { setTimeout(callback, 1200); }; onViewMoreClick = () => { // Set select loadingVariant to spinner then simulate network call before loading more options this.setState({ isLoading: true }); this.simulateNetworkCall(() => { const newLength = this.state.numOptions + 3 < this.options.length ? this.state.numOptions + 3 : this.options.length; this.setState({ numOptions: newLength, isLoading: false }); }); }; render() { const titleId = 'view-more-typeahead-select-id'; const { isOpen, selected, isLoading, numOptions } = this.state; return ( <StackItem isFilled={false}> <Title headingLevel="h2" size="2xl"> Typeahead Select </Title> <div> <span id={titleId} hidden> Select a state </span> <Select toggleId="view-more-typeahead-select" variant={SelectVariant.typeahead} aria-label="Select a state" onToggle={this.onToggle} onSelect={this.onSelect} onClear={this.clearSelection} selections={selected} isOpen={isOpen} aria-labelledby={titleId} placeholderText="Select a state" noResultsFoundText="Item not found" {...(!isLoading && numOptions < this.options.length && { loadingVariant: { text: 'View more', onClick: this.onViewMoreClick } })} {...(isLoading && { loadingVariant: 'spinner' })} > {this.options.slice(0, numOptions)} </Select> </div> </StackItem> ); } }
jelly/patternfly-react
packages/react-topology/src/components/nodes/labels/index.ts
export { default as LabelActionIcon } from './LabelActionIcon'; export { default as LabelBadge } from './LabelBadge'; export { default as LabelContextMenu } from './LabelContextMenu'; export { default as LabelIcon } from './LabelIcon'; export { default as NodeLabel } from './NodeLabel';
jelly/patternfly-react
packages/react-table/src/components/TableComposable/Tbody.tsx
import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Table/table'; export interface TbodyProps extends React.HTMLProps<HTMLTableSectionElement> { /** Content rendered inside the <tbody> row group */ children?: React.ReactNode; /** Additional classes added to the <tbody> element */ className?: string; /** Modifies the body to allow for expandable rows */ isExpanded?: boolean; /** Forwarded ref */ innerRef?: React.Ref<any>; /** Flag indicating the <tbody> contains oddly striped rows. */ isOddStriped?: boolean; /** Flag indicating the <tbody> contains evenly striped rows. */ isEvenStriped?: boolean; } const TbodyBase: React.FunctionComponent<TbodyProps> = ({ children, className, isExpanded, innerRef, isEvenStriped = false, isOddStriped = false, ...props }: TbodyProps) => ( <tbody role="rowgroup" className={css( className, isExpanded && styles.modifiers.expanded, isOddStriped && styles.modifiers.striped, isEvenStriped && styles.modifiers.stripedEven )} ref={innerRef} {...props} > {children} </tbody> ); export const Tbody = React.forwardRef((props: TbodyProps, ref: React.Ref<HTMLTableSectionElement>) => ( <TbodyBase {...props} innerRef={ref} /> )); Tbody.displayName = 'Tbody';
jelly/patternfly-react
packages/react-integration/cypress/integration/paginationbuttonvariant.spec.ts
describe('Pagination Button Variant Demo Test', () => { it('Navigate to Pagination section', () => { cy.visit('http://localhost:3000/pagination-button-variant-demo-nav-link'); }); it('should be disabled when flag is present on button variant', () => { cy.get('.pagination-options-menu-disabled') .find('.pf-c-options-menu__toggle-text') .then(toggleText => expect(toggleText).to.have.text('1 - 20 of 523 ')); cy.get('.pagination-options-menu-disabled') .find('button[data-action="first"]') .then(button => expect(button).to.be.disabled); cy.get('.pagination-options-menu-disabled') .find('button[data-action="previous"]') .then(button => expect(button).to.be.disabled); cy.get('.pagination-options-menu-disabled') .find('button[data-action="next"]') .then(button => expect(button).to.be.disabled); cy.get('.pagination-options-menu-disabled') .find('button[data-action="last"]') .then(button => expect(button).to.be.disabled); cy.get('.pagination-options-menu-disabled') .find('.pf-c-options-menu__toggle') .then(toggleButton => expect(toggleButton).to.be.disabled); }); it('should be sticky when flag is present on button variant', () => { cy.get('.pagination-options-menu-sticky').should('have.class', 'pf-m-sticky'); }); it('Verify initial state on button variant', () => { cy.get('.pf-c-pagination').should('have.length', 5); cy.get('.pagination-options-menu-bottom.pf-c-pagination.pf-m-bottom').should('exist'); cy.get('.pagination-options-menu-top') .find('.pf-c-options-menu__toggle-text') .then(toggleText => expect(toggleText).to.have.text('1 - 20 of 523 ')); cy.get('.pagination-options-menu-top') .find('button[data-action="first"]') .then(button => expect(button).to.be.disabled); cy.get('.pagination-options-menu-top') .find('button[data-action="previous"]') .then(button => expect(button).to.be.disabled); cy.get('.pagination-options-menu-top') .find('button[data-action="next"]') .then(button => expect(button).not.to.be.disabled); cy.get('.pagination-options-menu-top') .find('button[data-action="last"]') .then(button => expect(button).not.to.be.disabled); cy.get('.pagination-options-menu-top') .find('.pf-c-pagination__nav-page-select input') .then(input => expect(input).to.have.value('1')); cy.get('.pagination-options-menu-top') .find('.pf-c-pagination__nav-page-select') .then(navPageSelect => expect(navPageSelect).to.have.text('of 27')); }); it('Verify event handlers fire correctly on button variant', () => { cy.get('.pagination-options-menu-top') .find('button.pf-c-options-menu__toggle') .then((toggleButton: JQuery<HTMLButtonElement>) => { cy.wrap(toggleButton).click(); cy.get('.pf-c-options-menu.pf-m-expanded').should('exist'); cy.get('button[data-action="per-page-10"]').then((firstMenuItem: JQuery<HTMLButtonElement>) => { cy.wrap(firstMenuItem).click(); cy.get('.pf-c-options-menu.pf-m-expanded').should('not.exist'); cy.get('.pagination-options-menu-top') .find('.pf-c-options-menu__toggle-text') .then(toggleText => expect(toggleText).to.have.text('1 - 10 of 523 ')); cy.get('.pagination-options-menu-top') .find('.pf-c-pagination__nav-page-select') .then(navPageSelect => expect(navPageSelect).to.have.text('of 53')); cy.get('.pagination-options-menu-bottom') .find('.pf-c-options-menu__toggle-text') .then(toggleText => expect(toggleText).to.have.text('1 - 10 of 523 ')); cy.get('.pagination-options-menu-bottom') .find('.pf-c-pagination__nav-page-select') .then(navPageSelect => expect(navPageSelect).to.have.text('of 53')); }); }); cy.get('.pagination-options-menu-top') .find('button[data-action="next"]') .then((button: JQuery<HTMLButtonElement>) => { cy.wrap(button).click(); cy.get('.pagination-options-menu-top') .find('button[data-action="first"]') .then(firstButton => expect(firstButton).not.to.be.disabled); cy.get('.pagination-options-menu-top') .find('button[data-action="previous"]') .then(previousButton => expect(previousButton).not.to.be.disabled); cy.get('.pagination-options-menu-top') .find('.pf-c-options-menu__toggle-text') .then(toggleText => expect(toggleText).to.have.text('11 - 20 of 523 ')); cy.get('.pagination-options-menu-top') .find('.pf-c-pagination__nav-page-select input') .then(input => expect(input).to.have.value('2')); }); cy.get('.pagination-options-menu-bottom') .find('button[data-action="next"]') .then((button: JQuery<HTMLButtonElement>) => { cy.wrap(button).click(); cy.get('.pagination-options-menu-bottom') .find('button[data-action="first"]') .then(firstButton => expect(firstButton).not.to.be.disabled); cy.get('.pagination-options-menu-bottom') .find('button[data-action="previous"]') .then(previousButton => expect(previousButton).not.to.be.disabled); cy.get('.pagination-options-menu-bottom') .find('.pf-c-options-menu__toggle-text') .then(toggleText => expect(toggleText).to.have.text('11 - 20 of 523 ')); cy.get('.pagination-options-menu-bottom') .find('.pf-c-pagination__nav-page-select input') .then(input => expect(input).to.have.value('2')); }); cy.get('.pagination-options-menu-default-fullpage') .find('button[data-action="next"]') .then((button: JQuery<HTMLButtonElement>) => { cy.wrap(button).click(); cy.get('.pagination-options-menu-default-fullpage') .find('button[data-action="first"]') .then(firstButton => expect(firstButton).not.to.be.disabled); cy.get('.pagination-options-menu-default-fullpage') .find('button[data-action="previous"]') .then(previousButton => expect(previousButton).not.to.be.disabled); cy.get('.pagination-options-menu-default-fullpage') .find('.pf-c-options-menu__toggle-text') .then(toggleText => expect(toggleText).to.have.text('11 - 20 of 523 ')); cy.get('.pagination-options-menu-default-fullpage') .find('.pf-c-pagination__nav-page-select input') .then(input => expect(input).to.have.value('2')); }); }); it('Verify defaultToFullPage works correctly on button variant', () => { cy.get('.pagination-options-menu-default-fullpage') .find('button[data-action="last"]') .then((button: JQuery<HTMLButtonElement>) => { cy.wrap(button).click(); cy.get('.pagination-options-menu-default-fullpage') .find('button.pf-c-options-menu__toggle') .then((toggleButton: JQuery<HTMLButtonElement>) => { cy.wrap(toggleButton).click(); cy.get('.pf-c-options-menu.pf-m-expanded').should('exist'); cy.get('button[data-action="per-page-100"]').then((lastMenuItem: JQuery<HTMLButtonElement>) => { cy.wrap(lastMenuItem).click(); cy.get('.pf-c-options-menu.pf-m-expanded').should('not.exist'); cy.get('.pagination-options-menu-default-fullpage') .find('.pf-c-options-menu__toggle-text') .then(toggleText => expect(toggleText).to.have.text('401 - 500 of 523 ')); cy.get('.pagination-options-menu-default-fullpage') .find('.pf-c-form-control') .then(currentPage => expect(currentPage).to.have.value('5')); }); }); }); }); });
jelly/patternfly-react
packages/react-integration/cypress/integration/descriptionlist.spec.ts
<filename>packages/react-integration/cypress/integration/descriptionlist.spec.ts describe('Description List Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/description-list-demo-nav-link'); }); it('Verify list with help text', () => { cy.get('#description-list-help-text') .should('exist') .children('.pf-c-description-list__group'); cy.get('.pf-c-popover__content').should('not.exist'); cy.get( '#description-list-help-text > :nth-child(1) > .pf-c-description-list__term > .pf-c-description-list__text' ).click(); cy.get('.pf-c-popover__content').should('exist'); }); });
jelly/patternfly-react
packages/react-core/src/components/OverflowMenu/__tests__/OverflowMenuControl.test.tsx
<gh_stars>0 import * as React from 'react'; import { render, screen } from '@testing-library/react'; import styles from '@patternfly/react-styles/css/components/OverflowMenu/overflow-menu'; import { OverflowMenuControl } from '../OverflowMenuControl'; import { OverflowMenuContext } from '../OverflowMenuContext'; describe('OverflowMenuControl', () => { test('basic', () => { render( <OverflowMenuContext.Provider value={{ isBelowBreakpoint: true }}> <OverflowMenuControl data-testid="test-id" /> </OverflowMenuContext.Provider> ); expect(screen.getByTestId('test-id')).toHaveClass(styles.overflowMenuControl); }); test('Additional Options', () => { const { asFragment } = render(<OverflowMenuControl hasAdditionalOptions />); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-integration/cypress/integration/codeeditor.spec.ts
<gh_stars>100-1000 describe('Context Selector Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/code-editor-demo-nav-link'); }); it('Verify code editor contents controlled', () => { cy.get('.view-lines') .first() .then(code => expect(code).to.have.text('test')); cy.get('#reset-code').click(); cy.wait(1000); cy.get('.view-lines') .first() .then(code => expect(code).to.have.text('resetcode')); }); });
jelly/patternfly-react
packages/react-core/src/components/BackgroundImage/examples/BackgroundImageBasic.tsx
import React from 'react'; import { BackgroundImage } from '@patternfly/react-core'; /** * Note: When using background-filter.svg, you must also include #image_overlay as the fragment identifier */ const images = { xs: '/assets/images/pfbg_576.jpg', xs2x: '/assets/images/pfbg_576@2x.jpg', sm: '/assets/images/pfbg_768.jpg', sm2x: '/assets/images/pfbg_768@2x.jpg', lg: '/assets/images/pfbg_1200.jpg' }; export const BackgroundImageBasic: React.FunctionComponent = () => <BackgroundImage src={images} />;
jelly/patternfly-react
packages/testSetup.ts
// Add custom jest matchers from jest-dom import '@testing-library/jest-dom';
jelly/patternfly-react
packages/react-integration/cypress/integration/accordion.spec.ts
<gh_stars>100-1000 describe('Accordion Demo Test', () => { it('Navigate to Accordion section', () => { cy.visit('http://localhost:3000/accordion-demo-nav-link'); }); it('Verify toggle open behavior', () => { cy.get('#item-1').click(); cy.get('#item-1').should('have.attr', 'aria-expanded', 'true'); cy.get('#item-2').should('have.attr', 'aria-expanded', 'false'); cy.get('#item-3').should('have.attr', 'aria-expanded', 'false'); const expandedContent = cy.get('#accordion-example .pf-c-accordion__expanded-content.pf-m-expanded'); expandedContent.should('have.length', 1); expandedContent.should('have.attr', 'id', 'item-1-content'); }); it('Verify toggle switch behavior', () => { cy.get('#item-2').click(); cy.get('#item-1').should('have.attr', 'aria-expanded', 'false'); cy.get('#item-2').should('have.attr', 'aria-expanded', 'true'); cy.get('#item-3').should('have.attr', 'aria-expanded', 'false'); const expandedContent = cy.get('#accordion-example .pf-c-accordion__expanded-content.pf-m-expanded'); expandedContent.should('have.length', 1); expandedContent.should('have.attr', 'id', 'item-2-content'); }); it('Verify toggle close behavior', () => { cy.get('#item-2').click(); cy.get('#item-1').should('have.attr', 'aria-expanded', 'false'); cy.get('#item-2').should('have.attr', 'aria-expanded', 'false'); cy.get('#item-3').should('have.attr', 'aria-expanded', 'false'); const expandedContent = cy.get('#accordion-example .pf-c-accordion__expanded-content.pf-m-expanded'); expandedContent.should('not.exist'); }); });
jelly/patternfly-react
packages/react-core/src/components/Card/examples/CardExpandable.tsx
import React from 'react'; import { Card, CardHeader, CardActions, CardTitle, CardBody, CardFooter, CardExpandableContent, Checkbox, Dropdown, DropdownItem, DropdownSeparator, KebabToggle } from '@patternfly/react-core'; export const CardExpandable: React.FunctionComponent = () => { const [isOpen, setIsOpen] = React.useState<boolean>(false); const [isChecked, setIsChecked] = React.useState<boolean>(false); const [isExpanded, setIsExpanded] = React.useState<boolean>(false); const [isToggleRightAligned, setIsToggleRightAligned] = React.useState<boolean>(false); const onSelect = () => { setIsOpen(!isOpen); }; const onClick = (checked: boolean) => { setIsChecked(checked); }; const onExpand = (event: React.MouseEvent, id: string) => { // eslint-disable-next-line no-console console.log(id); setIsExpanded(!isExpanded); }; const onRightAlign = () => { setIsToggleRightAligned(!isToggleRightAligned); }; 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 ( <React.Fragment> <div style={{ marginBottom: '12px' }}> <Checkbox id={'isToggleRightAligned-1'} key={'isToggleRightAligned'} label={'isToggleRightAligned'} isChecked={isToggleRightAligned} onChange={onRightAlign} /> </div> <Card id="expandable-card" isExpanded={isExpanded}> <CardHeader onExpand={onExpand} isToggleRightAligned={isToggleRightAligned} toggleButtonProps={{ id: 'toggle-button1', 'aria-label': 'Details', 'aria-labelledby': 'expandable-card-title toggle-button1', 'aria-expanded': isExpanded }} > <CardActions> <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-4" name="check4" /> </CardActions> <CardTitle id="expandable-card-title">Header</CardTitle> </CardHeader> <CardExpandableContent> <CardBody>Body</CardBody> <CardFooter>Footer</CardFooter> </CardExpandableContent> </Card> </React.Fragment> ); };
jelly/patternfly-react
packages/react-core/src/components/EmptyState/__tests__/EmptyState.test.tsx
<gh_stars>0 import React from 'react'; import { render, screen } from '@testing-library/react'; import AddressBookIcon from '@patternfly/react-icons/dist/esm/icons/address-book-icon'; import { EmptyState, EmptyStateVariant } from '../EmptyState'; import { EmptyStateBody } from '../EmptyStateBody'; import { EmptyStateSecondaryActions } from '../EmptyStateSecondaryActions'; import { EmptyStateIcon } from '../EmptyStateIcon'; import { EmptyStatePrimary } from '../EmptyStatePrimary'; import { Button } from '../../Button'; import { Title, TitleSizes } from '../../Title'; describe('EmptyState', () => { test('Main', () => { const { asFragment } = render( <EmptyState> <Title headingLevel="h5" size="lg"> HTTP Proxies </Title> <EmptyStateBody> Defining HTTP Proxies that exist on your network allows you to perform various actions through those proxies. </EmptyStateBody> <Button variant="primary">New HTTP Proxy</Button> <EmptyStateSecondaryActions> <Button variant="link" aria-label="learn more action"> Learn more about this in the documentation. </Button> </EmptyStateSecondaryActions> </EmptyState> ); expect(asFragment()).toMatchSnapshot(); }); test('Main variant large', () => { const { asFragment } = render( <EmptyState variant={EmptyStateVariant.large}> <Title headingLevel="h3" size={TitleSizes.md}> EmptyState large </Title> </EmptyState> ); expect(asFragment()).toMatchSnapshot(); }); test('Main variant small', () => { const { asFragment } = render( <EmptyState variant={EmptyStateVariant.small}> <Title headingLevel="h3" size={TitleSizes.md}> EmptyState small </Title> </EmptyState> ); expect(asFragment()).toMatchSnapshot(); }); test('Main variant xs', () => { const { asFragment } = render( <EmptyState variant={EmptyStateVariant.xs}> <Title headingLevel="h3" size={TitleSizes.md}> EmptyState small </Title> </EmptyState> ); expect(asFragment()).toMatchSnapshot(); }); test('Body', () => { render(<EmptyStateBody className="custom-empty-state-body" data-testid="body-test-id" />); expect(screen.getByTestId('body-test-id')).toHaveClass('custom-empty-state-body pf-c-empty-state__body'); }); test('Secondary Action', () => { render(<EmptyStateSecondaryActions className="custom-empty-state-secondary" data-testid="actions-test-id" />); expect(screen.getByTestId('actions-test-id')).toHaveClass( 'custom-empty-state-secondary pf-c-empty-state__secondary' ); }); test('Icon', () => { render(<EmptyStateIcon icon={AddressBookIcon} data-testid="icon-test-id" />); expect(screen.getByTestId('icon-test-id')).toHaveClass('pf-c-empty-state__icon'); }); test('Wrap icon in a div', () => { const { container } = render( <EmptyStateIcon variant="container" component={AddressBookIcon} className="custom-empty-state-icon" id="empty-state-icon-id" /> ); expect(container.querySelector('div')).toHaveClass('pf-c-empty-state__icon custom-empty-state-icon'); expect(container.querySelector('svg')).toBeInTheDocument(); }); test('Primary div', () => { render( <EmptyStatePrimary data-testid="primary-test-id"> <Button variant="link">Link</Button> </EmptyStatePrimary> ); expect(screen.getByTestId('primary-test-id')).toHaveClass('pf-c-empty-state__primary'); }); test('Full height', () => { const { asFragment } = render( <EmptyState isFullHeight variant={EmptyStateVariant.large}> <Title headingLevel="h3" size={TitleSizes.md}> EmptyState large </Title> </EmptyState> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/OverflowMenu/__tests__/OverflowMenuItem.test.tsx
import * as React from 'react'; import { render, screen } from '@testing-library/react'; import styles from '@patternfly/react-styles/css/components/OverflowMenu/overflow-menu'; import { OverflowMenuItem } from '../OverflowMenuItem'; import { OverflowMenuContext } from '../OverflowMenuContext'; describe('OverflowMenuItem', () => { test('isPersistent and below breakpoint should still show', () => { render( <OverflowMenuContext.Provider value={{ isBelowBreakpoint: false }}> <OverflowMenuItem isPersistent>Some item value</OverflowMenuItem> </OverflowMenuContext.Provider> ); expect(screen.getByText('Some item value')).toHaveClass(styles.overflowMenuItem); }); test('Below breakpoint and not isPersistent should not show', () => { const { asFragment } = render( <OverflowMenuContext.Provider value={{ isBelowBreakpoint: false }}> <OverflowMenuItem>Some item value</OverflowMenuItem> </OverflowMenuContext.Provider> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/FileUpload/__tests__/FileUpload.test.tsx
<reponame>jelly/patternfly-react<gh_stars>0 import { FileUpload } from '../FileUpload'; import * as React from 'react'; import { render } from '@testing-library/react'; test('simple fileupload', () => { const changeHandler = jest.fn(); const readStartedHandler = jest.fn(); const readFinishedHandler = jest.fn(); const { asFragment } = render( <FileUpload id="simple-text-file" type="text" value={''} filename={''} onChange={changeHandler} onReadStarted={readStartedHandler} onReadFinished={readFinishedHandler} isLoading={false} /> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-topology/src/components/nodes/shapes/index.ts
<reponame>jelly/patternfly-react<filename>packages/react-topology/src/components/nodes/shapes/index.ts export { default as Ellipse } from './Ellipse'; export { default as Hexagon } from './Hexagon'; export { default as Octagon } from './Octagon'; export { default as Rectangle } from './Rectangle'; export { default as Rhombus } from './Rhombus'; export { default as Stadium } from './Stadium'; export { default as Trapezoid } from './Trapezoid'; export { default as SidedShape } from './SidedShape'; export * from './shapeUtils';
jelly/patternfly-react
packages/react-core/src/components/TextInputGroup/examples/TextInputGroupDisabled.tsx
import React from 'react'; import { TextInputGroup, TextInputGroupMain } from '@patternfly/react-core'; export const TextInputGroupDisabled: React.FunctionComponent = () => ( <TextInputGroup isDisabled> <TextInputGroupMain value="Disabled" type="text" aria-label="Disabled text input group example input" /> </TextInputGroup> );
jelly/patternfly-react
packages/react-core/src/components/ChipGroup/__tests__/ChipGroup.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { ChipGroup } from '../index'; import { Chip } from '../../Chip'; describe('ChipGroup', () => { test('chip group default', () => { const { asFragment } = render( <ChipGroup> <Chip>1.1</Chip> </ChipGroup> ); expect(asFragment()).toMatchSnapshot(); }); test('chip group with category', () => { const { asFragment } = render( <ChipGroup categoryName="category"> <Chip>1.1</Chip> </ChipGroup> ); expect(asFragment()).toMatchSnapshot(); }); test('chip group with closable category', () => { const { asFragment } = render( <ChipGroup categoryName="category" isClosable> <Chip>1.1</Chip> </ChipGroup> ); expect(asFragment()).toMatchSnapshot(); }); test('chip group expanded', () => { render( <ChipGroup> <Chip>1</Chip> <Chip>2</Chip> <Chip>3</Chip> <Chip>4</Chip> </ChipGroup> ); const moreText = screen.getByText('1 more'); expect(moreText).toBeInTheDocument(); userEvent.click(moreText); expect(screen.getByText('Show Less')).toBeInTheDocument(); }); test('chip group will not render if no children passed', () => { render(<ChipGroup />); expect(screen.queryByRole('group')).toBeNull(); }); test('chip group with category and tooltip', () => { const { asFragment } = render( <ChipGroup categoryName="A very long category name"> <Chip>1.1</Chip> </ChipGroup> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/themes/light/multi-color-ordered-theme.ts
<filename>packages/react-charts/src/components/ChartTheme/themes/light/multi-color-ordered-theme.ts /* eslint-disable camelcase */ import chart_color_blue_100 from '@patternfly/react-tokens/dist/esm/chart_color_blue_100'; import chart_color_blue_200 from '@patternfly/react-tokens/dist/esm/chart_color_blue_200'; import chart_color_blue_300 from '@patternfly/react-tokens/dist/esm/chart_color_blue_300'; import chart_color_blue_400 from '@patternfly/react-tokens/dist/esm/chart_color_blue_400'; import chart_color_blue_500 from '@patternfly/react-tokens/dist/esm/chart_color_blue_500'; import chart_color_green_100 from '@patternfly/react-tokens/dist/esm/chart_color_green_100'; import chart_color_green_200 from '@patternfly/react-tokens/dist/esm/chart_color_green_200'; import chart_color_green_300 from '@patternfly/react-tokens/dist/esm/chart_color_green_300'; import chart_color_green_400 from '@patternfly/react-tokens/dist/esm/chart_color_green_400'; import chart_color_green_500 from '@patternfly/react-tokens/dist/esm/chart_color_green_500'; import chart_color_cyan_100 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_100'; import chart_color_cyan_200 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_200'; import chart_color_cyan_300 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_300'; import chart_color_cyan_400 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_400'; import chart_color_cyan_500 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_500'; import chart_color_gold_100 from '@patternfly/react-tokens/dist/esm/chart_color_gold_100'; import chart_color_gold_200 from '@patternfly/react-tokens/dist/esm/chart_color_gold_200'; import chart_color_gold_300 from '@patternfly/react-tokens/dist/esm/chart_color_gold_300'; import chart_color_gold_400 from '@patternfly/react-tokens/dist/esm/chart_color_gold_400'; import chart_color_gold_500 from '@patternfly/react-tokens/dist/esm/chart_color_gold_500'; import chart_color_orange_100 from '@patternfly/react-tokens/dist/esm/chart_color_orange_100'; import chart_color_orange_200 from '@patternfly/react-tokens/dist/esm/chart_color_orange_200'; import chart_color_orange_300 from '@patternfly/react-tokens/dist/esm/chart_color_orange_300'; import chart_color_orange_400 from '@patternfly/react-tokens/dist/esm/chart_color_orange_400'; import chart_color_orange_500 from '@patternfly/react-tokens/dist/esm/chart_color_orange_500'; import { ColorTheme } from '../color-theme'; // The color order below (minus the purple color family) improves the color contrast in ordered charts; donut, pie, bar, & stack // See https://docs.google.com/document/d/1cw10pJFXWruB1SA8TQwituxn5Ss6KpxYPCOYGrH8qAY/edit const COLOR_SCALE = [ chart_color_blue_300.value, chart_color_green_300.value, chart_color_cyan_300.value, chart_color_gold_300.value, chart_color_orange_300.value, chart_color_blue_100.value, chart_color_green_500.value, chart_color_cyan_100.value, chart_color_gold_100.value, chart_color_orange_500.value, chart_color_blue_500.value, chart_color_green_100.value, chart_color_cyan_500.value, chart_color_gold_500.value, chart_color_orange_100.value, chart_color_blue_200.value, chart_color_green_400.value, chart_color_cyan_200.value, chart_color_gold_200.value, chart_color_orange_400.value, chart_color_blue_400.value, chart_color_green_200.value, chart_color_cyan_400.value, chart_color_gold_400.value, chart_color_orange_200.value ]; export const LightMultiColorOrderedTheme = ColorTheme({ COLOR_SCALE });
jelly/patternfly-react
packages/react-log-viewer/src/LogViewer/LogViewerRow.tsx
import React, { memo, useContext } from 'react'; import ReactDOMServer from 'react-dom/server'; import { LOGGER_LINE_NUMBER_INDEX_DELTA } from './utils/constants'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/LogViewer/log-viewer'; import { LogViewerContext } from './LogViewerContext'; import AnsiUp from '../ansi_up/ansi_up'; import { escapeString, escapeTextForHtml, isAnsi, searchedKeyWordType, splitAnsi } from './utils/utils'; interface LogViewerRowProps { index: number; style?: React.CSSProperties; data: { parsedData: string[] | null; rowInFocus: searchedKeyWordType; searchedWordIndexes: searchedKeyWordType[]; }; } const ansiUp = new AnsiUp(); export const LogViewerRow: React.FunctionComponent<LogViewerRowProps> = memo(({ index, style, data }) => { const { parsedData, searchedWordIndexes, rowInFocus } = data; const context = useContext(LogViewerContext); const getData = (index: number): string => (parsedData ? parsedData[index] : null); const getRowIndex = (index: number): number => index + LOGGER_LINE_NUMBER_INDEX_DELTA; /** Helper function for applying the correct styling for styling rows containing searched keywords */ const handleHighlight = (matchCounter: number) => { const searchedWordResult = searchedWordIndexes.filter(searchedWord => searchedWord.rowIndex === index); if (searchedWordResult.length !== 0) { if (rowInFocus.rowIndex === index && rowInFocus.matchIndex === matchCounter) { return styles.modifiers.current; } return styles.modifiers.match; } return ''; }; const getFormattedData = () => { const rowText = getData(index); let matchCounter = 0; if (context.searchedInput) { const splitAnsiString = splitAnsi(rowText); const regEx = new RegExp(`(${escapeString(context.searchedInput)})`, 'ig'); const composedString: string[] = []; splitAnsiString.forEach(str => { matchCounter = 0; if (isAnsi(str)) { composedString.push(str); } else { const splitString = str.split(regEx); splitString.forEach((substr, newIndex) => { if (substr.match(regEx)) { matchCounter += 1; composedString.push( ReactDOMServer.renderToString( <span className={css(styles.logViewerString, handleHighlight(matchCounter))} key={newIndex}> {substr} </span> ) ); } else { composedString.push(escapeTextForHtml(substr)); } }); } }); return composedString.join(''); } return escapeTextForHtml(rowText); }; return ( <div style={style} className={css(styles.logViewerListItem)}> <span className={css(styles.logViewerIndex)}>{getRowIndex(index)}</span> <span className={css(styles.logViewerText)} style={{ width: 'fit-content' }} dangerouslySetInnerHTML={{ __html: ansiUp.ansi_to_html(getFormattedData()) }} /> </div> ); }); LogViewerRow.displayName = 'LogViewerRow';
jelly/patternfly-react
packages/react-topology/src/anchors/PolygonAnchor.ts
import { observable } from 'mobx'; import Point from '../geom/Point'; import { distanceToPoint, getLinesIntersection } from '../utils/anchor-utils'; import AbstractAnchor from './AbstractAnchor'; import { Rect } from '../geom'; import { PointTuple } from '../types'; export default class PolygonAnchor extends AbstractAnchor { @observable.ref private points?: Point[]; setPoints(points: PointTuple[]) { this.points = points?.map(p => new Point(p[0], p[1])); } getLocation(reference: Point): Point { let bestPoint: Point = new Point(0, 0); if (this.points) { const translatedRef = reference.clone(); this.owner.translateFromParent(translatedRef); let bestDistance = Infinity; const bbox = this.getBoundingBox(); for (let i = 0; i < this.points.length; i++) { const intersectPoint: Point | null = getLinesIntersection( [this.points[i], this.points[i === this.points.length - 1 ? 0 : i + 1]], [bbox.getCenter(), translatedRef] ); if (intersectPoint) { const intersectDistance: number = distanceToPoint(intersectPoint, translatedRef); if (intersectDistance < bestDistance) { bestPoint = intersectPoint; bestDistance = intersectDistance; } } } } this.owner.translateToParent(bestPoint); return bestPoint; } getBoundingBox(): Rect { if (this.points?.length) { const bbox: Rect = new Rect(this.points[0].x, this.points[0].y); for (let i = 1; i < this.points.length; i++) { bbox.union(new Rect(this.points[i].x, this.points[i].y)); } return bbox; } return new Rect(0, 0); } getReferencePoint(): Point { if (this.points?.length) { const bbox: Rect = this.getBoundingBox(); const ref = bbox.getCenter(); this.owner.translateToParent(ref); // touch the bounds to force a re-render in case this anchor is for a group this.owner.getBounds(); return ref; } return super.getReferencePoint(); } }
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/stylesComponentFactory.tsx
import * as React from 'react'; import { GraphElement, ComponentFactory, withContextMenu, ContextMenuSeparator, ContextMenuItem, withDragNode, withSelection, ModelKind, DragObjectWithType, Node, withPanZoom, GraphComponent, withCreateConnector, Graph, isNode, withDndDrop, Edge, withTargetDrag, withSourceDrag, nodeDragSourceSpec, nodeDropTargetSpec, groupDropTargetSpec, graphDropTargetSpec, NODE_DRAG_TYPE, CREATE_CONNECTOR_DROP_TYPE } from '@patternfly/react-topology'; import StyleNode from './StyleNode'; import StyleGroup from './StyleGroup'; import StyleEdge from './StyleEdge'; import CustomPathNode from './CustomPathNode'; import CustomPolygonNode from './CustomPolygonNode'; const CONNECTOR_SOURCE_DROP = 'connector-src-drop'; const CONNECTOR_TARGET_DROP = 'connector-target-drop'; interface EdgeProps { element: Edge; } const contextMenuItem = (label: string, i: number): React.ReactElement => { if (label === '-') { return <ContextMenuSeparator key={`separator:${i.toString()}`} />; } return ( // eslint-disable-next-line no-alert <ContextMenuItem key={label} onClick={() => alert(`Selected: ${label}`)}> {label} </ContextMenuItem> ); }; const createContextMenuItems = (...labels: string[]): React.ReactElement[] => labels.map(contextMenuItem); const defaultMenu = createContextMenuItems('First', 'Second', 'Third', '-', 'Fourth'); const stylesComponentFactory: ComponentFactory = ( kind: ModelKind, type: string ): React.ComponentType<{ element: GraphElement }> | undefined => { if (kind === ModelKind.graph) { return withDndDrop(graphDropTargetSpec([NODE_DRAG_TYPE]))(withPanZoom()(GraphComponent)); } switch (type) { case 'node': return withCreateConnector((source: Node, target: Node | Graph): void => { let targetId; const model = source.getController().toModel(); if (isNode(target)) { targetId = target.getId(); } else { return; } const id = `e${source.getGraph().getEdges().length + 1}`; if (!model.edges) { model.edges = []; } model.edges.push({ id, type: 'edge', source: source.getId(), target: targetId }); source.getController().fromModel(model); })( withDndDrop(nodeDropTargetSpec([CONNECTOR_SOURCE_DROP, CONNECTOR_TARGET_DROP, CREATE_CONNECTOR_DROP_TYPE]))( withContextMenu(() => defaultMenu)( withDragNode(nodeDragSourceSpec('node', true, true))(withSelection()(StyleNode)) ) ) ); case 'node-path': return CustomPathNode; case 'node-polygon': return CustomPolygonNode; case 'group': return withDndDrop(groupDropTargetSpec)( withContextMenu(() => defaultMenu)(withDragNode(nodeDragSourceSpec('group'))(withSelection()(StyleGroup))) ); case 'edge': return withSourceDrag<DragObjectWithType, Node, any, EdgeProps>({ item: { type: CONNECTOR_SOURCE_DROP }, begin: (monitor, props) => { props.element.raise(); return props.element; }, drag: (event, monitor, props) => { props.element.setStartPoint(event.x, event.y); }, end: (dropResult, monitor, props) => { if (monitor.didDrop() && dropResult && props) { props.element.setSource(dropResult); } props.element.setStartPoint(); } })( withTargetDrag<DragObjectWithType, Node, { dragging?: boolean }, EdgeProps>({ item: { type: CONNECTOR_TARGET_DROP }, begin: (monitor, props) => { props.element.raise(); return props.element; }, drag: (event, monitor, props) => { props.element.setEndPoint(event.x, event.y); }, end: (dropResult, monitor, props) => { if (monitor.didDrop() && dropResult && props) { props.element.setTarget(dropResult); } props.element.setEndPoint(); }, collect: monitor => ({ dragging: monitor.isDragging() }) })(withContextMenu(() => defaultMenu)(withSelection()(StyleEdge))) ); default: return undefined; } }; export default stylesComponentFactory;
jelly/patternfly-react
packages/react-integration/cypress/integration/inputgroup.spec.ts
describe('Input Group Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/input-group-demo-nav-link'); }); it('Verify text input', () => { cy.get('#textarea1').type('Hi'); cy.get('#textarea1').should('have.value', 'Hi'); }); it('Verify number input only allows numbers', () => { const text = cy.get('#textInput5'); text.type('Hi'); text.should('have.value', ''); text.type('13'); text.should('have.value', '13'); }); });
jelly/patternfly-react
packages/react-core/src/components/Hint/Hint.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Hint/hint'; import { css } from '@patternfly/react-styles'; export interface HintProps { /** Content rendered inside the hint. */ children?: React.ReactNode; /** Additional classes applied to the hint. */ className?: string; /** Actions of the hint. */ actions?: React.ReactNode; } export const Hint: React.FunctionComponent<HintProps> = ({ children, className, actions, ...props }: HintProps) => ( <div className={css(styles.hint, className)} {...props}> <div className={css(styles.hintActions)}>{actions}</div> {children} </div> ); Hint.displayName = 'Hint';
jelly/patternfly-react
packages/react-core/src/components/ActionList/examples/ActionListWithCancelButton.tsx
import React from 'react'; import { ActionList, ActionListGroup, ActionListItem, Button } from '@patternfly/react-core'; export const ActionListWithCancelButton: React.FunctionComponent = () => ( <React.Fragment> In modals, forms, data lists <ActionList> <ActionListItem> <Button variant="primary" id="save-button"> Save </Button> </ActionListItem> <ActionListItem> <Button variant="link" id="cancel-button"> Cancel </Button> </ActionListItem> </ActionList> <br /> In wizards <ActionList> <ActionListGroup> <ActionListItem> <Button variant="primary" id="next-button"> Next </Button> </ActionListItem> <ActionListItem> <Button variant="secondary" id="back-button"> Back </Button> </ActionListItem> </ActionListGroup> <ActionListGroup> <ActionListItem> <Button variant="link" id="cancel-button2"> Cancel </Button> </ActionListItem> </ActionListGroup> </ActionList> </React.Fragment> );
jelly/patternfly-react
packages/react-core/src/components/Select/__tests__/SelectOption.test.tsx
<filename>packages/react-core/src/components/Select/__tests__/SelectOption.test.tsx import React from 'react'; import { render, screen } from '@testing-library/react'; import { SelectOption, SelectOptionObject } from '../SelectOption'; import { SelectProvider } from '../selectConstants'; class User implements SelectOptionObject { private firstName: string; private lastName: string; private title: string; constructor(title: string, firstName: string, lastName: string) { this.title = title; this.firstName = firstName; this.lastName = lastName; } toString = (): string => `${this.title}: ${this.firstName} ${this.lastName}`; } describe('SelectOption', () => { test('renders with value parameter successfully', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption id="option-1" value="test" sendRef={jest.fn()} data-testid="test-id" /> </SelectProvider> ); expect(asFragment()).toMatchSnapshot(); }); test('renders with description successfully', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption id="option-1" value="test" description="This is a description" sendRef={jest.fn()} data-testid="test-id" /> </SelectProvider> ); expect(asFragment()).toMatchSnapshot(); }); test('renders with item count successfully', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption id="option-1" value="test" itemCount={3} sendRef={jest.fn()} data-testid="test-id" /> </SelectProvider> ); expect(asFragment()).toMatchSnapshot(); }); test('renders with custom display successfully', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption id="option-1" value="test" sendRef={jest.fn()}> <div>test display</div> </SelectOption> </SelectProvider> ); expect(asFragment()).toMatchSnapshot(); }); test('renders with custom user object successfully', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption id="option-1" value={new User('Mr.', 'Test', 'User')} sendRef={jest.fn()} data-testid="test-id" /> </SelectProvider> ); expect(asFragment()).toMatchSnapshot(); }); test('renders with custom display and custom user object successfully', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption id="option-1" value={new User('Mr.', 'Test', 'User')} sendRef={jest.fn()}> <div>test display</div> </SelectOption> </SelectProvider> ); expect(asFragment()).toMatchSnapshot(); }); test('renders custom component', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption id="option-1" value={new User('Mr.', 'Test', 'User')} sendRef={jest.fn()} component="div"> <div>test display</div> </SelectOption> </SelectProvider> ); expect(asFragment()).toMatchSnapshot(); }); describe('disabled', () => { test('renders disabled successfully', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption id="option-1" isDisabled value="test" sendRef={jest.fn()} data-testid="test-id" /> </SelectProvider> ); expect(screen.getByText('test')).toHaveClass('pf-m-disabled'); expect(asFragment()).toMatchSnapshot(); }); }); describe('is selected', () => { test('renders selected successfully', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption id="option-1" isSelected value="test" sendRef={jest.fn()} data-testid="test-id" /> </SelectProvider> ); expect(asFragment()).toMatchSnapshot(); }); }); describe('checked', () => { test('renders with checked successfully', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption id="option-1" isChecked value="test" sendRef={jest.fn()} data-testid="test-id" /> </SelectProvider> ); expect(asFragment()).toMatchSnapshot(); }); }); describe('favorites warning', () => { test('generates warning when id is undefined and isFavorites is set', () => { const myMock = jest.fn() as any; global.console = { error: myMock } as any; render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectOption isFavorite value="test" sendRef={jest.fn()} /> </SelectProvider> ); expect(myMock).toHaveBeenCalled(); }); }); });
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/utils/getVariation.ts
// @ts-nocheck import { Variation, Placement } from '../enums'; /** * @param placement */ export default function getVariation(placement: Placement): Variation | null | undefined { return placement.split('-')[1] as any; }
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/dom-utils/getDocumentRect.ts
// @ts-nocheck import { Rect } from '../types'; import getDocumentElement from './getDocumentElement'; import getComputedStyle from './getComputedStyle'; import getWindowScrollBarX from './getWindowScrollBarX'; import getWindowScroll from './getWindowScroll'; // Gets the entire size of the scrollable document area, even extending outside // of the `<html>` and `<body>` rect bounds if horizontally scrollable /** * @param element */ export default function getDocumentRect(element: HTMLElement): Rect { const html = getDocumentElement(element); const winScroll = getWindowScroll(element); const body = element.ownerDocument.body; const width = Math.max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); const height = Math.max( html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0 ); let x = -winScroll.scrollLeft + getWindowScrollBarX(element); const y = -winScroll.scrollTop; if (getComputedStyle(body || html).direction === 'rtl') { x += Math.max(html.clientWidth, body ? body.clientWidth : 0) - width; } return { width, height, x, y }; }
jelly/patternfly-react
packages/react-core/src/components/CalendarMonth/examples/CalendarMonthDateRange.tsx
import React from 'react'; import { CalendarMonth } from '@patternfly/react-core'; export const CalendarMonthDateRange: React.FunctionComponent = () => { const startDate = new Date(2020, 10, 11); const endDate = new Date(2020, 10, 24); const disablePreStartDates = (date: Date) => date >= startDate; return <CalendarMonth validators={[disablePreStartDates]} date={endDate} rangeStart={startDate} />; };
jelly/patternfly-react
packages/react-core/src/components/CodeBlock/examples/CodeBlockExpandable.tsx
<gh_stars>0 import React from 'react'; import { CodeBlock, CodeBlockAction, CodeBlockCode, ClipboardCopyButton, ExpandableSection, ExpandableSectionToggle, Button } from '@patternfly/react-core'; import PlayIcon from '@patternfly/react-icons/dist/esm/icons/play-icon'; export const ExpandableCodeBlock: React.FunctionComponent = () => { const [isExpanded, setIsExpanded] = React.useState(false); const [copied, setCopied] = React.useState(false); const onToggle = isExpanded => { setIsExpanded(isExpanded); }; 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 copyBlock = `apiVersion: helm.openshift.io/v1beta1/ kind: HelmChartRepository metadata: name: azure-sample-repo spec: connectionConfig: url: https://raw.githubusercontent.com/Azure-Samples/helm-charts/master/docs`; const code = `apiVersion: helm.openshift.io/v1beta1/ kind: HelmChartRepository metadata: name: azure-sample-repo`; const expandedCode = `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, copyBlock)} 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> {code} <ExpandableSection isExpanded={isExpanded} isDetached contentId="code-block-expand"> {expandedCode} </ExpandableSection> </CodeBlockCode> <ExpandableSectionToggle isExpanded={isExpanded} onToggle={onToggle} contentId="code-block-expand" direction="up"> {isExpanded ? 'Show Less' : 'Show More'} </ExpandableSectionToggle> </CodeBlock> ); };
jelly/patternfly-react
packages/react-core/src/components/CalendarMonth/examples/CalendarMonthSelectableDate.tsx
<filename>packages/react-core/src/components/CalendarMonth/examples/CalendarMonthSelectableDate.tsx import React from 'react'; import { CalendarMonth } from '@patternfly/react-core'; export const CalendarMonthSelectableDate: React.FunctionComponent = () => { const [date, setDate] = React.useState(new Date(2020, 10, 24)); return ( <React.Fragment> <pre>Selected date: {date.toString()}</pre> <CalendarMonth date={date} onChange={setDate} /> </React.Fragment> ); };