repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
jelly/patternfly-react | packages/react-core/src/components/TextInputGroup/__tests__/TextInputGroupUtilities.test.tsx | <gh_stars>0
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import { TextInputGroupUtilities } from '../TextInputGroupUtilities';
describe('TextInputGroupUtilities', () => {
it('renders without children', () => {
render(<TextInputGroupUtilities data-testid="TextInputGroupUtilities" />);
expect(screen.getByTestId('TextInputGroupUtilities')).toBeVisible();
});
it('renders the children', () => {
render(<TextInputGroupUtilities>{<button>Test</button>}</TextInputGroupUtilities>);
expect(screen.getByRole('button', { name: 'Test' })).toBeVisible();
});
it('renders with class pf-c-text-input-group__utilities', () => {
render(<TextInputGroupUtilities>Test</TextInputGroupUtilities>);
const utilities = screen.getByText('Test');
expect(utilities).toHaveClass('pf-c-text-input-group__utilities');
});
it('matches the snapshot', () => {
const { asFragment } = render(<TextInputGroupUtilities>{<button>Test</button>}</TextInputGroupUtilities>);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-console/src/components/SerialConsole/__tests__/SerialConsole.test.tsx | import React from 'react';
import { render } from '@testing-library/react';
import { SerialConsole } from '../SerialConsole';
import { constants } from '../../common/constants';
const { CONNECTED, DISCONNECTED, LOADING } = constants;
describe('SerialConsole', () => {
beforeAll(() => {
window.HTMLCanvasElement.prototype.getContext = () => ({ canvas: {} } as any);
});
test('in the LOADING state', () => {
const { asFragment } = render(
<SerialConsole
onData={jest.fn()}
onConnect={jest.fn()}
onDisconnect={jest.fn()}
status={LOADING}
textLoading="My text for Loading"
/>
);
expect(asFragment()).toMatchSnapshot();
});
test('in the DISCONNECTED state', () => {
const { asFragment } = render(
<SerialConsole
onData={jest.fn()}
onConnect={jest.fn()}
onDisconnect={jest.fn()}
status={DISCONNECTED}
textDisconnected="My text for Disconnected"
textConnect="My text for Connect"
/>
);
expect(asFragment()).toMatchSnapshot();
});
describe('with CONNECTED state', () => {
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('renders', () => {
const { asFragment } = render(
<SerialConsole
cols={33}
rows={44}
status={CONNECTED}
onData={jest.fn()}
onConnect={jest.fn()}
onDisconnect={jest.fn()}
textDisconnect="My text for Disconnect"
/>
);
expect(asFragment()).toMatchSnapshot();
});
});
});
|
jelly/patternfly-react | packages/react-charts/src/components/ChartTheme/themes/dark/blue-color-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 { ColorTheme } from '../color-theme';
// Color scale
// See https://docs.google.com/document/d/1cw10pJFXWruB1SA8TQwituxn5Ss6KpxYPCOYGrH8qAY/edit
const COLOR_SCALE = [
chart_color_blue_300.value,
chart_color_blue_100.value,
chart_color_blue_500.value,
chart_color_blue_200.value,
chart_color_blue_400.value
];
export const DarkBlueColorTheme = ColorTheme({
COLOR_SCALE
});
|
jelly/patternfly-react | packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyInlineCompact.tsx | <gh_stars>0
import React from 'react';
import { ClipboardCopy } from '@patternfly/react-core';
export const ClipboardCopyInlineCompact: React.FunctionComponent = () => (
<ClipboardCopy hoverTip="Copy" clickTip="Copied" variant="inline-compact">
2.3.4-2-redhat
</ClipboardCopy>
);
|
jelly/patternfly-react | packages/react-topology/src/components/nodes/shapes/Ellipse.tsx | <reponame>jelly/patternfly-react<filename>packages/react-topology/src/components/nodes/shapes/Ellipse.tsx
import { css } from '@patternfly/react-styles';
import styles from '@patternfly/react-styles/css/components/Topology/topology-components';
import * as React from 'react';
import { useAnchor } from '../../../behavior';
import { EllipseAnchor } from '../../../anchors';
import { ShapeProps } from './shapeUtils';
type EllipseProps = ShapeProps;
const Ellipse: React.FunctionComponent<EllipseProps> = ({
className = css(styles.topologyNodeBackground),
width,
height,
filter,
dndDropRef
}) => {
useAnchor(EllipseAnchor);
return (
<ellipse
className={className}
ref={dndDropRef}
cx={width / 2}
cy={height / 2}
rx={Math.max(0, width / 2 - 1)}
ry={Math.max(0, height / 2 - 1)}
filter={filter}
/>
);
};
export default Ellipse;
|
jelly/patternfly-react | packages/react-integration/demo-app-ts/src/components/demos/ExpandableSectionDemo/ExpandableSectionDemo.tsx | <gh_stars>0
import React from 'react';
import { ExpandableSection, ExpandableSectionToggle, Stack, StackItem } from '@patternfly/react-core';
interface ExpandableSectionState {
isExpanded: boolean;
isDetachedExpanded: boolean;
isDisclosureExpanded: boolean;
}
export class ExpandableSectionDemo extends React.Component<null, ExpandableSectionState> {
static displayName = 'ExpandableSectionDemo';
state = {
isExpanded: false,
isDetachedExpanded: false,
isDisclosureExpanded: false
};
componentDidMount() {
window.scrollTo(0, 0);
}
onToggle = (isOpen: boolean) => this.setState({ isExpanded: isOpen });
onToggleDetached = (isOpen: boolean) => this.setState({ isDetachedExpanded: isOpen });
onToggleDisclosure = (isOpen: boolean) => this.setState({ isDisclosureExpanded: isOpen });
render() {
const { isExpanded, isDetachedExpanded, isDisclosureExpanded } = this.state;
return (
<React.Fragment>
<h1> Simple Expandable Example: </h1>
<ExpandableSection
toggleText={isExpanded ? 'Show Less' : 'Show More'}
onToggle={this.onToggle}
isExpanded={isExpanded}
>
This content is visible only when the component is expanded.
</ExpandableSection>
<br />
<h1> Uncontrolled Expandable Example: </h1>
<ExpandableSection toggleText="Show More">
This content is visible only when the component is expanded.
</ExpandableSection>
<h1> Uncontrolled Dynamic Expandable Example: </h1>
<ExpandableSection toggleTextExpanded="Show Less" toggleTextCollapsed="Show More">
This content is visible only when the component is expanded.
</ExpandableSection>
<br />
<h1>Detached Expandable Section</h1>
<Stack hasGutter>
<StackItem>
<ExpandableSection
id="detached-section"
isExpanded={isDetachedExpanded}
isDetached
contentId="detached-section"
>
This content is visible only when the component is expanded.
</ExpandableSection>
</StackItem>
<StackItem>
<ExpandableSectionToggle
id="detached"
isExpanded={isDetachedExpanded}
onToggle={this.onToggleDetached}
contentId="detached-section"
direction="up"
>
{isExpanded ? 'Show Less' : 'Show More'}
</ExpandableSectionToggle>
</StackItem>
</Stack>
<br />
<h1> Disclosure Expandable Example: </h1>
<ExpandableSection
toggleText={isDisclosureExpanded ? 'Show Less' : 'Show More'}
onToggle={this.onToggleDisclosure}
isExpanded={isDisclosureExpanded}
id="disclosure-expandable-section"
displaySize="large"
isWidthLimited
>
This content is visible only when the component is expanded.
</ExpandableSection>
</React.Fragment>
);
}
}
|
jelly/patternfly-react | packages/react-core/src/components/Modal/__tests__/ModalBoxDescription.test.tsx | import * as React from 'react';
import { render } from '@testing-library/react';
import { ModalBoxDescription } from '../ModalBoxDescription';
test('ModalBoxDescription Test', () => {
const { asFragment } = render(<ModalBoxDescription>This is a ModalBox Description</ModalBoxDescription>);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-charts/src/components/ChartTheme/styles/scatter-styles.ts | <filename>packages/react-charts/src/components/ChartTheme/styles/scatter-styles.ts
/* eslint-disable camelcase */
import chart_scatter_active_size from '@patternfly/react-tokens/dist/esm/chart_scatter_active_size';
import chart_scatter_size from '@patternfly/react-tokens/dist/esm/chart_scatter_size';
// Donut styles
export const ScatterStyles = {
activeSize: chart_scatter_active_size.value,
size: chart_scatter_size.value
};
|
jelly/patternfly-react | packages/react-core/src/components/DataList/examples/DataListBasic.tsx | import React from 'react';
import { DataList, DataListItem, DataListItemRow, DataListItemCells, DataListCell } from '@patternfly/react-core';
export const DataListBasic: React.FunctionComponent = () => (
<DataList aria-label="Simple data list example">
<DataListItem aria-labelledby="simple-item1">
<DataListItemRow>
<DataListItemCells
dataListCells={[
<DataListCell key="primary content">
<span id="simple-item1">Primary content</span>
</DataListCell>,
<DataListCell key="secondary content">Secondary content</DataListCell>
]}
/>
</DataListItemRow>
</DataListItem>
<DataListItem aria-labelledby="simple-item2">
<DataListItemRow>
<DataListItemCells
dataListCells={[
<DataListCell isFilled={false} key="secondary content fill">
<span id="simple-item2">Secondary content (pf-m-no-fill)</span>
</DataListCell>,
<DataListCell isFilled={false} alignRight key="secondary content align">
Secondary content (pf-m-align-right pf-m-no-fill)
</DataListCell>
]}
/>
</DataListItemRow>
</DataListItem>
</DataList>
);
|
jelly/patternfly-react | packages/react-topology/src/components/groups/DefaultGroup.tsx | import * as React from 'react';
import { observer } from 'mobx-react';
import DefaultGroupExpanded from './DefaultGroupExpanded';
import { WithContextMenuProps, WithDndDropProps, WithSelectionProps, WithDragNodeProps } from '../../behavior';
import { BadgeLocation, LabelPosition, Node } from '../../types';
import DefaultGroupCollapsed from './DefaultGroupCollapsed';
import { CollapsibleGroupProps } from './types';
type DefaultGroupProps = {
className?: string;
element: Node;
droppable?: boolean;
canDrop?: boolean;
dropTarget?: boolean;
dragging?: boolean;
dragRegroupable?: boolean;
hover?: boolean;
label?: string; // Defaults to element.getLabel()
secondaryLabel?: string;
showLabel?: boolean; // Defaults to true
labelPosition?: LabelPosition; // Defaults to bottom
truncateLength?: number; // Defaults to 13
labelIconClass?: string; // Icon to show in label
labelIcon?: string;
labelIconPadding?: number;
badge?: string;
badgeColor?: string;
badgeTextColor?: string;
badgeBorderColor?: string;
badgeClassName?: string;
badgeLocation?: BadgeLocation;
} & Partial<CollapsibleGroupProps & WithSelectionProps & WithDndDropProps & WithDragNodeProps & WithContextMenuProps>;
const DefaultGroup: React.FunctionComponent<DefaultGroupProps> = ({
className,
element,
onCollapseChange,
...rest
}) => {
const handleCollapse = (group: Node, collapsed: boolean): void => {
if (collapsed && rest.collapsedWidth !== undefined && rest.collapsedHeight !== undefined) {
group.setBounds(group.getBounds().setSize(rest.collapsedWidth, rest.collapsedHeight));
}
group.setCollapsed(collapsed);
onCollapseChange && onCollapseChange(group, collapsed);
};
if (element.isCollapsed()) {
return (
<DefaultGroupCollapsed className={className} element={element} onCollapseChange={handleCollapse} {...rest} />
);
}
return <DefaultGroupExpanded className={className} element={element} onCollapseChange={handleCollapse} {...rest} />;
};
export default observer(DefaultGroup);
|
jelly/patternfly-react | packages/react-integration/demo-app-ts/src/components/demos/PageDemo/PageDemo.tsx | <filename>packages/react-integration/demo-app-ts/src/components/demos/PageDemo/PageDemo.tsx
import React from 'react';
import {
Avatar,
Button,
Dropdown,
Page,
PageHeader,
PageHeaderTools,
PageHeaderToolsGroup,
PageHeaderToolsItem,
PageSidebar,
PageSection,
PageSectionVariants,
SkipToContent,
KebabToggle,
DropdownToggle,
DropdownGroup,
DropdownItem
} from '@patternfly/react-core';
import CogIcon from '@patternfly/react-icons/dist/esm/icons/cog-icon';
import HelpIcon from '@patternfly/react-icons/dist/esm/icons/help-icon';
import QuestionCircleIcon from '@patternfly/react-icons/dist/esm/icons/question-circle-icon';
import imgAvatar from '@patternfly/react-integration/demo-app-ts/src/assets/images/imgAvatar.svg';
export class PageDemo extends React.Component {
static displayName = 'PageDemo';
state = {
isNavOpen: true,
isDropdownOpen: false,
isKebabDropdownOpen: false
};
onNavToggle = () => {
this.setState({
isNavOpen: !this.state.isNavOpen
});
};
onDropdownToggle = (isDropdownOpen: boolean) => {
this.setState({
isDropdownOpen
});
};
onDropdownSelect = (_event: any) => {
this.setState({
isDropdownOpen: !this.state.isDropdownOpen
});
};
onKebabDropdownToggle = (isKebabDropdownOpen: boolean) => {
this.setState({
isKebabDropdownOpen
});
};
onKebabDropdownSelect = (_event: any) => {
this.setState({
isKebabDropdownOpen: !this.state.isKebabDropdownOpen
});
};
componentDidMount() {
window.scrollTo(0, 0);
}
render() {
const { isNavOpen, isDropdownOpen, isKebabDropdownOpen } = this.state;
const headerRole: string | undefined = undefined;
const pageRole: string | undefined = undefined;
const logoProps = {
href: 'https://patternfly.org',
// eslint-disable-next-line no-console
onClick: () => console.log('clicked logo'),
target: '_blank'
};
const kebabDropdownItems = [
<DropdownItem key="group 1 settings">
<CogIcon /> Settings
</DropdownItem>,
<DropdownItem key="group 1 help">
<HelpIcon /> Help
</DropdownItem>
];
const userDropdownItems = [
<DropdownGroup key="group 2">
<DropdownItem key="group 2 profile">My profile</DropdownItem>
<DropdownItem key="group 2 user" component="button">
User management
</DropdownItem>
<DropdownItem key="group 2 logout">Logout</DropdownItem>
</DropdownGroup>
];
const headerTools = (
<PageHeaderTools>
<PageHeaderToolsGroup
visibility={{
default: 'hidden',
lg: 'visible'
}} /** the settings and help icon buttons are only visible on desktop sizes and replaced by a kebab dropdown for other sizes */
>
<PageHeaderToolsItem>
<Button aria-label="Settings actions" variant="plain">
<CogIcon />
</Button>
</PageHeaderToolsItem>
<PageHeaderToolsItem>
<Button aria-label="Help actions" variant="plain">
<QuestionCircleIcon />
</Button>
</PageHeaderToolsItem>
</PageHeaderToolsGroup>
<PageHeaderToolsGroup>
<PageHeaderToolsItem
visibility={{
lg: 'hidden'
}}
id="kebab-dropdown"
/** this kebab dropdown replaces the icon buttons and is hidden for desktop sizes */
>
<Dropdown
isPlain
position="right"
onSelect={this.onKebabDropdownSelect}
toggle={<KebabToggle onToggle={this.onKebabDropdownToggle} />}
isOpen={isKebabDropdownOpen}
dropdownItems={kebabDropdownItems}
/>
</PageHeaderToolsItem>
<PageHeaderToolsItem
id="user-dropdown"
visibility={{
default: 'hidden',
md: 'visible',
lg: 'visible',
xl: 'visible',
'2xl': 'visible'
}} /** this user dropdown is hidden on mobile sizes */
>
<Dropdown
isPlain
position="right"
onSelect={this.onDropdownSelect}
isOpen={isDropdownOpen}
toggle={<DropdownToggle onToggle={this.onDropdownToggle}><NAME></DropdownToggle>}
dropdownItems={userDropdownItems}
/>
</PageHeaderToolsItem>
</PageHeaderToolsGroup>
<Avatar src={imgAvatar} alt="Avatar image" />
</PageHeaderTools>
);
const Header = (
<PageHeader
role={headerRole}
id="page-demo-header"
logo="Logo that's a <div>"
logoProps={logoProps}
headerTools={headerTools}
showNavToggle
isNavOpen={isNavOpen}
onNavToggle={this.onNavToggle}
logoComponent={'div'}
/>
);
const pageId = 'page-demo-page-id';
const PageSkipToContent = <SkipToContent href={`#${pageId}`}>Skip to Content</SkipToContent>;
const Sidebar = <PageSidebar id="page-demo-sidebar" nav="Navigation" isNavOpen={isNavOpen} />;
return (
<Page
role={pageRole}
id="page-demo"
header={Header}
sidebar={Sidebar}
mainContainerId={pageId}
skipToContent={PageSkipToContent}
mainAriaLabel="page demo"
>
<PageSection variant={PageSectionVariants.darker}>Section with darker background</PageSection>
<PageSection variant={PageSectionVariants.dark}>Section with dark background</PageSection>
<PageSection variant={PageSectionVariants.light} isWidthLimited>
Section with light background
</PageSection>
<PageSection
padding={{
default: 'noPadding',
md: 'padding',
lg: 'padding'
}}
>
Section with padding only on medium/large
</PageSection>
<PageSection variant={PageSectionVariants.light} padding={{ md: 'noPadding' }}>
Section with no padding on medium
</PageSection>
</Page>
);
}
}
|
jelly/patternfly-react | packages/react-core/src/components/AboutModal/__tests__/AboutModalBoxHero.test.tsx | import * as React from 'react';
import { render } from '@testing-library/react';
import { AboutModalBoxHero } from '../AboutModalBoxHero';
test('test About Modal Box SHero', () => {
const { asFragment } = render(<AboutModalBoxHero />);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-integration/cypress/integration/duallistselectorwithactions.spec.ts | describe('Dual List Selector With Actions Demo Test', () => {
it('Navigate to demo section', () => {
cy.visit('http://localhost:3000/dual-list-selector-with-actions-demo-nav-link');
});
it('Verify existence', () => {
cy.get('#dual-list-selector-demo').should('exist');
});
it('Verify default value content', () => {
cy.get('.pf-c-dual-list-selector__list')
.first()
.should('have.value', '');
cy.get('.pf-c-dual-list-selector__list li').should('have.length', 4);
});
it('Verify custom aria-labels, status, and titles', () => {
cy.get('.pf-m-available .pf-c-dual-list-selector__title-text').contains('Demo available options');
cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('4 available');
cy.get('.pf-m-available .pf-c-dual-list-selector__tools-filter input').should(
'have.attr',
'aria-label',
'Demo available options search'
);
cy.get('.pf-m-available .pf-c-dual-list-selector__list').should(
'have.attr',
'aria-labelledby',
'dual-list-selector-demo-available-pane-status'
);
cy.get('.pf-c-dual-list-selector__controls-item button')
.eq(1)
.should('have.attr', 'aria-label', 'Demo add all');
cy.get('.pf-c-dual-list-selector__controls-item button')
.eq(0)
.should('have.attr', 'aria-label', 'Demo add selected')
.and('have.attr', 'disabled');
cy.get('.pf-c-dual-list-selector__controls-item button')
.eq(3)
.should('have.attr', 'aria-label', 'Demo remove selected')
.and('have.attr', 'disabled');
cy.get('.pf-c-dual-list-selector__controls-item button')
.eq(2)
.should('have.attr', 'aria-label', 'Demo remove all')
.and('have.attr', 'disabled');
cy.get('.pf-m-chosen .pf-c-dual-list-selector__title-text').contains('Demo chosen options');
cy.get('.pf-m-chosen .pf-c-dual-list-selector__status-text').contains('0 chosen');
cy.get('.pf-m-chosen .pf-c-dual-list-selector__tools-filter input').should(
'have.attr',
'aria-label',
'Demo chosen options search'
);
cy.get('.pf-m-chosen .pf-c-dual-list-selector__list').should(
'have.attr',
'aria-labelledby',
'dual-list-selector-demo-chosen-pane-status'
);
});
it('Verify selecting options', () => {
cy.get('.pf-c-dual-list-selector__list-item .pf-m-selected').should('not.exist');
cy.get('.pf-c-dual-list-selector__list-item')
.eq(0)
.click();
cy.get('.pf-c-dual-list-selector__list-item .pf-m-selected').should('exist');
cy.get('.pf-c-dual-list-selector__list-item')
.eq(1)
.click();
cy.get('.pf-c-dual-list-selector__list-item .pf-m-selected').should('have.length', 2);
cy.get('.pf-c-dual-list-selector__list-item')
.eq(0)
.click();
cy.get('.pf-c-dual-list-selector__list-item .pf-m-selected').should('have.length', 1);
});
it('Verify selecting and choosing options', () => {
cy.get('.pf-c-dual-list-selector__controls-item')
.eq(0)
.click();
cy.get('.pf-c-dual-list-selector__list')
.eq(0)
.find('li')
.should('have.length', 3);
cy.get('.pf-c-dual-list-selector__list')
.eq(1)
.find('li')
.should('have.length', 1);
cy.get('.pf-c-dual-list-selector__list-item')
.eq(1)
.click();
cy.get('.pf-c-dual-list-selector__controls-item')
.eq(0)
.click();
cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('2 available');
cy.get('.pf-m-chosen .pf-c-dual-list-selector__status-text').contains('2 chosen');
cy.get('.pf-c-dual-list-selector__list')
.eq(0)
.find('li')
.should('have.length', 2);
cy.get('.pf-c-dual-list-selector__list')
.eq(1)
.find('li')
.should('have.length', 2);
});
it('Verify removing all options', () => {
cy.get('.pf-c-dual-list-selector__controls-item')
.eq(2)
.click();
cy.get('.pf-c-dual-list-selector__list')
.eq(0)
.find('li')
.should('have.length', 4);
cy.get('.pf-c-dual-list-selector__list')
.eq(1)
.find('li')
.should('have.length', 0);
cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('4 available');
cy.get('.pf-m-chosen .pf-c-dual-list-selector__status-text').contains('0 chosen');
});
it('Verify choosing all options', () => {
cy.get('.pf-c-dual-list-selector__controls-item')
.eq(1)
.click();
cy.get('.pf-c-dual-list-selector__list')
.eq(0)
.find('li')
.should('have.length', 0);
cy.get('.pf-c-dual-list-selector__list')
.eq(1)
.find('li')
.should('have.length', 4);
cy.get('.pf-m-available .pf-c-dual-list-selector__status-text').contains('0 available');
cy.get('.pf-m-chosen .pf-c-dual-list-selector__status-text').contains('4 chosen');
});
it('Verify sort works', () => {
cy.get('.pf-m-chosen .pf-c-dual-list-selector__list-item')
.last()
.contains('Option 3');
cy.get('.pf-m-chosen .pf-c-dual-list-selector__tools-actions button')
.first()
.click();
cy.get('.pf-m-chosen .pf-c-dual-list-selector__list-item')
.last()
.contains('Option 4');
});
it('Verify chosen search works', () => {
cy.get('.pf-c-dual-list-selector__list')
.eq(1)
.find('li')
.should('have.length', 4);
cy.get('.pf-c-dual-list-selector__tools-filter .pf-m-search')
.eq(1)
.type('Option 1');
cy.get('.pf-c-dual-list-selector__list')
.eq(1)
.find('li')
.should('have.length', 1);
});
it('Verify removing all options', () => {
cy.get('.pf-c-dual-list-selector__tools-filter .pf-m-search')
.eq(1)
.type('{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}');
cy.get('.pf-c-dual-list-selector__controls-item')
.eq(2)
.click();
cy.get('.pf-c-dual-list-selector__list')
.eq(0)
.find('li')
.should('have.length', 4);
cy.get('.pf-c-dual-list-selector__list')
.eq(1)
.find('li')
.should('have.length', 0);
});
it('Verify available search works', () => {
cy.get('.pf-c-dual-list-selector__list')
.eq(0)
.find('li')
.should('have.length', 4);
cy.get('.pf-c-dual-list-selector__tools-filter .pf-m-search')
.eq(0)
.type('Option 3');
cy.get('.pf-c-dual-list-selector__list')
.eq(0)
.find('li')
.should('have.length', 1);
});
xit('Verify adding all filtered options', () => {
cy.get('.pf-c-dual-list-selector__list')
.eq(0)
.find('li')
.should('have.length', 1);
cy.get('.pf-c-dual-list-selector__controls-item')
.eq(1)
.click();
cy.get('.pf-c-dual-list-selector__list')
.eq(0)
.find('li')
.should('have.length', 0);
cy.get('.pf-c-dual-list-selector__list')
.eq(1)
.find('li')
.should('have.length', 1);
cy.get('.pf-c-dual-list-selector__tools-filter .pf-m-search')
.eq(0)
.type('{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}');
cy.get('.pf-c-dual-list-selector__list')
.eq(0)
.find('li')
.should('have.length', 3);
});
});
|
jelly/patternfly-react | packages/react-console/src/components/SpiceConsole/SpiceActions.tsx | import React from 'react';
import { Dropdown, DropdownItem, DropdownToggle } from '@patternfly/react-core';
export interface SpiceActionsProps extends React.HTMLProps<HTMLDivElement> {
/** Callback for when Ctrl+Alt+Delete item is selected */
onCtrlAltDel?: () => void;
/** Text for the Dropdown Ctrl+Alt+Delety item */
textCtrlAltDel?: string;
/** Text for the Dropdown toggle button */
textSendShortcut?: string;
}
export const SpiceActions: React.FunctionComponent<SpiceActionsProps> = ({
textSendShortcut = 'Send Key',
textCtrlAltDel = 'Ctrl+Alt+Del',
onCtrlAltDel
}: SpiceActionsProps) => {
const [isOpen, setIsOpen] = React.useState(false);
return (
<Dropdown
id="console-send-shortcut"
onSelect={() => {
setIsOpen(!isOpen);
onCtrlAltDel();
}}
isOpen={isOpen}
toggle={
<DropdownToggle onToggle={isDropdownOpen => setIsOpen(isDropdownOpen)}>{textSendShortcut}</DropdownToggle>
}
dropdownItems={[<DropdownItem key="ctrl-alt-delete">{textCtrlAltDel}</DropdownItem>]}
/>
);
};
SpiceActions.displayName = 'SpiceActions';
|
jelly/patternfly-react | packages/react-integration/cypress/integration/radio.spec.ts | describe('Radio Demo Test', () => {
it('Navigate to demo section', () => {
cy.visit('http://localhost:3000/radio-demo-nav-link');
});
it('Verify controlled radio', () => {
cy.get('#radio-2').should('be.checked');
cy.get('#radio-1').check();
cy.get('#radio-2').should('not.be.checked');
cy.get('#radio-1').should('be.checked');
});
it('Verify uncontrolled radio', () => {
cy.get('[for="radio-3"]').contains('Uncontrolled radio 1');
cy.get('[for="radio-4"]').contains('Uncontrolled radio 2');
});
it('Verify disabled radio', () => {
cy.get('#radio-5').should('be.checked');
cy.get('#radio-5').should('be.disabled');
cy.get('#radio-6').should('not.be.checked');
cy.get('#radio-6').should('be.disabled');
});
it('Verify body content', () => {
cy.get('#not-standalone-container').within(() => {
cy.get('.pf-c-radio__body').contains('this is the radio body');
});
});
it('Verify standalone radio input', () => {
cy.get('#standalone-container').within(() => {
cy.get('div.pf-c-radio.pf-m-standalone').should('exist');
});
cy.get('#not-standalone-container').within(() => {
cy.get('div.pf-c-radio.pf-m-standalone').should('not.exist');
});
});
});
|
jelly/patternfly-react | packages/react-catalog-view-extension/src/components/VerticalTabs/VerticalTabs.test.tsx | import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { VerticalTabs } from './VerticalTabs';
import { VerticalTabsTab } from './VerticalTabsTab';
test('Vertical Tabs renders tabs properly', () => {
const component = render(
<VerticalTabs id="vertical-tabs" className="test-vertical-tabs">
<VerticalTabsTab id="all" className="test-vertical-tabs-tab" title="All" />
<VerticalTabsTab id="one" title="Tab One">
<VerticalTabs>
<VerticalTabsTab key="one-one" id="one-one" title="Tab One-One">
<VerticalTabs activeTab>
<VerticalTabsTab key="one-one-one" id="one-one-one" title="Tab One-One-One" active />
<VerticalTabsTab key="one-one-two" id="one-one-two" title="Tab One-One-Two" active={false} />
<VerticalTabsTab key="one-one-three" id="one-one-three" title="Tab One-One-Three" />
</VerticalTabs>
</VerticalTabsTab>
<VerticalTabsTab key="one-two" id="one-two" title="Tab One-Two" />
<VerticalTabsTab key="one-three" id="one-three" title="Tab One-Three" />
</VerticalTabs>
</VerticalTabsTab>
<VerticalTabsTab id="two" title="Tab Two" className="test-tab-class">
<VerticalTabs>
<VerticalTabsTab key="one-one-one" id="two-one" title="Tab Two-One" />
<VerticalTabsTab key="one-one-two" id="two-two" title="Tab Two-Two" />
<VerticalTabsTab key="one-one-three" id="two-three" title="Tab Two-Three" />
</VerticalTabs>
</VerticalTabsTab>
<VerticalTabsTab id="three" title="Tab Three">
<VerticalTabs>
<VerticalTabsTab key="three-one" id="three-one" title="Tab Three-One" />
<VerticalTabsTab key="three-two" id="three-two" title="Tab Three-Two" />
</VerticalTabs>
</VerticalTabsTab>
<VerticalTabsTab id="four" title="Tab Four" />
<VerticalTabsTab id="five" title="Tab Five" />
<VerticalTabsTab id="six" title="Tab Six" />
<VerticalTabsTab id="seven" title="Tab Seven" />
</VerticalTabs>
);
expect(component.container).toMatchSnapshot();
});
test('Vertical Tabs renders restricted tabs properly', () => {
const component = render(
<VerticalTabs id="vertical-tabs" className="test-vertical-tabs" restrictTabs>
<VerticalTabsTab id="all" className="test-vertical-tabs-tab" title="All" shown />
<VerticalTabsTab id="one" title="Tab One" hasActiveDescendant>
<VerticalTabs restrictTabs>
<VerticalTabsTab key="one-one" id="one-one" title="Tab One-One">
<VerticalTabs restrictTabs activeTab>
<VerticalTabsTab key="one-one-one" id="one-one-one" title="Tab One-One-One" active />
<VerticalTabsTab key="one-one-two" id="one-one-two" title="Tab One-One-Two" active={false} />
<VerticalTabsTab key="one-one-three" id="one-one-three" title="Tab One-One-Three" />
</VerticalTabs>
</VerticalTabsTab>
<VerticalTabsTab key="one-two" id="one-two" title="Tab One-Two" />
<VerticalTabsTab key="one-three" id="one-three" title="Tab One-Three" />
</VerticalTabs>
</VerticalTabsTab>
<VerticalTabsTab id="two" title="Tab Two" className="test-tab-class">
<VerticalTabs restrictTabs activeTab>
<VerticalTabsTab key="one-one-one" id="two-one" title="Tab Two-One" active />
<VerticalTabsTab key="one-one-two" id="two-two" title="Tab Two-Two" active={false} />
<VerticalTabsTab key="one-one-three" id="two-three" title="Tab Two-Three" />
</VerticalTabs>
</VerticalTabsTab>
<VerticalTabsTab id="three" title="Tab Three">
<VerticalTabs restrictTabs>
<VerticalTabsTab key="three-one" id="three-one" title="Tab Three-One" />
<VerticalTabsTab key="three-two" id="three-two" title="Tab Three-Two" />
</VerticalTabs>
</VerticalTabsTab>
<VerticalTabsTab id="four" title="Tab Four" />
<VerticalTabsTab id="five" title="Tab Five" />
<VerticalTabsTab id="six" title="Tab Six" />
<VerticalTabsTab id="seven" title="Tab Seven" />
</VerticalTabs>
);
expect(component.container).toMatchSnapshot();
});
test('Vertical Tabs Tab onActivate is called correctly', () => {
const onActivateMock = jest.fn();
const component = render(<VerticalTabsTab id="text-click" title="Click Me" onActivate={onActivateMock} />);
userEvent.click(screen.getByText('Click Me'));
expect(component.container).toMatchSnapshot();
expect(onActivateMock).toHaveBeenCalled();
});
test('Vertical Tabs Tab wrap styling is set correctly', () => {
const component = render(
<div>
<VerticalTabsTab id="default-wrap" title="Default Wrap" />
<VerticalTabsTab id="word-wrap" title="Word Wrap" wrapStyle="wrap" />
<VerticalTabsTab id="truncate" title="Truncate" wrapStyle="truncate" />
<VerticalTabsTab id="no-wrap" title="No Wrap" wrapStyle="nowrap" />
</div>
);
expect(component.container).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-charts/src/components/ChartLine/index.ts | export * from './ChartLine';
|
jelly/patternfly-react | packages/react-core/src/components/DataList/examples/DataListSelectableRows.tsx | <gh_stars>0
import React from 'react';
import {
Dropdown,
DropdownItem,
DropdownPosition,
KebabToggle,
DataList,
DataListItem,
DataListCell,
DataListItemRow,
DataListItemCells,
DataListAction
} from '@patternfly/react-core';
export const DataListSelectableRows: React.FunctionComponent = () => {
const [isOpen1, setIsOpen1] = React.useState(false);
const [isOpen2, setIsOpen2] = React.useState(false);
const [selectedDataListItemId, setSelectedDataListItemId] = React.useState('');
const onToggle1 = isOpen1 => {
setIsOpen1(isOpen1);
};
const onSelect1 = () => {
setIsOpen1(!isOpen1);
};
const onToggle2 = isOpen2 => {
setIsOpen2(isOpen2);
};
const onSelect2 = () => {
setIsOpen2(!isOpen2);
};
const onSelectDataListItem = id => {
setSelectedDataListItemId(id);
};
return (
<React.Fragment>
<DataList
aria-label="selectable data list example"
selectedDataListItemId={selectedDataListItemId}
onSelectDataListItem={onSelectDataListItem}
>
<DataListItem aria-labelledby="selectable-action-item1" id="item1">
<DataListItemRow>
<DataListItemCells
dataListCells={[
<DataListCell key="primary content">
<span id="selectable-action-item1">Single actionable Primary content</span>
</DataListCell>,
<DataListCell key="secondary content">Single actionable Secondary content</DataListCell>
]}
/>
<DataListAction
aria-labelledby="selectable-action-item1 selectable-action-action1"
id="selectable-action-action1"
aria-label="Actions"
isPlainButtonAction
>
<Dropdown
isPlain
position={DropdownPosition.right}
isOpen={isOpen1}
onSelect={onSelect1}
toggle={<KebabToggle onToggle={onToggle1} />}
dropdownItems={[
<DropdownItem key="link">Link</DropdownItem>,
<DropdownItem key="action" component="button">
Action
</DropdownItem>,
<DropdownItem key="disabled link" isDisabled>
Disabled Link
</DropdownItem>
]}
/>
</DataListAction>
</DataListItemRow>
</DataListItem>
<DataListItem aria-labelledby="selectable-actions-item2" id="item2">
<DataListItemRow>
<DataListItemCells
dataListCells={[
<DataListCell key="primary content">
<span id="selectable-actions-item2">Selectable actions Primary content</span>
</DataListCell>,
<DataListCell key="secondary content">Selectable actions Secondary content</DataListCell>
]}
/>
<DataListAction
aria-labelledby="selectable-actions-item2 selectable-actions-action2"
id="selectable-actions-action2"
aria-label="Actions"
isPlainButtonAction
>
<Dropdown
isPlain
position={DropdownPosition.right}
isOpen={isOpen2}
onSelect={onSelect2}
toggle={<KebabToggle onToggle={onToggle2} />}
dropdownItems={[
<DropdownItem key="link">Link</DropdownItem>,
<DropdownItem key="action" component="button">
Action
</DropdownItem>,
<DropdownItem key="disabled link" isDisabled>
Disabled Link
</DropdownItem>
]}
/>
</DataListAction>
</DataListItemRow>
</DataListItem>
</DataList>
</React.Fragment>
);
};
|
jelly/patternfly-react | packages/react-core/src/components/MultipleFileUpload/__tests__/MultipleFileUploadInfo.test.tsx | <reponame>jelly/patternfly-react
import React from 'react';
import { render } from '@testing-library/react';
import { MultipleFileUploadInfo } from '../MultipleFileUploadInfo';
describe('MultipleFileUploadInfo', () => {
test('renders with expected class names', () => {
const { asFragment } = render(<MultipleFileUploadInfo>Foo</MultipleFileUploadInfo>);
expect(asFragment()).toMatchSnapshot();
});
test('renders custom class names', () => {
const { asFragment } = render(<MultipleFileUploadInfo className="test">Foo</MultipleFileUploadInfo>);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-core/src/demos/examples/MultipleFileUpload/MultipleFileUploadRejectedFile.tsx | <filename>packages/react-core/src/demos/examples/MultipleFileUpload/MultipleFileUploadRejectedFile.tsx<gh_stars>0
import React from 'react';
import {
MultipleFileUpload,
MultipleFileUploadMain,
MultipleFileUploadStatus,
MultipleFileUploadStatusItem,
Modal,
Checkbox
} from '@patternfly/react-core';
import UploadIcon from '@patternfly/react-icons/dist/esm/icons/upload-icon';
interface readFile {
fileName: string;
data?: string;
loadResult?: 'danger' | 'success';
loadError?: DOMException;
}
export const MultipleFileUploadBasic: React.FunctionComponent = () => {
const [isHorizontal, setIsHorizontal] = React.useState(false);
const [currentFiles, setCurrentFiles] = React.useState<File[]>([]);
const [readFileData, setReadFileData] = React.useState<readFile[]>([]);
const [showStatus, setShowStatus] = React.useState(false);
const [statusIcon, setStatusIcon] = React.useState('inProgress');
const [modalText, setModalText] = React.useState('');
// only show the status component once a file has been uploaded, but keep the status list component itself even if all files are removed
if (!showStatus && currentFiles.length > 0) {
setShowStatus(true);
}
// determine the icon that should be shown for the overall status list
React.useEffect(() => {
if (readFileData.length < currentFiles.length) {
setStatusIcon('inProgress');
} else if (readFileData.every(file => file.loadResult === 'success')) {
setStatusIcon('success');
} else {
setStatusIcon('danger');
}
}, [readFileData, currentFiles]);
// remove files from both state arrays based on their name
const removeFiles = (namesOfFilesToRemove: string[]) => {
const newCurrentFiles = currentFiles.filter(
currentFile => !namesOfFilesToRemove.some(fileName => fileName === currentFile.name)
);
setCurrentFiles(newCurrentFiles);
const newReadFiles = readFileData.filter(
readFile => !namesOfFilesToRemove.some(fileName => fileName === readFile.fileName)
);
setReadFileData(newReadFiles);
};
// callback that will be called by the react dropzone with the newly dropped file objects
const handleFileDrop = (droppedFiles: File[]) => {
// identify what, if any, files are re-uploads of already uploaded files
const currentFileNames = currentFiles.map(file => file.name);
const reUploads = droppedFiles.filter(droppedFile => currentFileNames.includes(droppedFile.name));
/** this promise chain is needed because if the file removal is done at the same time as the file adding react
* won't realize that the status items for the re-uploaded files needs to be re-rendered */
Promise.resolve()
.then(() => removeFiles(reUploads.map(file => file.name)))
.then(() => setCurrentFiles(prevFiles => [...prevFiles, ...droppedFiles]));
};
// callback called by the status item when a file is successfully read with the built-in file reader
const handleReadSuccess = (data: string, file: File) => {
setReadFileData(prevReadFiles => [...prevReadFiles, { data, fileName: file.name, loadResult: 'success' }]);
};
// callback called by the status item when a file encounters an error while being read with the built-in file reader
const handleReadFail = (error: DOMException, file: File) => {
setReadFileData(prevReadFiles => [
...prevReadFiles,
{ loadError: error, fileName: file.name, loadResult: 'danger' }
]);
};
// dropzone prop that communicates to the user that files they've attempted to upload are not an appropriate type
const handleDropRejected = (files: File[], _event: React.DragEvent<HTMLElement>) => {
if (files.length === 1) {
setModalText(`${files[0].name} is not an accepted file type`);
} else {
const rejectedMessages = files.reduce((acc, file) => (acc += `${file.name}, `), '');
setModalText(`${rejectedMessages}are not accepted file types`);
}
};
const successfullyReadFileCount = readFileData.filter(fileData => fileData.loadResult === 'success').length;
return (
<>
<MultipleFileUpload
onFileDrop={handleFileDrop}
dropzoneProps={{
accept: 'image/jpeg, application/msword, application/pdf, image/png',
onDropRejected: handleDropRejected
}}
isHorizontal={isHorizontal}
>
<MultipleFileUploadMain
titleIcon={<UploadIcon />}
titleText="Drag and drop files here"
titleTextSeparator="or"
infoText="Accepted file types: JPEG, Doc, PDF, PNG"
/>
{showStatus && (
<MultipleFileUploadStatus
statusToggleText={`${successfullyReadFileCount} of ${currentFiles.length} files uploaded`}
statusToggleIcon={statusIcon}
>
{currentFiles.map(file => (
<MultipleFileUploadStatusItem
file={file}
key={file.name}
onClearClick={() => removeFiles([file.name])}
onReadSuccess={handleReadSuccess}
onReadFail={handleReadFail}
/>
))}
</MultipleFileUploadStatus>
)}
<Modal
isOpen={!!modalText}
title="Unsupported file"
titleIconVariant="warning"
showClose
aria-label="unsupported file upload attempted"
onClose={() => setModalText('')}
>
{modalText}
</Modal>
</MultipleFileUpload>
<Checkbox
id="horizontal-checkbox"
label="Show as horizontal"
isChecked={isHorizontal}
onChange={() => setIsHorizontal(!isHorizontal)}
/>
</>
);
};
|
jelly/patternfly-react | packages/react-core/src/components/LoginPage/__tests__/LoginPage.test.tsx | <gh_stars>0
import * as React from 'react';
import { render } from '@testing-library/react';
import { LoginPage } from '../LoginPage';
import { ListVariant } from '../../List';
const needAccountMesseage = (
<React.Fragment>
Login to your account <a href="https://www.patternfly.org">Need an account?</a>
</React.Fragment>
);
test('check loginpage example against snapshot', () => {
const { asFragment } = render(
<LoginPage
footerListVariants={ListVariant.inline}
brandImgSrc="Brand src"
brandImgAlt="Pf-logo"
backgroundImgSrc="Background src"
backgroundImgAlt="Pf-background"
footerListItems="English"
textContent="This is placeholder text only."
loginTitle="Log into your account"
signUpForAccountMessage={needAccountMesseage}
socialMediaLoginContent="Footer"
/>
);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-integration/demo-app-ts/src/components/demos/ProgressStepperDemo/ProgressStepperDemo.tsx | import { ProgressStepper, ProgressStep, Popover } from '@patternfly/react-core';
import React, { Component } from 'react';
export class ProgressStepperDemo extends Component {
componentDidMount() {
window.scrollTo(0, 0);
}
render() {
return (
<ProgressStepper>
<ProgressStep
variant="success"
id="popover-step1"
titleId="popover-step1-title"
aria-label="completed step with popover, step with success"
popoverRender={(stepRef: React.RefObject<any>) => (
<Popover
aria-label="First step help"
headerContent={<div>First step popover</div>}
bodyContent={<div>Additional info or help text content.</div>}
reference={stepRef}
position="right"
/>
)}
>
First step
</ProgressStep>
<ProgressStep
variant="danger"
id="popover-step2"
titleId="popover-step2-title"
aria-label="completed step with popover, step with danger"
popoverRender={(stepRef: React.RefObject<any>) => (
<Popover
aria-label="Second step help"
headerContent={<div>Second step popover</div>}
bodyContent={<div>Additional info or help text content.</div>}
reference={stepRef}
position="right"
/>
)}
>
Second step
</ProgressStep>
<ProgressStep
variant="info"
id="popover-step3"
titleId="popover-step3-title"
aria-label="current step with popover"
popoverRender={(stepRef: React.RefObject<any>) => (
<Popover
aria-label="Third step help"
headerContent={<div>Third step popover</div>}
bodyContent={<div>Additional info or help text content.</div>}
reference={stepRef}
position="right"
/>
)}
isCurrent
>
Third step
</ProgressStep>
<ProgressStep variant="pending" id="popover-step4" titleId="popover-step4-title" aria-label="pending step">
Fourth step
</ProgressStep>
</ProgressStepper>
);
}
}
export default ProgressStepperDemo;
|
jelly/patternfly-react | packages/react-charts/src/components/ChartTheme/themes/base-theme.ts | <reponame>jelly/patternfly-react
/* eslint-disable camelcase */
import chart_global_FontFamily from '@patternfly/react-tokens/dist/esm/chart_global_FontFamily';
import chart_global_letter_spacing from '@patternfly/react-tokens/dist/esm/chart_global_letter_spacing';
import chart_global_FontSize_sm from '@patternfly/react-tokens/dist/esm/chart_global_FontSize_sm';
import chart_global_label_Padding from '@patternfly/react-tokens/dist/esm/chart_global_label_Padding';
import chart_global_label_stroke from '@patternfly/react-tokens/dist/esm/chart_global_label_stroke';
import chart_global_label_text_anchor from '@patternfly/react-tokens/dist/esm/chart_global_label_text_anchor';
import chart_global_layout_Padding from '@patternfly/react-tokens/dist/esm/chart_global_layout_Padding';
import chart_global_layout_Height from '@patternfly/react-tokens/dist/esm/chart_global_layout_Height';
import chart_global_layout_Width from '@patternfly/react-tokens/dist/esm/chart_global_layout_Width';
import chart_global_stroke_line_cap from '@patternfly/react-tokens/dist/esm/chart_global_stroke_line_cap';
import chart_global_stroke_line_join from '@patternfly/react-tokens/dist/esm/chart_global_stroke_line_join';
import chart_area_data_Fill from '@patternfly/react-tokens/dist/esm/chart_area_data_Fill';
import chart_area_Opacity from '@patternfly/react-tokens/dist/esm/chart_area_Opacity';
import chart_area_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_area_stroke_Width';
import chart_axis_axis_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_axis_axis_stroke_Width';
import chart_axis_axis_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_axis_axis_stroke_Color';
import chart_axis_axis_Fill from '@patternfly/react-tokens/dist/esm/chart_axis_axis_Fill';
import chart_axis_axis_label_Padding from '@patternfly/react-tokens/dist/esm/chart_axis_axis_label_Padding';
import chart_axis_axis_label_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_axis_axis_label_stroke_Color';
import chart_axis_grid_Fill from '@patternfly/react-tokens/dist/esm/chart_axis_grid_Fill';
import chart_axis_grid_PointerEvents from '@patternfly/react-tokens/dist/esm/chart_axis_grid_PointerEvents';
import chart_axis_tick_Fill from '@patternfly/react-tokens/dist/esm/chart_axis_tick_Fill';
import chart_axis_tick_Size from '@patternfly/react-tokens/dist/esm/chart_axis_tick_Size';
import chart_axis_tick_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_axis_tick_stroke_Color';
import chart_axis_tick_Width from '@patternfly/react-tokens/dist/esm/chart_axis_tick_Width';
import chart_axis_tick_label_Fill from '@patternfly/react-tokens/dist/esm/chart_axis_tick_label_Fill';
import chart_bar_Width from '@patternfly/react-tokens/dist/esm/chart_bar_Width';
import chart_bar_data_stroke from '@patternfly/react-tokens/dist/esm/chart_bar_data_stroke';
import chart_bar_data_Fill from '@patternfly/react-tokens/dist/esm/chart_bar_data_Fill';
import chart_bar_data_Padding from '@patternfly/react-tokens/dist/esm/chart_bar_data_Padding';
import chart_bar_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_bar_data_stroke_Width';
import chart_boxplot_max_Padding from '@patternfly/react-tokens/dist/esm/chart_boxplot_max_Padding';
import chart_boxplot_max_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_boxplot_max_stroke_Color';
import chart_boxplot_max_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_boxplot_max_stroke_Width';
import chart_boxplot_median_Padding from '@patternfly/react-tokens/dist/esm/chart_boxplot_median_Padding';
import chart_boxplot_median_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_boxplot_median_stroke_Color';
import chart_boxplot_median_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_boxplot_median_stroke_Width';
import chart_boxplot_min_Padding from '@patternfly/react-tokens/dist/esm/chart_boxplot_min_Padding';
import chart_boxplot_min_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_boxplot_min_stroke_Width';
import chart_boxplot_min_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_boxplot_min_stroke_Color';
import chart_boxplot_lower_quartile_Padding from '@patternfly/react-tokens/dist/esm/chart_boxplot_lower_quartile_Padding';
import chart_boxplot_lower_quartile_Fill from '@patternfly/react-tokens/dist/esm/chart_boxplot_lower_quartile_Fill';
import chart_boxplot_upper_quartile_Padding from '@patternfly/react-tokens/dist/esm/chart_boxplot_upper_quartile_Padding';
import chart_boxplot_upper_quartile_Fill from '@patternfly/react-tokens/dist/esm/chart_boxplot_upper_quartile_Fill';
import chart_boxplot_box_Width from '@patternfly/react-tokens/dist/esm/chart_boxplot_box_Width';
import chart_candelstick_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_candelstick_data_stroke_Width';
import chart_candelstick_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_candelstick_data_stroke_Color';
import chart_candelstick_candle_positive_Color from '@patternfly/react-tokens/dist/esm/chart_candelstick_candle_positive_Color';
import chart_candelstick_candle_negative_Color from '@patternfly/react-tokens/dist/esm/chart_candelstick_candle_negative_Color';
import chart_errorbar_BorderWidth from '@patternfly/react-tokens/dist/esm/chart_errorbar_BorderWidth';
import chart_errorbar_data_Fill from '@patternfly/react-tokens/dist/esm/chart_errorbar_data_Fill';
import chart_errorbar_data_Opacity from '@patternfly/react-tokens/dist/esm/chart_errorbar_data_Opacity';
import chart_errorbar_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_errorbar_data_stroke_Width';
import chart_errorbar_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_errorbar_data_stroke_Color';
import chart_legend_gutter_Width from '@patternfly/react-tokens/dist/esm/chart_legend_gutter_Width';
import chart_legend_orientation from '@patternfly/react-tokens/dist/esm/chart_legend_orientation';
import chart_legend_title_orientation from '@patternfly/react-tokens/dist/esm/chart_legend_title_orientation';
import chart_legend_data_type from '@patternfly/react-tokens/dist/esm/chart_legend_data_type';
import chart_legend_title_Padding from '@patternfly/react-tokens/dist/esm/chart_legend_title_Padding';
import chart_line_data_Fill from '@patternfly/react-tokens/dist/esm/chart_line_data_Fill';
import chart_line_data_Opacity from '@patternfly/react-tokens/dist/esm/chart_line_data_Opacity';
import chart_line_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_line_data_stroke_Width';
import chart_line_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_line_data_stroke_Color';
import chart_pie_Padding from '@patternfly/react-tokens/dist/esm/chart_pie_Padding';
import chart_pie_data_Padding from '@patternfly/react-tokens/dist/esm/chart_pie_data_Padding';
import chart_pie_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_pie_data_stroke_Width';
import chart_pie_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_pie_data_stroke_Color';
import chart_pie_labels_Padding from '@patternfly/react-tokens/dist/esm/chart_pie_labels_Padding';
import chart_pie_Height from '@patternfly/react-tokens/dist/esm/chart_pie_Height';
import chart_pie_Width from '@patternfly/react-tokens/dist/esm/chart_pie_Width';
import chart_scatter_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_scatter_data_stroke_Color';
import chart_scatter_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_scatter_data_stroke_Width';
import chart_scatter_data_Opacity from '@patternfly/react-tokens/dist/esm/chart_scatter_data_Opacity';
import chart_scatter_data_Fill from '@patternfly/react-tokens/dist/esm/chart_scatter_data_Fill';
import chart_stack_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_stack_data_stroke_Width';
import chart_tooltip_corner_radius from '@patternfly/react-tokens/dist/esm/chart_tooltip_corner_radius';
import chart_tooltip_pointer_length from '@patternfly/react-tokens/dist/esm/chart_tooltip_pointer_length';
import chart_tooltip_Fill from '@patternfly/react-tokens/dist/esm/chart_tooltip_Fill';
import chart_tooltip_flyoutStyle_corner_radius from '@patternfly/react-tokens/dist/esm/chart_tooltip_flyoutStyle_corner_radius';
import chart_tooltip_flyoutStyle_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_tooltip_flyoutStyle_stroke_Width';
import chart_tooltip_flyoutStyle_PointerEvents from '@patternfly/react-tokens/dist/esm/chart_tooltip_flyoutStyle_PointerEvents';
import chart_tooltip_flyoutStyle_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_tooltip_flyoutStyle_stroke_Color';
import chart_tooltip_flyoutStyle_Fill from '@patternfly/react-tokens/dist/esm/chart_tooltip_flyoutStyle_Fill';
import chart_tooltip_pointer_Width from '@patternfly/react-tokens/dist/esm/chart_tooltip_pointer_Width';
import chart_tooltip_Padding from '@patternfly/react-tokens/dist/esm/chart_tooltip_Padding';
import chart_tooltip_PointerEvents from '@patternfly/react-tokens/dist/esm/chart_tooltip_PointerEvents';
import chart_voronoi_data_Fill from '@patternfly/react-tokens/dist/esm/chart_voronoi_data_Fill';
import chart_voronoi_data_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_voronoi_data_stroke_Color';
import chart_voronoi_data_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_voronoi_data_stroke_Width';
import chart_voronoi_labels_Fill from '@patternfly/react-tokens/dist/esm/chart_voronoi_labels_Fill';
import chart_voronoi_labels_Padding from '@patternfly/react-tokens/dist/esm/chart_voronoi_labels_Padding';
import chart_voronoi_labels_PointerEvents from '@patternfly/react-tokens/dist/esm/chart_voronoi_labels_PointerEvents';
import chart_voronoi_flyout_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_voronoi_flyout_stroke_Width';
import chart_voronoi_flyout_PointerEvents from '@patternfly/react-tokens/dist/esm/chart_voronoi_flyout_PointerEvents';
import chart_voronoi_flyout_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_voronoi_flyout_stroke_Color';
import chart_voronoi_flyout_stroke_Fill from '@patternfly/react-tokens/dist/esm/chart_voronoi_flyout_stroke_Fill';
// Note: Values must be in pixles
// Typography
//
// Note: Victory's approximateTextSize function uses specific character widths and does not work with font variables
// See https://github.com/patternfly/patternfly-react/issues/5300
const TYPOGRAPHY_FONT_FAMILY = chart_global_FontFamily.value.replace(/ /g, '');
const TYPOGRAPHY_LETTER_SPACING = chart_global_letter_spacing.value;
const TYPOGRAPHY_FONT_SIZE = chart_global_FontSize_sm.value;
// Labels
const LABEL_PROPS = {
fontFamily: TYPOGRAPHY_FONT_FAMILY,
fontSize: TYPOGRAPHY_FONT_SIZE,
letterSpacing: TYPOGRAPHY_LETTER_SPACING,
padding: chart_global_label_Padding.value,
stroke: chart_global_label_stroke.value
};
const LABEL_CENTERED_PROPS = {
...LABEL_PROPS,
textAnchor: chart_global_label_text_anchor.value
};
// Layout
const LAYOUT_PROPS = {
padding: chart_global_layout_Padding.value,
height: chart_global_layout_Height.value,
width: chart_global_layout_Width.value
};
// Strokes
const STROKE_LINE_CAP = chart_global_stroke_line_cap.value;
const STROKE_LINE_JOIN = chart_global_stroke_line_join.value;
// Victory theme properties only
export const BaseTheme = {
area: {
...LAYOUT_PROPS,
style: {
data: {
fill: chart_area_data_Fill.value,
fillOpacity: chart_area_Opacity.value,
// Omit stroke to add a line border from color scale
// stroke: chart_global_label_stroke.value,
strokeWidth: chart_area_stroke_Width.value
},
labels: LABEL_CENTERED_PROPS
}
},
axis: {
...LAYOUT_PROPS,
style: {
axis: {
fill: chart_axis_axis_Fill.value,
strokeWidth: chart_axis_axis_stroke_Width.value,
stroke: chart_axis_axis_stroke_Color.value,
strokeLinecap: STROKE_LINE_CAP,
strokeLinejoin: STROKE_LINE_JOIN
},
axisLabel: {
...LABEL_CENTERED_PROPS,
padding: chart_axis_axis_label_Padding.value,
stroke: chart_axis_axis_label_stroke_Color.value
},
grid: {
fill: chart_axis_grid_Fill.value,
stroke: 'none',
pointerEvents: chart_axis_grid_PointerEvents.value,
strokeLinecap: STROKE_LINE_CAP,
strokeLinejoin: STROKE_LINE_JOIN
},
ticks: {
fill: chart_axis_tick_Fill.value,
size: chart_axis_tick_Size.value,
stroke: chart_axis_tick_stroke_Color.value,
strokeLinecap: STROKE_LINE_CAP,
strokeLinejoin: STROKE_LINE_JOIN,
strokeWidth: chart_axis_tick_Width.value
},
tickLabels: {
...LABEL_PROPS,
fill: chart_axis_tick_label_Fill.value
}
}
},
bar: {
...LAYOUT_PROPS,
barWidth: chart_bar_Width.value,
style: {
data: {
fill: chart_bar_data_Fill.value,
padding: chart_bar_data_Padding.value,
stroke: chart_bar_data_stroke.value,
strokeWidth: chart_bar_data_stroke_Width.value
},
labels: LABEL_PROPS
}
},
boxplot: {
...LAYOUT_PROPS,
style: {
max: {
padding: chart_boxplot_max_Padding.value,
stroke: chart_boxplot_max_stroke_Color.value,
strokeWidth: chart_boxplot_max_stroke_Width.value
},
maxLabels: LABEL_PROPS,
median: {
padding: chart_boxplot_median_Padding.value,
stroke: chart_boxplot_median_stroke_Color.value,
strokeWidth: chart_boxplot_median_stroke_Width.value
},
medianLabels: LABEL_PROPS,
min: {
padding: chart_boxplot_min_Padding.value,
stroke: chart_boxplot_min_stroke_Color.value,
strokeWidth: chart_boxplot_min_stroke_Width.value
},
minLabels: LABEL_PROPS,
q1: {
fill: chart_boxplot_lower_quartile_Fill.value,
padding: chart_boxplot_lower_quartile_Padding.value
},
q1Labels: LABEL_PROPS,
q3: {
fill: chart_boxplot_upper_quartile_Fill.value,
padding: chart_boxplot_upper_quartile_Padding.value
},
q3Labels: LABEL_PROPS
},
boxWidth: chart_boxplot_box_Width.value
},
candlestick: {
...LAYOUT_PROPS,
candleColors: {
positive: chart_candelstick_candle_positive_Color.value,
negative: chart_candelstick_candle_negative_Color.value
},
style: {
data: {
stroke: chart_candelstick_data_stroke_Color.value,
strokeWidth: chart_candelstick_data_stroke_Width.value
},
labels: LABEL_CENTERED_PROPS
}
},
chart: {
...LAYOUT_PROPS
},
errorbar: {
...LAYOUT_PROPS,
borderWidth: chart_errorbar_BorderWidth.value,
style: {
data: {
fill: chart_errorbar_data_Fill.value,
opacity: chart_errorbar_data_Opacity.value,
stroke: chart_errorbar_data_stroke_Color.value,
strokeWidth: chart_errorbar_data_stroke_Width.value
},
labels: LABEL_CENTERED_PROPS
}
},
group: {
...LAYOUT_PROPS
},
legend: {
gutter: chart_legend_gutter_Width.value,
orientation: chart_legend_orientation.value,
titleOrientation: chart_legend_title_orientation.value,
style: {
data: {
type: chart_legend_data_type.value
},
labels: LABEL_PROPS,
title: {
...LABEL_PROPS,
fontSize: TYPOGRAPHY_FONT_SIZE,
padding: chart_legend_title_Padding.value
}
}
},
line: {
...LAYOUT_PROPS,
style: {
data: {
fill: chart_line_data_Fill.value,
opacity: chart_line_data_Opacity.value,
stroke: chart_line_data_stroke_Color.value,
strokeWidth: chart_line_data_stroke_Width.value
},
labels: LABEL_CENTERED_PROPS
}
},
pie: {
padding: chart_pie_Padding.value,
style: {
data: {
padding: chart_pie_data_Padding.value,
stroke: chart_pie_data_stroke_Color.value,
strokeWidth: chart_pie_data_stroke_Width.value
},
labels: {
...LABEL_PROPS,
padding: chart_pie_labels_Padding.value
}
},
height: chart_pie_Height.value,
width: chart_pie_Width.value
},
scatter: {
...LAYOUT_PROPS,
style: {
data: {
fill: chart_scatter_data_Fill.value,
opacity: chart_scatter_data_Opacity.value,
stroke: chart_scatter_data_stroke_Color.value,
strokeWidth: chart_scatter_data_stroke_Width.value
},
labels: LABEL_CENTERED_PROPS
}
},
stack: {
...LAYOUT_PROPS,
style: {
data: {
strokeWidth: chart_stack_data_stroke_Width.value
}
}
},
tooltip: {
cornerRadius: chart_tooltip_corner_radius.value,
flyoutPadding: chart_tooltip_Padding.value,
flyoutStyle: {
cornerRadius: chart_tooltip_flyoutStyle_corner_radius.value,
fill: chart_tooltip_flyoutStyle_Fill.value, // background
pointerEvents: chart_tooltip_flyoutStyle_PointerEvents.value,
stroke: chart_tooltip_flyoutStyle_stroke_Color.value, // border
strokeWidth: chart_tooltip_flyoutStyle_stroke_Width.value
},
pointerLength: chart_tooltip_pointer_length.value,
pointerWidth: chart_tooltip_pointer_Width.value,
style: {
fill: chart_tooltip_Fill.value, // text
pointerEvents: chart_tooltip_PointerEvents.value
}
},
voronoi: {
...LAYOUT_PROPS,
style: {
data: {
fill: chart_voronoi_data_Fill.value,
stroke: chart_voronoi_data_stroke_Color.value,
strokeWidth: chart_voronoi_data_stroke_Width.value
},
labels: {
...LABEL_CENTERED_PROPS,
fill: chart_voronoi_labels_Fill.value, // text
padding: chart_voronoi_labels_Padding.value,
pointerEvents: chart_voronoi_labels_PointerEvents.value
},
// Note: These properties override tooltip
flyout: {
fill: chart_voronoi_flyout_stroke_Fill.value, // background
pointerEvents: chart_voronoi_flyout_PointerEvents.value,
stroke: chart_voronoi_flyout_stroke_Color.value, // border
strokeWidth: chart_voronoi_flyout_stroke_Width.value
}
}
}
};
|
jelly/patternfly-react | packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/DefaultGroup.tsx | <gh_stars>0
import * as React from 'react';
import { observer } from 'mobx-react';
import {
useCombineRefs,
WithDragNodeProps,
WithSelectionProps,
Node,
Rect,
Layer,
WithDndDropProps,
WithDndDragProps,
useAnchor,
RectAnchor
} from '@patternfly/react-topology';
type GroupProps = {
element: Node;
droppable?: boolean;
hover?: boolean;
canDrop?: boolean;
} & WithSelectionProps &
WithDragNodeProps &
WithDndDragProps &
WithDndDropProps;
const DefaultGroup: React.FunctionComponent<GroupProps> = ({
element,
children,
selected,
onSelect,
dragNodeRef,
dndDragRef,
dndDropRef,
droppable,
hover,
canDrop
}) => {
useAnchor(RectAnchor);
const boxRef = React.useRef<Rect | null>(null);
const refs = useCombineRefs<SVGRectElement>(dragNodeRef, dndDragRef, dndDropRef);
if (!droppable || !boxRef.current) {
// change the box only when not dragging
boxRef.current = element.getBounds();
}
let fill = '#ededed';
if (canDrop && hover) {
fill = 'lightgreen';
} else if (canDrop && droppable) {
fill = 'lightblue';
} else if (element.getData()) {
fill = element.getData().background;
}
if (element.isCollapsed()) {
const { width, height } = element.getDimensions();
return (
<g>
<rect
ref={refs}
x={0}
y={0}
width={width}
height={height}
rx={5}
ry={5}
fill={fill}
strokeWidth={2}
stroke={selected ? 'blue' : '#cdcdcd'}
/>
</g>
);
}
return (
<Layer id="groups">
<rect
ref={refs}
onClick={onSelect}
x={boxRef.current.x}
y={boxRef.current.y}
width={boxRef.current.width}
height={boxRef.current.height}
fill={fill}
strokeWidth={2}
stroke={selected ? 'blue' : '#cdcdcd'}
/>
{children}
</Layer>
);
};
export default observer(DefaultGroup);
|
jelly/patternfly-react | packages/react-topology/src/components/factories/components/componentUtils.ts | import { action } from 'mobx';
import { Edge, Graph, GraphElement, isEdge, Node } from '../../../types';
import {
CREATE_CONNECTOR_DROP_TYPE,
CREATE_CONNECTOR_OPERATION,
DragObjectWithType,
DragOperationWithType,
DragSourceSpec,
DragSpecOperationType,
DropTargetMonitor,
DropTargetSpec,
Modifiers,
TargetType
} from '../../../behavior';
const MOVE_CONNECTOR_DROP_TYPE = '#moveConnector#';
const NODE_DRAG_TYPE = '#node#';
const EDGE_DRAG_TYPE = '#edge#';
const MOVE_CONNECTOR_OPERATION = 'moveconnector';
const REGROUP_OPERATION = 'regroup';
export interface GraphComponentProps {
element: Graph;
}
export interface NodeComponentProps {
element: Node;
}
export interface EdgeComponentProps {
element: Edge;
}
/**
* type: the drag operation type
* edit: true if the operation performs an edit, used to dim invalid drop targets
* canDropOnNode: true if the drag object can be dropped on node, used to highlight valid drop nodes
*/
export type EditableDragOperationType = DragOperationWithType & {
edit?: boolean;
canDropOnNode?: (operationType: string, dragElement: GraphElement, node: Node) => boolean;
};
export interface DragNodeObject {
element: GraphElement;
allowRegroup: boolean;
}
const canDropEdgeOnNode = (operation: string, element: GraphElement, node: Node): boolean => {
if (!isEdge(element)) {
return false;
}
const edge = element as Edge;
if (edge.getSource() === node) {
return false;
}
if (edge.getTarget() === node) {
return true;
}
return !node.getTargetEdges().find(e => e.getSource() === edge.getSource());
};
const highlightNode = (monitor: DropTargetMonitor, element: Node): boolean => {
const operation = monitor.getOperation() as EditableDragOperationType;
if (!monitor.isDragging() || !operation) {
return false;
}
if (operation.type === CREATE_CONNECTOR_OPERATION) {
return (
monitor.getItem() !== element &&
monitor.getItem().getParent() !== element &&
!monitor
.getItem()
.getSourceEdges()
.find((e: Edge) => e.getTarget() === element)
);
}
return operation.canDropOnNode && operation.canDropOnNode(operation.type, monitor.getItem(), element);
};
const nodeDragSourceSpec = (
type: string,
allowRegroup: boolean = true,
canEdit: boolean = false
): DragSourceSpec<
DragObjectWithType,
DragSpecOperationType<EditableDragOperationType>,
Node,
{
dragging?: boolean;
regrouping?: boolean;
},
NodeComponentProps & { canEdit?: boolean }
> => ({
item: { type: NODE_DRAG_TYPE },
operation: (monitor, props) =>
(canEdit || props.canEdit) && allowRegroup
? {
[Modifiers.SHIFT]: { type: REGROUP_OPERATION, edit: true }
}
: undefined,
canCancel: monitor => monitor.getOperation()?.type === REGROUP_OPERATION,
begin: (monitor, props): DragNodeObject => ({
element: props.element,
allowRegroup: (canEdit || props.canEdit) && allowRegroup
}),
end: async (dropResult, monitor, props) => {
if (!monitor.isCancelled() && monitor.getOperation()?.type === REGROUP_OPERATION) {
if (monitor.didDrop() && dropResult && props && props.element.getParent() !== dropResult) {
const controller = props.element.getController();
// perform the update in an action so as not to render too soon
action(() => {
if (controller.getNodeById(props.element.getId())) {
dropResult.appendChild(props.element);
}
})();
} else {
// cancel operation
return Promise.reject();
}
}
return undefined;
},
collect: monitor => ({
dragging: monitor.isDragging(),
regrouping: monitor.getOperation()?.type === REGROUP_OPERATION
})
});
const noRegroupDragSourceSpec: DragSourceSpec<
DragObjectWithType,
DragSpecOperationType<EditableDragOperationType>,
Node,
{
dragging?: boolean;
},
NodeComponentProps
> = {
item: { type: NODE_DRAG_TYPE },
collect: monitor => ({
dragging: monitor.isDragging()
})
};
const nodesEdgeIsDragging = (monitor: any, props: NodeComponentProps) => {
if (!monitor.isDragging()) {
return false;
}
if (monitor.getOperation() === MOVE_CONNECTOR_OPERATION) {
return monitor.getItem().getSource() === props.element;
}
if (monitor.getOperation() === CREATE_CONNECTOR_OPERATION) {
return monitor.getItem() === props.element;
}
return false;
};
const nodeDropTargetSpec = (
accept?: TargetType
): DropTargetSpec<
GraphElement,
any,
{ canDrop: boolean; dropTarget: boolean; edgeDragging: boolean },
NodeComponentProps
> => ({
accept: accept || [EDGE_DRAG_TYPE, CREATE_CONNECTOR_DROP_TYPE],
canDrop: (item, monitor, props) => {
if (isEdge(item)) {
return canDropEdgeOnNode(monitor.getOperation()?.type, item as Edge, props.element);
}
if (item === props.element) {
return false;
}
return !props.element.getTargetEdges().find(e => e.getSource() === item);
},
collect: (monitor, props) => ({
canDrop: highlightNode(monitor, props.element),
dropTarget: monitor.isOver({ shallow: true }),
edgeDragging: nodesEdgeIsDragging(monitor, props)
})
});
const graphDropTargetSpec = (
accept?: TargetType
): DropTargetSpec<DragNodeObject, any, { dragEditInProgress: boolean }, GraphComponentProps> => ({
accept: accept || [NODE_DRAG_TYPE, EDGE_DRAG_TYPE, CREATE_CONNECTOR_DROP_TYPE],
hitTest: () => true,
canDrop: (item, monitor, props) =>
monitor.isOver({ shallow: monitor.getItemType() === CREATE_CONNECTOR_DROP_TYPE }) &&
((monitor.getOperation()?.type === REGROUP_OPERATION &&
// FIXME: the hasParent check is necessary due to model updates during async actions
item.element.hasParent() &&
item.element.getParent() !== props.element) ||
monitor.getItemType() === CREATE_CONNECTOR_DROP_TYPE),
collect: monitor => {
const operation = monitor.getOperation() as EditableDragOperationType;
const dragEditInProgress =
monitor.isDragging() && (operation?.type === CREATE_CONNECTOR_OPERATION || operation?.edit);
const dragCreate =
dragEditInProgress &&
(monitor.getItemType() === CREATE_CONNECTOR_DROP_TYPE || monitor.getItemType() === MOVE_CONNECTOR_DROP_TYPE);
return {
dragEditInProgress,
dragCreate,
hasDropTarget: dragEditInProgress && monitor.hasDropTarget()
};
},
dropHint: 'create'
});
const groupDropTargetSpec: DropTargetSpec<
any,
any,
{ droppable: boolean; dropTarget: boolean; canDrop: boolean },
any
> = {
accept: [NODE_DRAG_TYPE, EDGE_DRAG_TYPE, CREATE_CONNECTOR_DROP_TYPE],
canDrop: (item, monitor) =>
monitor.isOver({ shallow: monitor.getItemType() === CREATE_CONNECTOR_DROP_TYPE }) &&
(monitor.getOperation()?.type === REGROUP_OPERATION || monitor.getItemType() === CREATE_CONNECTOR_DROP_TYPE),
collect: monitor => ({
droppable: monitor.isDragging() && monitor.getOperation()?.type === REGROUP_OPERATION,
dropTarget: monitor.isOver({ shallow: monitor.getItemType() === CREATE_CONNECTOR_DROP_TYPE }),
canDrop:
monitor.isDragging() &&
(monitor.getOperation()?.type === REGROUP_OPERATION || monitor.getItemType() === CREATE_CONNECTOR_DROP_TYPE),
dragRegroupable: monitor.isDragging() && monitor.getItem()?.allowRegroup
}),
dropHint: 'create'
};
const edgeDragSourceSpec = (
type: string,
callback: (sourceNode: Node, targetNode: Node, replaceTargetNode?: Node) => void
): DragSourceSpec<
DragObjectWithType,
DragSpecOperationType<EditableDragOperationType>,
Node,
{ dragging: boolean },
EdgeComponentProps
> => ({
item: { type: EDGE_DRAG_TYPE },
operation: { type: MOVE_CONNECTOR_OPERATION, edit: true, canDropOnNode: canDropEdgeOnNode },
begin: (monitor, props) => {
props.element.raise();
return props.element;
},
drag: (event, monitor, props) => {
props.element.setEndPoint(event.x, event.y);
},
end: (dropResult, monitor, props) => {
props.element.setEndPoint();
if (monitor.didDrop() && dropResult && canDropEdgeOnNode(monitor.getOperation()?.type, props.element, dropResult)) {
callback(props.element.getSource(), dropResult, props.element.getTarget());
}
},
collect: monitor => ({
dragging: monitor.isDragging()
})
});
const noDropTargetSpec: DropTargetSpec<GraphElement, any, {}, { element: GraphElement }> = {
accept: [NODE_DRAG_TYPE, EDGE_DRAG_TYPE, CREATE_CONNECTOR_DROP_TYPE],
canDrop: () => false
};
export {
nodesEdgeIsDragging,
noRegroupDragSourceSpec,
nodeDragSourceSpec,
nodeDropTargetSpec,
graphDropTargetSpec,
groupDropTargetSpec,
edgeDragSourceSpec,
noDropTargetSpec,
REGROUP_OPERATION,
MOVE_CONNECTOR_DROP_TYPE,
NODE_DRAG_TYPE,
EDGE_DRAG_TYPE,
canDropEdgeOnNode,
highlightNode
};
|
jelly/patternfly-react | packages/react-core/src/components/ContextSelector/examples/ContextSelectorBasic.tsx | <reponame>jelly/patternfly-react<filename>packages/react-core/src/components/ContextSelector/examples/ContextSelectorBasic.tsx
import React from 'react';
import { ContextSelector, ContextSelectorItem } from '@patternfly/react-core';
export const ContextSelectorBasic: React.FunctionComponent = () => {
const items = [
{
text: 'Link',
href: '#'
},
'Action',
{
text: 'Disabled link',
href: '#',
isDisabled: true
},
{
text: 'Disabled action',
isDisabled: true
},
'My project',
'OpenShift cluster',
'Production Ansible',
'AWS',
'Azure',
'My project 2',
'OpenShift cluster ',
'Production Ansible 2 ',
'AWS 2',
'Azure 2'
];
const firstItemText = typeof items[0] === 'string' ? items[0] : items[0].text;
const [isOpen, setOpen] = React.useState(false);
const [selected, setSelected] = React.useState(firstItemText);
const [searchValue, setSearchValue] = React.useState('');
const [filteredItems, setFilteredItems] = React.useState(items);
const onToggle = (event: any, isOpen: boolean) => {
setOpen(isOpen);
};
const onSelect = (event: any, value: React.ReactNode) => {
setSelected(value as string);
setOpen(!isOpen);
};
const onSearchInputChange = (value: string) => {
setSearchValue(value);
};
const onSearchButtonClick = (_event: React.SyntheticEvent<HTMLButtonElement>) => {
const filtered =
searchValue === ''
? items
: items.filter(item => {
const str = typeof item === 'string' ? item : item.text;
return str.toLowerCase().indexOf(searchValue.toLowerCase()) !== -1;
});
setFilteredItems(filtered || []);
};
return (
<ContextSelector
toggleText={selected}
onSearchInputChange={onSearchInputChange}
isOpen={isOpen}
searchInputValue={searchValue}
onToggle={onToggle}
onSelect={onSelect}
onSearchButtonClick={onSearchButtonClick}
screenReaderLabel="Selected Project:"
>
{filteredItems.map((item, index) => {
const [text = null, href = null, isDisabled] =
typeof item === 'string' ? [item, null, false] : [item.text, item.href, item.isDisabled];
return (
<ContextSelectorItem key={index} href={href} isDisabled={isDisabled}>
{text || item}
</ContextSelectorItem>
);
})}
</ContextSelector>
);
};
|
jelly/patternfly-react | packages/react-core/src/components/Avatar/__tests__/Avatar.test.tsx | import * as React from 'react';
import { render } from '@testing-library/react';
import { Avatar } from '../Avatar';
test('simple avatar', () => {
const { asFragment } = render(<Avatar alt="avatar" src="test.png" border="light" />);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-core/src/components/Divider/examples/DividerUsingLi.tsx | <reponame>jelly/patternfly-react
import React from 'react';
import { Divider } from '@patternfly/react-core';
export const DividerUsingLi: React.FunctionComponent = () => (
<ul>
<li>List item one</li>
<Divider component="li" />
<li>List item two</li>
</ul>
);
|
jelly/patternfly-react | packages/react-core/src/components/DescriptionList/DescriptionListTerm.tsx | <reponame>jelly/patternfly-react
import * as React from 'react';
import styles from '@patternfly/react-styles/css/components/DescriptionList/description-list';
import { css } from '@patternfly/react-styles';
export interface DescriptionListTermProps extends React.HTMLProps<HTMLElement> {
/** Anything that can be rendered inside of list term */
children: React.ReactNode;
/** Icon that is rendered inside of list term to the left side of the children */
icon?: React.ReactNode;
/** Additional classes added to the DescriptionListTerm */
className?: string;
}
export const DescriptionListTerm: React.FunctionComponent<DescriptionListTermProps> = ({
children,
className,
icon,
...props
}: DescriptionListTermProps) => (
<dt className={css(styles.descriptionListTerm, className)} {...props}>
{icon ? <span className={css(styles.descriptionListTermIcon)}>{icon}</span> : null}
<span className={css(styles.descriptionListText)}>{children}</span>
</dt>
);
DescriptionListTerm.displayName = 'DescriptionListTerm';
|
jelly/patternfly-react | packages/react-core/src/components/DescriptionList/DescriptionList.tsx | <reponame>jelly/patternfly-react
import * as React from 'react';
import { css } from '@patternfly/react-styles';
import styles from '@patternfly/react-styles/css/components/DescriptionList/description-list';
import { formatBreakpointMods } from '../../helpers';
export interface BreakpointModifiers {
default?: string;
md?: string;
lg?: string;
xl?: string;
'2xl'?: string;
}
export interface DescriptionListProps extends Omit<React.HTMLProps<HTMLDListElement>, 'type'> {
/** Anything that can be rendered inside of the list */
children?: React.ReactNode;
/** Additional classes added to the list */
className?: string;
/** Sets the description list to auto fit. */
isAutoFit?: boolean;
/** Sets the description list component term and description pair to a horizontal layout. */
isHorizontal?: boolean;
/** Sets the description list to format automatically. */
isAutoColumnWidths?: boolean;
/** Modifies the description list display to inline-grid. */
isInlineGrid?: boolean;
/** Sets the description list to compact styling. */
isCompact?: boolean;
/** Sets a horizontal description list to have fluid styling. */
isFluid?: boolean;
/** Sets the the default placement of description list groups to fill from top to bottom. */
isFillColumns?: boolean;
/** Sets the number of columns on the description list at various breakpoints */
columnModifier?: {
default?: '1Col' | '2Col' | '3Col';
sm?: '1Col' | '2Col' | '3Col';
md?: '1Col' | '2Col' | '3Col';
lg?: '1Col' | '2Col' | '3Col';
xl?: '1Col' | '2Col' | '3Col';
'2xl'?: '1Col' | '2Col' | '3Col';
};
/** Indicates how the menu will align at various breakpoints. */
orientation?: {
sm?: 'vertical' | 'horizontal';
md?: 'vertical' | 'horizontal';
lg?: 'vertical' | 'horizontal';
xl?: 'vertical' | 'horizontal';
'2xl'?: 'vertical' | 'horizontal';
};
/** Sets the minimum column size for the auto-fit (isAutoFit) layout at various breakpoints. */
autoFitMinModifier?: {
default?: string;
sm?: string;
md?: string;
lg?: string;
xl?: string;
'2xl'?: string;
};
/** Sets the horizontal description list's term column width at various breakpoints. */
horizontalTermWidthModifier?: {
default?: string;
sm?: string;
md?: string;
lg?: string;
xl?: string;
'2xl'?: string;
};
}
const setBreakpointModifiers = (prefix: string, modifiers: BreakpointModifiers) => {
const mods = modifiers as Partial<{ [k: string]: string }>;
return Object.keys(mods || {}).reduce(
(acc, curr) =>
curr === 'default' ? { ...acc, [prefix]: mods[curr] } : { ...acc, [`${prefix}-on-${curr}`]: mods[curr] },
{}
);
};
export const DescriptionList: React.FunctionComponent<DescriptionListProps> = ({
className = '',
children = null,
isHorizontal = false,
isAutoColumnWidths,
isAutoFit,
isInlineGrid,
isCompact,
isFluid,
isFillColumns,
columnModifier,
autoFitMinModifier,
horizontalTermWidthModifier,
orientation,
style,
...props
}: DescriptionListProps) => {
if (isAutoFit && autoFitMinModifier) {
style = {
...style,
...setBreakpointModifiers('--pf-c-description-list--GridTemplateColumns--min', autoFitMinModifier)
};
}
if (isHorizontal && horizontalTermWidthModifier) {
style = {
...style,
...setBreakpointModifiers('--pf-c-description-list--m-horizontal__term--width', horizontalTermWidthModifier)
};
}
return (
<dl
className={css(
styles.descriptionList,
(isHorizontal || isFluid) && styles.modifiers.horizontal,
isAutoColumnWidths && styles.modifiers.autoColumnWidths,
isAutoFit && styles.modifiers.autoFit,
formatBreakpointMods(columnModifier, styles),
formatBreakpointMods(orientation, styles),
isInlineGrid && styles.modifiers.inlineGrid,
isCompact && styles.modifiers.compact,
isFluid && styles.modifiers.fluid,
isFillColumns && styles.modifiers.fillColumns,
className
)}
style={style}
{...props}
>
{children}
</dl>
);
};
DescriptionList.displayName = 'DescriptionList';
|
jelly/patternfly-react | packages/react-core/src/components/Wizard/__tests__/Generated/WizardFooterInternal.test.tsx | /**
* This test was generated
*/
import * as React from 'react';
import { render } from '@testing-library/react';
import { WizardFooterInternal } from '../../WizardFooterInternal';
// any missing imports can usually be resolved by adding them here
import {} from '../..';
it('WizardFooterInternal should match snapshot (auto-generated)', () => {
const { asFragment } = render(
<WizardFooterInternal
onNext={'any'}
onBack={'any'}
onClose={'any'}
isValid={true}
firstStep={true}
activeStep={{ name: 'some step' }}
nextButtonText={<div>ReactNode</div>}
backButtonText={<div>ReactNode</div>}
cancelButtonText={<div>ReactNode</div>}
/>
);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-core/src/components/DualListSelector/DualListSelectorList.tsx | import { css } from '@patternfly/react-styles';
import styles from '@patternfly/react-styles/css/components/DualListSelector/dual-list-selector';
import { DualListSelectorListItem } from './DualListSelectorListItem';
import * as React from 'react';
import { DualListSelectorListContext } from './DualListSelectorContext';
export interface DualListSelectorListProps extends React.HTMLProps<HTMLUListElement> {
children?: React.ReactNode;
}
export const DualListSelectorList: React.FunctionComponent<DualListSelectorListProps> = ({
children,
...props
}: DualListSelectorListProps) => {
const {
setFocusedOption,
isTree,
ariaLabelledBy,
focusedOption,
displayOption,
selectedOptions,
id,
onOptionSelect,
options,
isDisabled
} = React.useContext(DualListSelectorListContext);
// only called when options are passed via options prop
const onOptionClick = (e: React.MouseEvent | React.ChangeEvent | React.KeyboardEvent, index: number, id: string) => {
setFocusedOption(id);
onOptionSelect(e, index, id);
};
return (
<ul
className={css(styles.dualListSelectorList)}
role={isTree ? 'tree' : 'listbox'}
aria-multiselectable="true"
aria-labelledby={ariaLabelledBy}
aria-activedescendant={focusedOption}
aria-disabled={isDisabled ? 'true' : undefined}
{...props}
>
{options.length === 0
? children
: options.map((option, index) => {
if (displayOption(option)) {
return (
<DualListSelectorListItem
key={index}
isSelected={(selectedOptions as number[]).indexOf(index) !== -1}
id={`${id}-option-${index}`}
onOptionSelect={(e, id) => onOptionClick(e, index, id)}
orderIndex={index}
isDisabled={isDisabled}
>
{option}
</DualListSelectorListItem>
);
}
return;
})}
</ul>
);
};
DualListSelectorList.displayName = 'DualListSelectorList';
|
jelly/patternfly-react | packages/react-console/src/components/VncConsole/VncConsole.tsx | import React from 'react';
import { css } from '@patternfly/react-styles';
import { Button, EmptyState, EmptyStateBody, EmptyStateIcon, Spinner } from '@patternfly/react-core';
import { initLogging } from '@novnc/novnc/core/util/logging';
/** Has bad types. https://github.com/larryprice/novnc-core/issues/5 */
import RFB from '@novnc/novnc/core/rfb';
import { VncActions } from './VncActions';
import { constants } from '../common/constants';
import styles from '@patternfly/react-styles/css/components/Consoles/VncConsole';
import '@patternfly/react-styles/css/components/Consoles/VncConsole.css';
const { CONNECTED, CONNECTING, DISCONNECTED } = constants;
export interface VncConsoleProps extends React.HTMLProps<HTMLDivElement> {
/** Children nodes */
children?: React.ReactNode;
/** FQDN or IP to connect to */
host: string;
/** TCP Port */
port?: string;
/** host:port/path */
path?: string;
encrypt?: boolean;
/** Is a boolean indicating if a request to resize the remote session should be sent whenever the container changes dimensions */
resizeSession?: boolean;
/** Is a boolean indicating if the remote session should be scaled locally so it fits its container */
scaleViewport?: boolean;
/** Is a boolean indicating if any events (e.g. key presses or mouse movement) should be prevented from being sent to the server */
viewOnly?: boolean;
/** Is a boolean indicating if the remote server should be shared or if any other connected clients should be disconnected */
shared?: boolean;
/** An Object specifying the credentials to provide to the server when authenticating
* { username: '' password: '' target: ''}
*/
credentials?: object;
/** A DOMString specifying the ID to provide to any VNC repeater encountered */
repeaterID?: string;
/** log-level for noVNC */
vncLogging?: 'error' | 'warn' | 'none' | 'debug' | 'info';
consoleContainerId?: string;
additionalButtons?: React.ReactNode[];
/** Callback. VNC server disconnected. */
onDisconnected?: (e: any) => void;
/** Initialization of RFB failed */
onInitFailed?: (e: any) => void;
/** Handshake failed */
onSecurityFailure?: (e: any) => void;
/* Text content rendered inside the EmptyState in the "Connect' button for when console is disconnnected */
textConnect?: string;
/* Text content rendered inside the EmptyState for when console is connecting */
textConnecting?: string | React.ReactNode;
/* Text content rendered inside the EmptyState for when console is disconnnected */
textDisconnected?: string;
/** Text content rendered inside the Disconnect button */
textDisconnect?: string;
/** Text content rendered inside the button Send shortcut dropdown toggle */
textSendShortcut?: string;
/** Text content rendered inside the Ctrl-Alt-Delete dropdown entry */
textCtrlAltDel?: string;
}
export const VncConsole: React.FunctionComponent<VncConsoleProps> = ({
children,
host,
port = '80',
path = '',
encrypt = false,
resizeSession = true,
scaleViewport = false,
viewOnly = false,
shared = false,
credentials,
repeaterID = '',
vncLogging = 'warn',
consoleContainerId,
additionalButtons = [] as React.ReactNode[],
onDisconnected = () => {},
onInitFailed,
onSecurityFailure,
textConnect = 'Connect',
textConnecting = 'Connecting',
textDisconnected = 'Click Connect to open the VNC console.',
textDisconnect = 'Disconnect',
textSendShortcut,
textCtrlAltDel
}) => {
const rfb = React.useRef<any>();
let novncStaticComponent: React.ReactNode;
let novncElem: HTMLDivElement;
const [status, setStatus] = React.useState(CONNECTING);
const addEventListeners = () => {
if (rfb.current) {
rfb.current?.addEventListener('connect', onConnected);
rfb.current?.addEventListener('disconnect', _onDisconnected);
rfb.current?.addEventListener('securityfailure', _onSecurityFailure);
}
};
const removeEventListeners = () => {
if (rfb.current) {
rfb.current.removeEventListener('connect', onConnected);
rfb.current.removeEventListener('disconnect', _onDisconnected);
rfb.current.removeEventListener('securityfailure', _onSecurityFailure);
}
};
const connect = () => {
const protocol = encrypt ? 'wss' : 'ws';
const url = `${protocol}://${host}:${port}/${path}`;
const options = {
repeaterID,
shared,
credentials
};
rfb.current = new RFB(novncElem, url, options);
addEventListeners();
rfb.current.viewOnly = viewOnly;
rfb.current.scaleViewport = scaleViewport;
rfb.current.resizeSession = resizeSession;
};
React.useEffect(() => {
initLogging(vncLogging);
try {
connect();
} catch (e) {
onInitFailed && onInitFailed(e);
rfb.current = undefined;
}
return () => {
disconnect();
removeEventListeners();
rfb.current = undefined;
};
}, [connect, onInitFailed, removeEventListeners, vncLogging]);
const disconnect = () => {
if (!rfb.current) {
return;
}
rfb.current.disconnect();
};
const onConnected = () => {
setStatus(CONNECTED);
};
const _onDisconnected = (e: any) => {
setStatus(DISCONNECTED);
onDisconnected(e);
};
const _onSecurityFailure = (e: any) => {
setStatus(DISCONNECTED);
onSecurityFailure(e);
};
const onCtrlAltDel = () => {
if (rfb.current) {
rfb?.current?.sendCtrlAltDel();
}
};
let rightContent;
let emptyState;
switch (status) {
case CONNECTED:
rightContent = (
<VncActions
onCtrlAltDel={onCtrlAltDel}
textSendShortcut={textSendShortcut}
textCtrlAltDel={textCtrlAltDel}
textDisconnect={textDisconnect}
onDisconnect={disconnect}
additionalButtons={additionalButtons}
/>
);
break;
case DISCONNECTED:
emptyState = (
<EmptyState>
<EmptyStateBody>{textDisconnected}</EmptyStateBody>
<Button variant="primary" onClick={connect}>
{textConnect}
</Button>
</EmptyState>
);
break;
case CONNECTING:
default:
emptyState = (
<EmptyState>
<EmptyStateIcon variant="container" component={Spinner} />
<EmptyStateBody>{textConnecting}</EmptyStateBody>
</EmptyState>
);
}
if (!novncStaticComponent) {
novncStaticComponent = <div id={consoleContainerId} ref={e => (novncElem = e)} />;
}
return (
<>
{rightContent}
<div className={css(styles.consoleVnc)}>
{children}
<React.Fragment>
<div>
{emptyState}
{novncStaticComponent}
</div>
</React.Fragment>
</div>
</>
);
};
VncConsole.displayName = 'VncConsole';
|
jelly/patternfly-react | packages/react-core/src/components/Select/__tests__/SelectToggle.test.tsx | <reponame>jelly/patternfly-react
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SelectToggle } from '../SelectToggle';
describe('SelectToggle', () => {
describe('API', () => {
test('click on closed', () => {
const mockToggle = jest.fn();
render(
<SelectToggle id="Select Toggle" onToggle={mockToggle} parentRef={{ current: document.createElement('div') }}>
Select
</SelectToggle>
);
userEvent.click(screen.getByRole('button'));
expect(mockToggle).toHaveBeenCalledWith(true, expect.any(Object));
});
test('click on opened', () => {
const mockToggle = jest.fn();
render(
<SelectToggle
id="Select Toggle"
onToggle={mockToggle}
isOpen
parentRef={{ current: document.createElement('div') }}
>
Select
</SelectToggle>
);
userEvent.click(screen.getByRole('button'));
expect(mockToggle).toHaveBeenCalledWith(false, expect.any(MouseEvent));
});
test('click on document', () => {
const mockToggle = jest.fn();
render(
<SelectToggle
id="Select Toggle"
onToggle={mockToggle}
isOpen
parentRef={{ current: document.createElement('div') }}
>
Select
</SelectToggle>
);
userEvent.click(screen.getByText('Select').parentElement);
expect(mockToggle).toHaveBeenCalledWith(false, expect.any(MouseEvent));
});
test('on click outside has been removed', () => {
const mockToggle = jest.fn();
render(
<SelectToggle
id="Select Toggle"
onToggle={mockToggle}
isOpen={false}
parentRef={{ current: document.createElement('div') }}
>
Select
</SelectToggle>
);
userEvent.click(screen.getByText('Select').parentElement);
expect(mockToggle).not.toHaveBeenCalled();
});
});
describe('state', () => {
test('active', () => {
const { asFragment } = render(
<SelectToggle id="Select Toggle" isActive parentRef={{ current: document.createElement('div') }}>
Select
</SelectToggle>
);
expect(asFragment()).toMatchSnapshot();
});
});
});
|
jelly/patternfly-react | packages/react-table/src/components/TableComposable/examples/ComposableTableActionsOverflow.tsx | /* eslint-disable no-console */
import React from 'react';
import {
Button,
OverflowMenu,
OverflowMenuControl,
OverflowMenuContent,
OverflowMenuGroup,
OverflowMenuItem,
OverflowMenuDropdownItem,
Dropdown,
KebabToggle
} from '@patternfly/react-core';
import { TableComposable, Thead, Tr, Th, Tbody, Td } from '@patternfly/react-table';
interface Repository {
name: string;
branches: string;
prs: string;
workspaces: string;
lastCommit: string;
isMenuOpen: boolean;
}
export const ComposableTableActions: 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', isMenuOpen: false },
{ name: 'a', branches: 'two', prs: 'k', workspaces: 'four', lastCommit: 'five', isMenuOpen: false },
{ name: 'p', branches: 'two', prs: 'b', workspaces: 'four', lastCommit: 'five', isMenuOpen: false },
{ name: '4', branches: '2', prs: 'b', workspaces: 'four', lastCommit: 'five', isMenuOpen: false },
{ name: '5', branches: '2', prs: 'b', workspaces: 'four', lastCommit: 'five', isMenuOpen: false }
];
const [repos, setRepos] = React.useState(repositories);
const columnNames = {
name: 'Repositories',
branches: 'Branches',
prs: 'Pull requests',
workspaces: 'Workspaces',
lastCommit: 'Last commit'
};
const dropdownItems = [
<OverflowMenuDropdownItem key="item1" isShared>
Pimary
</OverflowMenuDropdownItem>,
<OverflowMenuDropdownItem key="item2" isShared>
Secondary
</OverflowMenuDropdownItem>,
<OverflowMenuDropdownItem key="item3" isShared>
Tertiary
</OverflowMenuDropdownItem>
];
return (
<React.Fragment>
<TableComposable aria-label="Actions table">
<Thead>
<Tr>
<Th>{columnNames.name}</Th>
<Th>{columnNames.branches}</Th>
<Th>{columnNames.prs}</Th>
<Th>{columnNames.workspaces}</Th>
<Th>{columnNames.lastCommit}</Th>
<Td></Td>
</Tr>
</Thead>
<Tbody>
{repos.map(repo => (
<Tr key={repo.name}>
<Td dataLabel={columnNames.name}>{repo.name}</Td>
<Td dataLabel={columnNames.branches}>{repo.branches}</Td>
<Td dataLabel={columnNames.prs}>{repo.prs}</Td>
<Td dataLabel={columnNames.workspaces}>{repo.workspaces}</Td>
<Td dataLabel={columnNames.lastCommit}>{repo.lastCommit}</Td>
<Td isActionCell>
<OverflowMenu breakpoint="lg">
<OverflowMenuContent>
<OverflowMenuGroup groupType="button">
<OverflowMenuItem>
<Button variant="primary">Primary</Button>
</OverflowMenuItem>
<OverflowMenuItem>
<Button variant="secondary">Secondary</Button>
</OverflowMenuItem>
<OverflowMenuItem>
<Button variant="tertiary">Tertiary</Button>
</OverflowMenuItem>
</OverflowMenuGroup>
</OverflowMenuContent>
<OverflowMenuControl>
<Dropdown
position="right"
onSelect={() =>
setRepos(repos.map(r => (r.name !== repo.name ? r : { ...r, isMenuOpen: !r.isMenuOpen })))
}
toggle={
<KebabToggle
onToggle={open =>
setRepos(repos.map(r => (r.name !== repo.name ? r : { ...r, isMenuOpen: open })))
}
/>
}
isOpen={repo.isMenuOpen}
isPlain
dropdownItems={dropdownItems}
/>
</OverflowMenuControl>
</OverflowMenu>
</Td>
</Tr>
))}
</Tbody>
</TableComposable>
</React.Fragment>
);
};
|
jelly/patternfly-react | packages/react-topology/src/components/defs/SVGDefs.tsx | import * as React from 'react';
import SVGDefsContext, { SVGDefsContextProps } from './SVGDefsContext';
import { SVGDefsSetter } from './SVGDefsSetter';
interface SVGDefsProps {
id: string;
children: React.ReactNode;
}
export type SVGDefsSetterProps = SVGDefsContextProps & SVGDefsProps;
/**
* Contributes `children` to the parent SVG `<defs>` element.
* A contribution is assumed to be static in nature in that the children will never change
* for a given ID. This is because there may be multiple children referencing the same defs contribution.
* The assumption must be that there is not a single owner but many owners and therefore each
* owner must be contributing the same def.
*/
export default class SVGDefs extends React.Component<SVGDefsProps> {
shouldComponentUpdate() {
return false;
}
render() {
return (
<SVGDefsContext.Consumer>
{({ addDef, removeDef }) => <SVGDefsSetter {...this.props} addDef={addDef} removeDef={removeDef} />}
</SVGDefsContext.Consumer>
);
}
}
|
jelly/patternfly-react | packages/react-core/src/components/Divider/examples/DividerInsetVariousBreakpoints.tsx | <gh_stars>0
import React from 'react';
import { Divider } from '@patternfly/react-core';
export const DividerInsetVariousBreakpoints: React.FunctionComponent = () => (
<Divider
inset={{
default: 'insetMd',
md: 'insetNone',
lg: 'inset3xl',
xl: 'insetLg'
}}
/>
);
|
jelly/patternfly-react | packages/react-topology/src/layouts/GridLink.ts | import { LayoutLink } from './LayoutLink';
export class GridLink extends LayoutLink {}
|
jelly/patternfly-react | packages/react-topology/src/layouts/BreadthFirstGroup.ts | import { LayoutGroup } from './LayoutGroup';
export class BreadthFirstGroup extends LayoutGroup {}
|
jelly/patternfly-react | packages/react-inline-edit-extension/src/components/ConfirmButtons/index.ts | <reponame>jelly/patternfly-react
export * from './ConfirmButtons';
|
jelly/patternfly-react | packages/react-core/src/components/ChipGroup/examples/ChipGroupRemovableCategories.tsx | import React from 'react';
import { Chip, ChipGroup } from '@patternfly/react-core';
export const ChipGroupRemovableCategories: React.FunctionComponent = () => {
const [chipGroup1, setChipGroup1] = React.useState(['Chip one', 'Chip two', 'Chip three']);
const [chipGroup2, setChipGroup2] = React.useState(['Chip one', 'Chip two', 'Chip three', 'Chip four']);
const deleteItem = (id: string, group: string[]) => {
const copyOfChips = [...group];
const filteredCopy = copyOfChips.filter(chip => chip !== id);
if (group === chipGroup1) {
setChipGroup1(filteredCopy);
} else {
setChipGroup2(filteredCopy);
}
};
const deleteCategory = (group: string[]) => {
if (group === chipGroup1) {
setChipGroup1([]);
} else {
setChipGroup2([]);
}
};
return (
<React.Fragment>
<ChipGroup categoryName="Category one" isClosable onClick={() => deleteCategory(chipGroup1)}>
{chipGroup1.map(currentChip => (
<Chip key={currentChip} onClick={() => deleteItem(currentChip, chipGroup1)}>
{currentChip}
</Chip>
))}
</ChipGroup>
<br /> <br />
<ChipGroup categoryName="Category two has a very long name" isClosable onClick={() => deleteCategory(chipGroup2)}>
{chipGroup2.map(currentChip => (
<Chip key={currentChip} onClick={() => deleteItem(currentChip, chipGroup2)}>
{currentChip}
</Chip>
))}
</ChipGroup>
</React.Fragment>
);
};
|
jelly/patternfly-react | packages/react-table/src/components/TableComposable/examples/ComposableTableStripedTr.tsx | <filename>packages/react-table/src/components/TableComposable/examples/ComposableTableStripedTr.tsx<gh_stars>0
import React from 'react';
import { TableComposable, Caption, Thead, Tr, Th, Tbody, Td } from '@patternfly/react-table';
interface Repository {
name: string;
branches: number;
prs: number;
workspaces: number;
lastCommit: string;
}
export const ComposableTableStripedTr: React.FunctionComponent = () => {
// In real usage, this data would come from some external source like an API via props.
const repositories: Repository[] = [
{ name: 'Repository 1', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' },
{ name: 'Repository 2', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' },
{ name: 'Repository 3', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' },
{ name: 'Repository 4', branches: 10, prs: 25, workspaces: 5, lastCommit: '2 days ago' }
];
const columnNames = {
name: 'Repositories',
branches: 'Branches',
prs: 'Pull requests',
workspaces: 'Workspaces',
lastCommit: 'Last commit'
};
return (
<TableComposable aria-label="Simple table">
<Caption>Manually striped table using composable components</Caption>
<Thead>
<Tr>
<Th>{columnNames.name}</Th>
<Th>{columnNames.branches}</Th>
<Th>{columnNames.prs}</Th>
<Th>{columnNames.workspaces}</Th>
<Th>{columnNames.lastCommit}</Th>
</Tr>
</Thead>
<Tbody>
{repositories.map((repo, index) => (
<Tr key={repo.name} {...(index % 2 === 0 && { isStriped: true })}>
<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>
);
};
|
jelly/patternfly-react | packages/react-integration/cypress/integration/chipgroupwithoverflowchipeventhandler.spec.ts | <gh_stars>100-1000
describe('Chip Group with Custom Overflow Chip Event Handler', () => {
it('Navigate to demo section', () => {
cy.visit('http://localhost:3000/chipgroup-with-overflow-chip-event-handler-demo-nav-link');
});
it('Verify additional text is shown from custom event handler when overflow chip is clicked', () => {
cy.get('.pf-c-title').should('not.exist');
cy.get('.pf-m-overflow').click();
cy.get('.pf-c-title').should('exist');
});
});
|
jelly/patternfly-react | packages/react-core/src/components/Form/__tests__/ActionGroup.test.tsx | <filename>packages/react-core/src/components/Form/__tests__/ActionGroup.test.tsx
import React from 'react';
import { render } from '@testing-library/react';
import { ActionGroup } from '../ActionGroup';
import { Form } from '../Form';
describe('ActionGroup component', () => {
test('should render default action group variant', () => {
const { asFragment } = render(
<ActionGroup>
<div>Hello</div>
</ActionGroup>
);
expect(asFragment()).toMatchSnapshot();
});
test('should render horizontal form ActionGroup variant', () => {
const { asFragment } = render(
<Form isHorizontal>
<ActionGroup />
</Form>
);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-integration/demo-app-ts/src/components/demos/FileUploadDemo/FileUploadDemo.tsx | import React from 'react';
import { FileUpload } from '@patternfly/react-core';
export class FileUploadDemo extends React.Component {
static displayName = 'FileUploadDemo';
state = { value: '', filename: '', isLoading: false };
/* eslint-disable-next-line no-console */
handleFileInputChange = (event: React.ChangeEvent<HTMLInputElement>, file: File) =>
this.setState({ value: file, filename: file.name });
handleDataChange = (value: string) => this.setState({ value });
/* eslint-disable @typescript-eslint/no-unused-vars */
handleFileReadStarted = (fileHandle: File) => this.setState({ isLoading: true });
handleFileReadFinished = (fileHandle: File) => this.setState({ isLoading: false });
/* eslint-enable @typescript-eslint/no-unused-vars */
render() {
const { value, filename, isLoading } = this.state;
return (
<FileUpload
id="simple-text-file"
type="text"
value={value}
filename={filename}
onFileInputChange={this.handleFileInputChange}
onDataChange={this.handleDataChange}
onReadStarted={this.handleFileReadStarted}
onReadFinished={this.handleFileReadFinished}
isLoading={isLoading}
/>
);
}
}
|
jelly/patternfly-react | packages/react-topology/src/anchors/CenterAnchor.ts | <filename>packages/react-topology/src/anchors/CenterAnchor.ts<gh_stars>100-1000
import Point from '../geom/Point';
import AbstractAnchor from './AbstractAnchor';
import { getEllipseAnchorPoint } from '../utils/anchor-utils';
export default class CenterAnchor extends AbstractAnchor {
getLocation(reference: Point): Point {
const bounds = this.owner.getBounds();
if (this.offset === 0) {
return bounds.getCenter();
}
const offset2x = this.offset * 2;
return getEllipseAnchorPoint(bounds.getCenter(), offset2x, offset2x, reference);
}
}
|
jelly/patternfly-react | packages/react-core/src/components/Modal/__tests__/ModalBox.test.tsx | import * as React from 'react';
import { render } from '@testing-library/react';
import { ModalBox } from '../ModalBox';
test('ModalBox Test', () => {
const { asFragment } = render(
<ModalBox aria-describedby="Test Modal Box" id="boxId">
This is a ModalBox
</ModalBox>
);
expect(asFragment()).toMatchSnapshot();
});
test('ModalBox Test large', () => {
const { asFragment } = render(
<ModalBox aria-describedby="Test Modal Box" id="boxId" variant="large">
This is a ModalBox
</ModalBox>
);
expect(asFragment()).toMatchSnapshot();
});
test('ModalBox Test medium', () => {
const { asFragment } = render(
<ModalBox aria-describedby="Test Modal Box" id="boxId" variant="medium">
This is a ModalBox
</ModalBox>
);
expect(asFragment()).toMatchSnapshot();
});
test('ModalBox Test small', () => {
const { asFragment } = render(
<ModalBox aria-describedby="Test Modal Box" id="boxId" variant="small">
This is a ModalBox
</ModalBox>
);
expect(asFragment()).toMatchSnapshot();
});
test('ModalBox Test top aligned', () => {
const { asFragment } = render(
<ModalBox aria-describedby="Test Modal Box" id="boxId" position="top">
This is a ModalBox
</ModalBox>
);
expect(asFragment()).toMatchSnapshot();
});
test('ModalBox Test top aligned distance', () => {
const { asFragment } = render(
<ModalBox aria-describedby="Test Modal Box" id="boxId" position="top" positionOffset="50px">
This is a ModalBox
</ModalBox>
);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-charts/src/components/ChartBullet/ChartBulletTitle.test.tsx | import * as React from 'react';
import { render } from '@testing-library/react';
import { ChartBulletTitle } from './ChartBulletTitle';
Object.values([true, false]).forEach(() => {
test('ChartBulletTitle', () => {
const { asFragment } = render(<ChartBulletTitle />);
expect(asFragment()).toMatchSnapshot();
});
});
test('renders component data', () => {
const { asFragment } = render(<ChartBulletTitle title="Text label" subTitle="Measure details" />);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-core/src/components/Button/examples/ButtonProgress.tsx | <filename>packages/react-core/src/components/Button/examples/ButtonProgress.tsx
import React from 'react';
import { Button } from '@patternfly/react-core';
import UploadIcon from '@patternfly/react-icons/dist/esm/icons/upload-icon';
interface LoadingPropsType {
spinnerAriaValueText: string;
spinnerAriaLabelledBy?: string;
spinnerAriaLabel?: string;
isLoading: boolean;
}
export const ButtonProgress: React.FunctionComponent = () => {
const [isPrimaryLoading, setIsPrimaryLoading] = React.useState<boolean>(true);
const [isSecondaryLoading, setIsSecondaryLoading] = React.useState<boolean>(true);
const [isUploading, setIsUploading] = React.useState<boolean>(false);
const primaryLoadingProps = {} as LoadingPropsType;
if (isPrimaryLoading) {
primaryLoadingProps.spinnerAriaValueText = 'Loading';
primaryLoadingProps.spinnerAriaLabelledBy = 'primary-loading-button';
primaryLoadingProps.isLoading = true;
}
const secondaryLoadingProps = {} as LoadingPropsType;
if (isSecondaryLoading) {
secondaryLoadingProps.spinnerAriaValueText = 'Loading';
secondaryLoadingProps.spinnerAriaLabel = 'Content being loaded';
secondaryLoadingProps.isLoading = true;
}
const uploadingProps = {} as LoadingPropsType;
if (isUploading) {
uploadingProps.spinnerAriaValueText = 'Loading';
uploadingProps.isLoading = true;
uploadingProps.spinnerAriaLabel = 'Uploading data';
}
return (
<React.Fragment>
<Button
variant="primary"
id="primary-loading-button"
onClick={() => setIsPrimaryLoading(!isPrimaryLoading)}
{...primaryLoadingProps}
>
{isPrimaryLoading ? 'Pause loading logs' : 'Resume loading logs'}
</Button>{' '}
<Button variant="secondary" onClick={() => setIsSecondaryLoading(!isSecondaryLoading)} {...secondaryLoadingProps}>
{isSecondaryLoading ? 'Click to stop loading' : 'Click to start loading'}
</Button>{' '}
<Button
variant="plain"
{...(!isUploading && { 'aria-label': 'Upload' })}
onClick={() => setIsUploading(!isUploading)}
icon={<UploadIcon />}
{...uploadingProps}
/>
<br />
<br />
</React.Fragment>
);
};
|
jelly/patternfly-react | packages/react-core/src/components/SearchInput/__tests__/SearchInput.test.tsx | import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SearchInput } from '../SearchInput';
import { FormGroup } from '../../Form';
import { Button } from '../../Button';
import { ExternalLinkSquareAltIcon } from '@patternfly/react-icons';
const props = {
onChange: jest.fn(),
value: 'test input',
onNextClick: jest.fn(),
onPreviousClick: jest.fn(),
onClear: jest.fn(),
onSearch: jest.fn()
};
describe('SearchInput', () => {
test('simple search input', () => {
const { asFragment } = render(<SearchInput {...props} aria-label="simple text input" />);
expect(asFragment()).toMatchSnapshot();
});
test('search input with hint', () => {
const { asFragment } = render(<SearchInput {...props} hint="test hint" aria-label="simple text input" />);
expect(asFragment()).toMatchSnapshot();
});
test('result count', () => {
render(<SearchInput {...props} resultsCount={3} aria-label="simple text input" data-testid="test-id" />);
expect(screen.getByTestId('test-id').querySelector('.pf-c-badge')).toBeInTheDocument();
});
test('navigable search results', () => {
render(<SearchInput {...props} resultsCount="3 / 7" aria-label="simple text input" data-testid="test-id" />);
const input = screen.getByTestId('test-id');
expect(input.querySelector('.pf-c-search-input__nav')).toBeInTheDocument();
expect(input.querySelector('.pf-c-badge')).toBeInTheDocument();
userEvent.click(screen.getByRole('button', { name: 'Previous' }));
expect(props.onPreviousClick).toHaveBeenCalled();
userEvent.click(screen.getByRole('button', { name: 'Next' }));
expect(props.onNextClick).toHaveBeenCalled();
userEvent.click(screen.getByRole('button', { name: 'Reset' }));
expect(props.onClear).toHaveBeenCalled();
});
test('hide clear button', () => {
const { onClear, ...testProps } = props;
render(<SearchInput {...testProps} resultsCount="3" aria-label="simple text input without on clear" />);
expect(screen.queryByRole('button', { name: 'Reset' })).not.toBeInTheDocument();
});
test('advanced search', () => {
const { asFragment } = render(
<SearchInput
attributes={[
{ attr: 'username', display: 'Username' },
{ attr: 'firstname', display: 'First name' }
]}
advancedSearchDelimiter=":"
value="username:player firstname:john"
onChange={props.onChange}
onSearch={props.onSearch}
onClear={props.onClear}
/>
);
userEvent.click(screen.getByRole('button', { name: 'Search' }));
expect(props.onSearch).toHaveBeenCalled();
expect(asFragment()).toMatchSnapshot();
});
test('advanced search with custom attributes', () => {
const { asFragment } = render(
<SearchInput
attributes={[
{ attr: 'username', display: 'Username' },
{ attr: 'firstname', display: 'First name' }
]}
advancedSearchDelimiter=":"
formAdditionalItems={
<FormGroup fieldId="test-form-group">
<Button variant="link" isInline icon={<ExternalLinkSquareAltIcon />} iconPosition="right">
Link
</Button>
</FormGroup>
}
value="username:player firstname:john"
onChange={props.onChange}
onSearch={props.onSearch}
onClear={props.onClear}
/>
);
userEvent.click(screen.getByRole('button', { name: 'Search' }));
expect(props.onSearch).toHaveBeenCalled();
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-core/src/components/OptionsMenu/index.ts | export * from './OptionsMenu';
export * from './OptionsMenuToggle';
export * from './OptionsMenuItemGroup';
export * from './OptionsMenuItem';
export * from './OptionsMenuSeparator';
export * from './OptionsMenuToggleWithText';
|
jelly/patternfly-react | packages/react-core/src/demos/ComposableMenu/examples/ComposableApplicationLauncher.tsx | import React from 'react';
import {
MenuToggle,
Menu,
MenuContent,
MenuList,
MenuItem,
MenuGroup,
MenuInput,
Popper,
Tooltip,
Divider,
TextInput
} from '@patternfly/react-core';
import { Link } from '@reach/router';
import ThIcon from '@patternfly/react-icons/dist/js/icons/th-icon';
import pfIcon from 'pf-logo-small.svg';
export const ComposableApplicationLauncher: React.FunctionComponent = () => {
const [isOpen, setIsOpen] = React.useState<boolean>(false);
const [refFullOptions, setRefFullOptions] = React.useState<Element[]>();
const [favorites, setFavorites] = React.useState<string[]>([]);
const [filteredIds, setFilteredIds] = React.useState<string[]>(['*']);
const menuRef = React.useRef<HTMLDivElement>();
const toggleRef = React.useRef<HTMLButtonElement>();
const containerRef = React.useRef<HTMLDivElement>();
const handleMenuKeys = (event: KeyboardEvent) => {
if (!isOpen) {
return;
}
if (menuRef.current.contains(event.target as Node) || toggleRef.current.contains(event.target as Node)) {
if (event.key === 'Escape') {
setIsOpen(!isOpen);
toggleRef.current.focus();
}
}
};
const handleClickOutside = (event: MouseEvent) => {
if (isOpen && !menuRef.current.contains(event.target as Node)) {
setIsOpen(false);
}
};
const onToggleClick = (ev: React.MouseEvent) => {
ev.stopPropagation(); // Stop handleClickOutside from handling
setTimeout(() => {
if (menuRef.current) {
const firstElement = menuRef.current.querySelector('li > button,input:not(:disabled)');
firstElement && (firstElement as HTMLElement).focus();
setRefFullOptions(Array.from(menuRef.current.querySelectorAll('li:not(li[role=separator])')));
}
}, 0);
setIsOpen(!isOpen);
};
React.useEffect(() => {
window.addEventListener('keydown', handleMenuKeys);
window.addEventListener('click', handleClickOutside);
return () => {
window.removeEventListener('keydown', handleMenuKeys);
window.removeEventListener('click', handleClickOutside);
};
}, [isOpen, menuRef]);
const toggle = (
<MenuToggle
aria-label="Toggle"
ref={toggleRef}
variant="plain"
onClick={onToggleClick}
isExpanded={isOpen}
style={{ width: 'auto' }}
>
<ThIcon />
</MenuToggle>
);
const menuItems = [
<MenuGroup key="group1" label="Group 1">
<MenuList>
<MenuItem itemId="0" id="0" isFavorited={favorites.includes('0')}>
Application 1
</MenuItem>
<MenuItem
itemId="1"
id="1"
isFavorited={favorites.includes('1')}
to="#default-link2"
onClick={ev => ev.preventDefault()}
>
Application 2
</MenuItem>
</MenuList>
</MenuGroup>,
<Divider key="group1-divider" />,
<MenuGroup key="group2" label="Group 2">
<MenuList>
<MenuItem
itemId="2"
id="2"
isFavorited={favorites.includes('2')}
component={props => <Link {...props} to="#router-link" />}
>
@reach/router Link
</MenuItem>
<MenuItem
itemId="3"
id="3"
isFavorited={favorites.includes('3')}
isExternalLink
icon={<img src={pfIcon} />}
component={props => <Link {...props} to="#router-link2" />}
>
@reach/router Link with icon
</MenuItem>
</MenuList>
</MenuGroup>,
<Divider key="group2-divider" />,
<MenuList key="other-items">
<MenuItem key="tooltip-app" isFavorited={favorites.includes('4')} itemId="4" id="4">
<Tooltip content={<div>Launch Application 3</div>} position="right">
<span>Application 3 with tooltip</span>
</Tooltip>
</MenuItem>
<MenuItem key="disabled-app" itemId="5" id="5" isDisabled>
Unavailable Application
</MenuItem>
</MenuList>
];
const createFavorites = (favIds: string[]) => {
const favorites = [];
menuItems.forEach(item => {
if (item.type === MenuList) {
item.props.children.filter(child => {
if (favIds.includes(child.props.itemId)) {
favorites.push(child);
}
});
} else if (item.type === MenuGroup) {
item.props.children.props.children.filter(child => {
if (favIds.includes(child.props.itemId)) {
favorites.push(child);
}
});
} else {
if (favIds.includes(item.props.itemId)) {
favorites.push(item);
}
}
});
return favorites;
};
const filterItems = (items: any[], filteredIds: string[]) => {
if (filteredIds.length === 1 && filteredIds[0] === '*') {
return items;
}
let keepDivider = false;
const filteredCopy = items
.map(group => {
if (group.type === MenuGroup) {
const filteredGroup = React.cloneElement(group, {
children: React.cloneElement(group.props.children, {
children: group.props.children.props.children.filter(child => {
if (filteredIds.includes(child.props.itemId)) {
return child;
}
})
})
});
const filteredList = filteredGroup.props.children;
if (filteredList.props.children.length > 0) {
keepDivider = true;
return filteredGroup;
} else {
keepDivider = false;
}
} else if (group.type === MenuList) {
const filteredGroup = React.cloneElement(group, {
children: group.props.children.filter(child => {
if (filteredIds.includes(child.props.itemId)) {
return child;
}
})
});
if (filteredGroup.props.children.length > 0) {
keepDivider = true;
return filteredGroup;
} else {
keepDivider = false;
}
} else {
if ((keepDivider && group.type === Divider) || filteredIds.includes(group.props.itemId)) {
return group;
}
}
})
.filter(newGroup => newGroup);
if (filteredCopy.length > 0) {
const lastGroup = filteredCopy.pop();
if (lastGroup.type !== Divider) {
filteredCopy.push(lastGroup);
}
}
return filteredCopy;
};
const onTextChange = (textValue: string) => {
if (textValue === '') {
setFilteredIds(['*']);
return;
}
const filteredIds = refFullOptions
.filter(item => (item as HTMLElement).innerText.toLowerCase().includes(textValue.toString().toLowerCase()))
.map(item => item.id);
setFilteredIds(filteredIds);
};
const onFavorite = (event: any, itemId: string, actionId: string) => {
event.stopPropagation();
if (actionId === 'fav') {
const isFavorite = favorites.includes(itemId);
if (isFavorite) {
setFavorites(favorites.filter(fav => fav !== itemId));
} else {
setFavorites([...favorites, itemId]);
}
}
};
const filteredFavorites = filterItems(createFavorites(favorites), filteredIds);
const filteredItems = filterItems(menuItems, filteredIds);
if (filteredItems.length === 0) {
filteredItems.push(<MenuItem key="no-items">No results found</MenuItem>);
}
const menu = (
// eslint-disable-next-line no-console
<Menu ref={menuRef} onActionClick={onFavorite} onSelect={(_ev, itemId) => console.log('selected', itemId)}>
<MenuInput>
<TextInput
aria-label="Filter menu items"
iconVariant="search"
type="search"
onChange={value => onTextChange(value)}
/>
</MenuInput>
<Divider />
<MenuContent>
{filteredFavorites.length > 0 && (
<React.Fragment>
<MenuGroup key="favorites-group" label="Favorites">
<MenuList>{filteredFavorites}</MenuList>
</MenuGroup>
<Divider key="favorites-divider" />
</React.Fragment>
)}
{filteredItems}
</MenuContent>
</Menu>
);
return (
<div ref={containerRef}>
<Popper
trigger={toggle}
popper={menu}
isVisible={isOpen}
popperMatchesTriggerWidth={false}
appendTo={containerRef.current}
/>
</div>
);
};
|
jelly/patternfly-react | packages/react-core/src/components/ToggleGroup/__tests__/ToggleGroup.test.tsx | import * as React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ToggleGroup } from '../ToggleGroup';
import { ToggleGroupItem } from '../ToggleGroupItem';
const props = {
onChange: jest.fn(),
selected: false
};
describe('ToggleGroup', () => {
test('basic selected', () => {
const { asFragment } = render(
<ToggleGroupItem text="test" isSelected buttonId="toggleGroupItem" aria-label="basic selected" />
);
expect(asFragment()).toMatchSnapshot();
});
test('basic not selected', () => {
const { asFragment } = render(
<ToggleGroupItem text="test" buttonId="toggleGroupItem" aria-label="basic not selected" />
);
expect(asFragment()).toMatchSnapshot();
});
test('icon variant', () => {
const { asFragment } = render(
<ToggleGroupItem isSelected icon="icon" buttonId="toggleGroupItem" aria-label="icon variant" />
);
expect(asFragment()).toMatchSnapshot();
});
test('isDisabled', () => {
const { asFragment } = render(
<ToggleGroupItem text="test" isDisabled buttonId="toggleGroupItem" aria-label="isDisabled" />
);
expect(asFragment()).toMatchSnapshot();
});
test('item passes selection and event to onChange handler', () => {
render(
<ToggleGroupItem text="test" buttonId="toggleGroupItem" onChange={props.onChange} aria-label="onChange handler" />
);
userEvent.click(screen.getByRole('button'));
expect(props.onChange).toHaveBeenCalledWith(true, expect.any(Object));
});
test('isCompact', () => {
const { asFragment } = render(
<ToggleGroup isCompact aria-label="Label">
<ToggleGroupItem text="Test" />
<ToggleGroupItem text="Test" />
</ToggleGroup>
);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyInlineCompactWithAdditionalAction.tsx | <reponame>jelly/patternfly-react<filename>packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyInlineCompactWithAdditionalAction.tsx
import React from 'react';
import { ClipboardCopy, ClipboardCopyAction, Button } from '@patternfly/react-core';
import PlayIcon from '@patternfly/react-icons/dist/esm/icons/play-icon';
export const ClipboardCopyInlineCompactWithAdditionalAction: React.FunctionComponent = () => (
<ClipboardCopy
hoverTip="Copy"
clickTip="Copied"
variant="inline-compact"
additionalActions={
<ClipboardCopyAction>
<Button variant="plain" aria-label="Run in web terminal">
<PlayIcon aria-hidden />
</Button>
</ClipboardCopyAction>
}
>
2.3.4-2-redhat
</ClipboardCopy>
);
|
jelly/patternfly-react | packages/react-core/src/components/Card/CardHeaderMain.tsx | <gh_stars>100-1000
import * as React from 'react';
export interface CardHeaderMainProps extends React.HTMLProps<HTMLDivElement> {
/** Content rendered inside the Card Head Main */
children?: React.ReactNode;
/** Additional classes added to the Card Head Main */
className?: string;
}
export const CardHeaderMain: React.FunctionComponent<CardHeaderMainProps> = ({
children = null,
className = '',
...props
}: CardHeaderMainProps) => (
<div className={className} {...props}>
{children}
</div>
);
CardHeaderMain.displayName = 'CardHeaderMain';
|
jelly/patternfly-react | packages/react-charts/src/components/ChartTheme/styles/donut-utilization-styles.ts | <reponame>jelly/patternfly-react
/* eslint-disable camelcase */
import chart_donut_threshold_warning_Color from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_warning_Color';
import chart_donut_threshold_danger_Color from '@patternfly/react-tokens/dist/esm/chart_donut_threshold_danger_Color';
// Donut utilization styles
export const DonutUtilizationStyles = {
thresholds: {
colorScale: [chart_donut_threshold_warning_Color.value, chart_donut_threshold_danger_Color.value]
}
};
|
jelly/patternfly-react | packages/react-core/src/components/AlertGroup/examples/AlertGroupStatic.tsx | <gh_stars>0
import React from 'react';
import { Alert, AlertGroup } from '@patternfly/react-core';
export const AlertGroupStatic: React.FunctionComponent = () => (
<React.Fragment>
<AlertGroup>
<Alert title="Success alert" variant="success" isInline />
<Alert title="Info alert" variant="info" isInline />
</AlertGroup>
</React.Fragment>
);
|
jelly/patternfly-react | packages/react-core/src/components/OptionsMenu/__tests__/Generated/OptionsMenuItem.test.tsx | <gh_stars>0
import React from 'react';
import { render } from '@testing-library/react';
import { OptionsMenuItem } from '../../OptionsMenuItem';
import { DropdownArrowContext } from '../../../Dropdown';
describe('OptionsMenuItem', () => {
it('should match snapshot', () => {
const { asFragment } = render(
<DropdownArrowContext.Provider value={{ sendRef: jest.fn(), keyHandler: undefined }}>
<OptionsMenuItem
children={<>ReactNode</>}
className={'string'}
isSelected={false}
isDisabled={true}
onSelect={() => null as any}
id={"''"}
/>{' '}
</DropdownArrowContext.Provider>
);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-core/src/components/ActionList/ActionListItem.tsx | import * as React from 'react';
import { css } from '@patternfly/react-styles';
export interface ActionListItemProps extends React.HTMLProps<HTMLDivElement> {
/** Children of the action list item */
children?: React.ReactNode;
/** Additional classes added to the action list item */
className?: string;
}
export const ActionListItem: React.FunctionComponent<ActionListItemProps> = ({
children,
className = '',
...props
}: ActionListItemProps) => (
<div className={css('pf-c-action-list__item', className)} {...props}>
{children}
</div>
);
ActionListItem.displayName = 'ActionListItem';
|
jelly/patternfly-react | packages/react-inline-edit-extension/src/utils/formatters.ts | <reponame>jelly/patternfly-react<filename>packages/react-inline-edit-extension/src/utils/formatters.ts
export * from './formatters/inlineEditFormatterFactory';
|
jelly/patternfly-react | packages/react-core/src/components/LabelGroup/__tests__/LabelGroup.test.tsx | <gh_stars>0
import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Label } from '../../Label';
import { LabelGroup } from '../index';
describe('LabelGroup', () => {
test('label group default', () => {
const { asFragment } = render(
<LabelGroup>
<Label>1.1</Label>
</LabelGroup>
);
expect(asFragment()).toMatchSnapshot();
});
test('label group with category', () => {
const { asFragment } = render(
<LabelGroup categoryName="category">
<Label>1.1</Label>
</LabelGroup>
);
expect(asFragment()).toMatchSnapshot();
});
test('label group with closable category', () => {
const { asFragment } = render(
<LabelGroup categoryName="category" isClosable>
<Label>1.1</Label>
</LabelGroup>
);
expect(asFragment()).toMatchSnapshot();
});
test('label group expanded', () => {
render(
<LabelGroup>
<Label>1</Label>
<Label>2</Label>
<Label>3</Label>
<Label>4</Label>
</LabelGroup>
);
const showMoreButton = screen.getByRole('button');
expect(showMoreButton.textContent).toBe('1 more');
userEvent.click(showMoreButton);
expect(showMoreButton.textContent).toBe('Show Less');
});
test('label group will not render if no children passed', () => {
render(<LabelGroup data-testid="label-group-test-id" />);
expect(screen.queryByTestId('label-group-test-id')).toBeNull();
});
// TODO, fix test - no tooltip shows up with this categoryName.zzw
test('label group with category and tooltip', () => {
const { asFragment } = render(
<LabelGroup categoryName="A very long category name">
<Label>1.1</Label>
</LabelGroup>
);
expect(asFragment()).toMatchSnapshot();
});
test('label group compact', () => {
const { asFragment } = render(
<LabelGroup isCompact>
<Label isCompact>1</Label>
<Label isCompact>2</Label>
<Label isCompact>3</Label>
<Label isCompact>4</Label>
</LabelGroup>
);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-core/src/components/Card/examples/CardHeaderInCardHead.tsx | <filename>packages/react-core/src/components/Card/examples/CardHeaderInCardHead.tsx
import React from 'react';
import {
Card,
CardHeader,
CardActions,
CardTitle,
CardBody,
CardFooter,
Checkbox,
Dropdown,
DropdownItem,
DropdownSeparator,
KebabToggle
} from '@patternfly/react-core';
export const CardTitleInHeader: React.FunctionComponent = () => {
const [isOpen, setIsOpen] = React.useState<boolean>(false);
const [isChecked, setIsChecked] = React.useState<boolean>(false);
const onSelect = () => {
setIsOpen(!isOpen);
};
const onClick = (checked: boolean) => {
setIsChecked(checked);
};
const dropdownItems = [
<DropdownItem key="link">Link</DropdownItem>,
<DropdownItem key="action" component="button">
Action
</DropdownItem>,
<DropdownItem key="disabled link" isDisabled>
Disabled Link
</DropdownItem>,
<DropdownItem key="disabled action" isDisabled component="button">
Disabled Action
</DropdownItem>,
<DropdownSeparator key="separator" />,
<DropdownItem key="separated link">Separated Link</DropdownItem>,
<DropdownItem key="separated action" component="button">
Separated Action
</DropdownItem>
];
return (
<Card>
<CardHeader>
<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-2"
name="check2"
/>
</CardActions>
<CardTitle>
This is a really really really really really really really really really really long header
</CardTitle>
</CardHeader>
<CardBody>Body</CardBody>
<CardFooter>Footer</CardFooter>
</Card>
);
};
|
jelly/patternfly-react | packages/react-topology/src/components/TopologySideBar/TopologySideBar.tsx | <reponame>jelly/patternfly-react
import * as React from 'react';
import { css } from '@patternfly/react-styles';
import styles from '@patternfly/react-styles/css/components/Topology/topology-side-bar';
import TimesIcon from '@patternfly/react-icons/dist/esm/icons/times-icon';
import { Button } from '@patternfly/react-core';
export interface TopologySideBarProps {
/** Additional classes added to the sidebar */
className?: string;
/** Contents for the sidebar */
children?: React.ReactNode;
/** Flag if sidebar is being used in a resizable drawer (default false) */
resizable?: boolean;
/** Not used for resizeable side bars */
show?: boolean;
/** A callback for closing the sidebar, if provided the close button will be displayed in the sidebar */
onClose?: () => void;
/** Component to place in the header of the sidebar */
header?: React.ReactNode;
}
export const TopologySideBar: React.FunctionComponent<TopologySideBarProps> = ({
className = '',
resizable = false,
show,
onClose = null,
header,
children = null,
...otherProps
}) => {
const [isIn, setIsIn] = React.useState<boolean>(false);
React.useEffect(() => {
let timer: any = null;
if (isIn !== show) {
clearTimeout(timer);
timer = setTimeout(() => setIsIn(show), 150);
}
return () => {
clearTimeout(timer);
};
}, [show, isIn]);
const classNames = resizable
? css(styles.topologyResizableSideBar, className)
: css(styles.topologySideBar, 'fade', className, show && styles.shown, isIn && styles.in);
return (
<div {...otherProps} role="dialog" className={classNames}>
{(resizable || show) && (
<React.Fragment>
{onClose && (
<Button
className={css(styles.topologySideBarDismiss)}
variant="plain"
onClick={onClose as any}
aria-label="Close"
>
<TimesIcon />
</Button>
)}
{header && <div className={css(styles.topologySideBarHeader)}>{header}</div>}
{children}
</React.Fragment>
)}
</div>
);
};
TopologySideBar.displayName = 'TopologySideBar';
|
jelly/patternfly-react | packages/react-core/src/components/DescriptionList/DescriptionListTermHelpTextButton.tsx | <filename>packages/react-core/src/components/DescriptionList/DescriptionListTermHelpTextButton.tsx<gh_stars>100-1000
import * as React from 'react';
import styles from '@patternfly/react-styles/css/components/DescriptionList/description-list';
import { css } from '@patternfly/react-styles';
export interface DescriptionListTermHelpTextButtonProps extends React.HTMLProps<HTMLSpanElement> {
/** Anything that can be rendered inside of list term */
children: React.ReactNode;
/** Additional classes added to the DescriptionListTerm */
className?: string;
}
export const DescriptionListTermHelpTextButton: React.FunctionComponent<DescriptionListTermHelpTextButtonProps> = ({
children,
className,
...props
}: DescriptionListTermHelpTextButtonProps) => (
<span
className={css(className, styles.descriptionListText, styles.modifiers.helpText)}
role="button"
type="button"
tabIndex={0}
{...props}
>
{children}
</span>
);
DescriptionListTermHelpTextButton.displayName = 'DescriptionListTermHelpTextButton';
|
jelly/patternfly-react | packages/react-table/src/components/Table/examples/LegacyTableTree.tsx | import React from 'react';
import {
Table,
TableHeader,
TableBody,
treeRow,
IRow,
OnTreeRowCollapse,
OnCheckChange,
OnToggleRowDetails
} from '@patternfly/react-table';
import LeafIcon from '@patternfly/react-icons/dist/esm/icons/leaf-icon';
import FolderIcon from '@patternfly/react-icons/dist/esm/icons/folder-icon';
import FolderOpenIcon from '@patternfly/react-icons/dist/esm/icons/folder-open-icon';
interface RepositoriesTreeNode {
name: string;
branches: string;
pullRequests: string;
workspaces: string;
children?: RepositoriesTreeNode[];
}
export const LegacyTableTree: React.FunctionComponent = () => {
// In real usage, this data would come from some external source like an API via props.
const data: RepositoriesTreeNode[] = [
{
name: 'Repositories one',
branches: 'Branch one',
pullRequests: 'Pull request one',
workspaces: 'Workplace one',
children: [
{
name: 'Repositories two',
branches: 'Branch two',
pullRequests: 'Pull request two',
workspaces: 'Workplace two',
children: [
{
name: 'Repositories three',
branches: 'Branch three',
pullRequests: 'Pull request three',
workspaces: 'Workplace three'
},
{
name: 'Repositories four',
branches: 'Branch four',
pullRequests: 'Pull request four',
workspaces: 'Workplace four'
}
]
},
{
name: 'Repositories five',
branches: 'Branch five',
pullRequests: 'Pull request five',
workspaces: 'Workplace five'
},
{
name: 'Repositories six',
branches: 'Branch six',
pullRequests: 'Pull request six',
workspaces: 'Workplace six'
}
]
},
{
name: 'Repositories seven',
branches: 'Branch seven',
pullRequests: 'Pull request seven',
workspaces: 'Workplace seven',
children: [
{
name: 'Repositories eight',
branches: 'Branch eight',
pullRequests: 'Pull request eight',
workspaces: 'Workplace eight'
}
]
},
{
name: 'Repositories nine',
branches: 'Branch nine',
pullRequests: 'Pull request nine',
workspaces: 'Workplace nine'
}
];
const [expandedNodeNames, setExpandedNodeNames] = React.useState<string[]>(['Repositories one']);
const [expandedDetailsNodeNames, setExpandedDetailsNodeNames] = React.useState<string[]>([]);
const [selectedNodeNames, setSelectedNodeNames] = React.useState<string[]>([]);
const getDescendants = (node: RepositoriesTreeNode): RepositoriesTreeNode[] =>
[node].concat(...(node.children ? node.children.map(getDescendants) : []));
const areAllDescendantsSelected = (node: RepositoriesTreeNode) =>
getDescendants(node).every(n => selectedNodeNames.includes(n.name));
const areSomeDescendantsSelected = (node: RepositoriesTreeNode) =>
getDescendants(node).some(n => selectedNodeNames.includes(n.name));
const isNodeChecked = (node: RepositoriesTreeNode) => {
if (areAllDescendantsSelected(node)) {
return true;
}
if (areSomeDescendantsSelected(node)) {
return null;
}
return false;
};
// We index the tree nodes in the order of the table rows, for looking up by rowIndex
const flattenedNodes: RepositoriesTreeNode[] = [];
/**
Recursive function which flattens the data into an array of flattened IRow objects
params:
- nodes - array of a single level of tree nodes
- level - number representing how deeply nested the current row is
- posinset - position of the row relative to this row's siblings
- isHidden - defaults to false, true if this row's parent is expanded
- currentRowIndex - position of the row relative to the entire table
*/
const buildRows = (
[node, ...remainingNodes]: RepositoriesTreeNode[],
level = 1,
posinset = 1,
rowIndex = 0,
isHidden = false
): IRow[] => {
if (!node) {
return [];
}
const isExpanded = expandedNodeNames.includes(node.name);
const isDetailsExpanded = expandedDetailsNodeNames.includes(node.name);
const isChecked = isNodeChecked(node);
let icon = <LeafIcon />;
if (node.children) {
icon = isExpanded ? <FolderOpenIcon aria-hidden /> : <FolderIcon aria-hidden />;
}
flattenedNodes.push(node);
const childRows =
node.children && node.children.length
? buildRows(node.children, level + 1, 1, rowIndex + 1, !isExpanded || isHidden)
: [];
return [
{
cells: [node.name, node.branches, node.pullRequests, node.workspaces],
props: {
isExpanded,
isDetailsExpanded,
isHidden,
'aria-level': level,
'aria-posinset': posinset,
'aria-setsize': node.children ? node.children.length : 0,
isChecked,
icon
}
},
...childRows,
...buildRows(remainingNodes, level, posinset + 1, rowIndex + 1 + childRows.length, isHidden)
];
};
const onCollapse: OnTreeRowCollapse = (_event, rowIndex) => {
const node = flattenedNodes[rowIndex];
const isExpanded = expandedNodeNames.includes(node.name);
setExpandedNodeNames(prevExpanded => {
const otherExpandedNodeNames = prevExpanded.filter(name => name !== node.name);
return isExpanded ? otherExpandedNodeNames : [...otherExpandedNodeNames, node.name];
});
};
const onCheck: OnCheckChange = (_event, isChecking, rowIndex) => {
const node = flattenedNodes[rowIndex];
const nodeNamesToCheck = getDescendants(node).map(n => n.name);
setSelectedNodeNames(prevSelected => {
const otherSelectedNodeNames = prevSelected.filter(name => !nodeNamesToCheck.includes(name));
return !isChecking ? otherSelectedNodeNames : [...otherSelectedNodeNames, ...nodeNamesToCheck];
});
};
const onToggleRowDetails: OnToggleRowDetails = (_event, rowIndex) => {
const node = flattenedNodes[rowIndex];
const isDetailsExpanded = expandedDetailsNodeNames.includes(node.name);
setExpandedDetailsNodeNames(prevDetailsExpanded => {
const otherDetailsExpandedNodeNames = prevDetailsExpanded.filter(name => name !== node.name);
return isDetailsExpanded ? otherDetailsExpandedNodeNames : [...otherDetailsExpandedNodeNames, node.name];
});
};
return (
<Table
isTreeTable
aria-label="Tree table"
cells={[
{
title: 'Repositories',
cellTransforms: [treeRow(onCollapse, onCheck, onToggleRowDetails)]
},
'Branches',
'Pull requests',
'Workspaces'
]}
rows={buildRows(data)}
>
<TableHeader />
<TableBody />
</Table>
);
};
|
jelly/patternfly-react | packages/react-core/src/components/Tabs/__tests__/Tab.test.tsx | <reponame>jelly/patternfly-react
import React from 'react';
import { render } from '@testing-library/react';
import { Tab } from '../Tab';
import { TabTitleText } from '../TabTitleText';
test('should not render anything', () => {
const { asFragment } = render(
<Tab eventKey={0} title={<TabTitleText>"Tab item 1"</TabTitleText>}>
Tab 1 section
</Tab>
);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-catalog-view-extension/src/components/CatalogItemHeader/CatalogItemHeader.test.tsx | import { CatalogItemHeader } from './CatalogItemHeader';
import React from 'react';
import { render } from '@testing-library/react';
test('simple catalog item header', () => {
const { asFragment } = render(
<CatalogItemHeader
title="PatternFly"
vendor={
<span>
provided by <a href="redhat.com">Red Hat</a>
</span>
}
/>
);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-core/src/layouts/Stack/__tests__/Stack.test.tsx | import * as React from 'react';
import { render } from '@testing-library/react';
import { Stack } from '../Stack';
import { StackItem } from '../StackItem';
test('isMain set to true', () => {
const { asFragment } = render(
<Stack>
<StackItem isFilled>Filled content</StackItem>
</Stack>
);
expect(asFragment()).toMatchSnapshot();
});
test('isMain defaults to false', () => {
const { asFragment } = render(
<Stack>
<StackItem>Basic content</StackItem>
</Stack>
);
expect(asFragment()).toMatchSnapshot();
});
test('gutter', () => {
const { asFragment } = render(
<Stack hasGutter>
<StackItem>Basic content</StackItem>
</Stack>
);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-core/src/components/HelperText/HelperText.tsx | <gh_stars>0
import * as React from 'react';
import styles from '@patternfly/react-styles/css/components/HelperText/helper-text';
import { css } from '@patternfly/react-styles';
export interface HelperTextProps extends React.HTMLProps<HTMLDivElement | HTMLUListElement> {
/** Content rendered inside the helper text container. */
children?: React.ReactNode;
/** Additional classes applied to the helper text container. */
className?: string;
/** Component type of the helper text container */
component?: 'div' | 'ul';
/** ID for the helper text container. The value of this prop can be passed into a form component's
* aria-describedby prop when you intend for all helper text items to be announced to
* assistive technologies.
*/
id?: string;
/** Flag for indicating whether the helper text container is a live region. Use this prop when you
* expect or intend for any helper text items within the container to be dynamically updated.
*/
isLiveRegion?: boolean;
}
export const HelperText: React.FunctionComponent<HelperTextProps> = ({
children,
className,
component = 'div',
id,
isLiveRegion = false,
...props
}: HelperTextProps) => {
const Component = component as any;
return (
<Component
id={id}
className={css(styles.helperText, className)}
{...(isLiveRegion && { 'aria-live': 'polite' })}
{...props}
>
{children}
</Component>
);
};
HelperText.displayName = 'HelperText';
|
jelly/patternfly-react | packages/react-core/src/components/Alert/AlertContext.ts | import * as React from 'react';
interface AlertContext {
title: React.ReactNode;
variantLabel?: string;
}
export const AlertContext = React.createContext<AlertContext>(null);
|
jelly/patternfly-react | packages/react-core/src/components/Badge/examples/BadgeRead.tsx | <reponame>jelly/patternfly-react
import React from 'react';
import { Badge } from '@patternfly/react-core';
export const BadgeRead: React.FunctionComponent = () => (
<React.Fragment>
<Badge key={1} isRead>
7
</Badge>{' '}
<Badge key={2} isRead>
24
</Badge>{' '}
<Badge key={3} isRead>
240
</Badge>{' '}
<Badge key={4} isRead>
999+
</Badge>
</React.Fragment>
);
|
jelly/patternfly-react | packages/react-core/src/components/LoginPage/Login.tsx | import * as React from 'react';
import styles from '@patternfly/react-styles/css/components/Login/login';
import { css } from '@patternfly/react-styles';
export interface LoginProps extends React.HTMLProps<HTMLDivElement> {
/** Content rendered inside the main section of the login layout */
children?: React.ReactNode;
/** Additional classes added to the login layout */
className?: string;
/** Footer component (e.g. <LoginFooter />) */
footer?: React.ReactNode;
/** Header component (e.g. <LoginHeader />) */
header?: React.ReactNode;
}
export const Login: React.FunctionComponent<LoginProps> = ({
className = '',
children = null,
footer = null,
header = null,
...props
}: LoginProps) => (
<div {...props} className={css(styles.login, className)}>
<div className={css(styles.loginContainer)}>
{header}
<main className={css(styles.loginMain)}>{children}</main>
{footer}
</div>
</div>
);
Login.displayName = 'Login';
|
jelly/patternfly-react | packages/react-core/src/components/Dropdown/__tests__/DropdownToggleCheckbox.test.tsx | import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DropdownToggleCheckbox } from '../DropdownToggleCheckbox';
const props = {
onChange: jest.fn(),
isChecked: false
};
describe('DropdownToggleCheckbox', () => {
test('controlled', () => {
const { asFragment } = render(<DropdownToggleCheckbox isChecked id="check" aria-label="check" />);
expect(asFragment()).toMatchSnapshot();
});
test('uncontrolled', () => {
const { asFragment } = render(<DropdownToggleCheckbox id="check" aria-label="check" />);
expect(asFragment()).toMatchSnapshot();
});
test('with text', () => {
const { asFragment } = render(
<DropdownToggleCheckbox id="check" isDisabled aria-label="check">
Some text
</DropdownToggleCheckbox>
);
expect(asFragment()).toMatchSnapshot();
});
test('isDisabled', () => {
const { asFragment } = render(<DropdownToggleCheckbox id="check" isDisabled aria-label="check" />);
expect(asFragment()).toMatchSnapshot();
});
test('3rd state', () => {
const { asFragment } = render(<DropdownToggleCheckbox id="check" isChecked={null} aria-label="check" />);
expect(asFragment()).toMatchSnapshot();
});
test('passing class', () => {
const { asFragment } = render(
<DropdownToggleCheckbox label="label" className="class-123" id="check" isChecked aria-label="check" />
);
expect(asFragment()).toMatchSnapshot();
});
test('passing HTML attribute', () => {
const { asFragment } = render(
<DropdownToggleCheckbox label="label" aria-labelledby="labelId" id="check" isChecked aria-label="check" />
);
expect(asFragment()).toMatchSnapshot();
});
test('checkbox passes value and event to onChange handler', () => {
render(<DropdownToggleCheckbox id="check" {...props} aria-label="check" />);
userEvent.click(screen.getByRole('checkbox'));
expect(props.onChange).toHaveBeenCalledWith(true, expect.any(Object));
});
});
|
jelly/patternfly-react | packages/react-topology/src/components/TopologyView/TopologyView.tsx | <reponame>jelly/patternfly-react
import * as React from 'react';
import {
Drawer,
DrawerContent,
DrawerContentBody,
DrawerPanelContent,
Toolbar,
ToolbarContent,
ToolbarGroup,
Divider,
GenerateId,
Stack,
StackItem
} from '@patternfly/react-core';
import { css } from '@patternfly/react-styles';
import styles from '@patternfly/react-styles/css/components/Topology/topology-view';
import sideBarStyles from '@patternfly/react-styles/css/components/Topology/topology-side-bar';
import controlBarStyles from '@patternfly/react-styles/css/components/Topology/topology-controlbar';
export interface TopologyViewProps extends React.HTMLProps<HTMLDivElement> {
/** Additional classes added to the view */
className?: string;
/** Topology inner container (canvas) */
children?: React.ReactNode;
/** Context toolbar to be displayed at the top of the view, should contain components for changing context */
contextToolbar?: React.ReactNode;
/** View toolbar to be displayed below the context toolbar, should contain components for changing view contents */
viewToolbar?: React.ReactNode;
/** Topology control bar (typically a TopologyControlBar), used to manipulate the graph layout */
controlBar?: React.ReactNode;
/** Topology side bar (typically a TopologySideBar), used to display information for elements in graph */
sideBar?: React.ReactNode;
/** Flag if side bar is open */
sideBarOpen?: boolean;
/** Flag if side bar is resizable, default false */
sideBarResizable?: boolean;
/** The starting size of the side bar, in either pixels or percentage, only used if resizable. */
defaultSideBarSize?: string;
/** The minimum size of the side bar, in either pixels or percentage. */
minSideBarSize?: string;
/** The maximum size of the side bar, in either pixels or percentage. */
maxSideBarSize?: string;
/** Callback for side bar resize end. */
onSideBarResize?: (width: number, id: string) => void;
}
export const TopologyView: React.FunctionComponent<TopologyViewProps> = ({
className = '',
contextToolbar = null,
viewToolbar = null,
children = null,
controlBar = null,
sideBar = null,
sideBarResizable = false,
sideBarOpen = false,
defaultSideBarSize = '500px',
minSideBarSize = '150px',
maxSideBarSize = '100%',
onSideBarResize,
...props
}: TopologyViewProps) => {
const topologyContent = !sideBarResizable ? (
<StackItem
isFilled
className={css(
styles.topologyContainer,
sideBar && sideBarStyles.topologyContainerWithSidebar,
sideBarOpen && sideBarStyles.topologyContainerWithSidebarOpen
)}
>
<div className={css(styles.topologyContent)}>
{children}
{controlBar && <span className={css(controlBarStyles.topologyControlBar)}>{controlBar}</span>}
</div>
{sideBar}
</StackItem>
) : (
<StackItem isFilled className={css(styles.topologyContainer)}>
<Drawer isExpanded={sideBarOpen} isInline>
<DrawerContent
panelContent={
<DrawerPanelContent
isResizable={sideBarResizable}
id="topology-resize-panel"
defaultSize={defaultSideBarSize}
minSize={minSideBarSize}
maxSize={maxSideBarSize}
onResize={onSideBarResize}
>
{sideBar}
</DrawerPanelContent>
}
>
<DrawerContentBody>
<div className={css(styles.topologyContent)}>
{children}
{controlBar && <span className={css(controlBarStyles.topologyControlBar)}>{controlBar}</span>}
</div>
</DrawerContentBody>
</DrawerContent>
</Drawer>
</StackItem>
);
return (
<Stack className={className} {...props}>
{contextToolbar || viewToolbar ? (
<StackItem isFilled={false}>
<GenerateId prefix="pf-topology-view-">
{randomId => (
<Toolbar id={randomId}>
{contextToolbar && (
<ToolbarContent>
<ToolbarGroup className="pf-topology-view__project-toolbar">{contextToolbar}</ToolbarGroup>
</ToolbarContent>
)}
{viewToolbar && (
<ToolbarContent>
<ToolbarGroup className="pf-topology-view__view-toolbar">{viewToolbar}</ToolbarGroup>
</ToolbarContent>
)}
<Divider />
</Toolbar>
)}
</GenerateId>
</StackItem>
) : null}
{topologyContent}
</Stack>
);
};
TopologyView.displayName = 'TopologyView';
|
jelly/patternfly-react | packages/react-integration/cypress/integration/numberInput.spec.ts | <reponame>jelly/patternfly-react
describe('NumberInput Demo Test', () => {
it('Navigate to numberInput section', () => {
cy.visit('http://localhost:3000/numberInput-demo-nav-link');
});
it('has initial value of 0 & shows min threshold', () => {
cy.get('#input1').should('have.value', 0);
cy.get('#minus-button').should('be.disabled');
cy.get('#plus-button').should('not.be.disabled');
});
it('can be incremented with the plus button & shows max threshold', () => {
cy.get('#plus-button').click();
cy.get('#minus-button').should('not.be.disabled');
cy.get('#input1').should('have.value', 1);
cy.get('#plus-button').click();
cy.get('#plus-button').click();
cy.get('#input1').should('have.value', 3);
cy.get('#plus-button').should('be.disabled');
});
it('can be decremented with the minus button', () => {
cy.get('#minus-button').click();
cy.get('#input1').should('have.value', 2);
cy.get('#minus-button').should('not.be.disabled');
cy.get('#plus-button').should('not.be.disabled');
});
it('can be manually set with input', () => {
cy.get('#input1')
.type('{selectall}')
.type('1');
cy.get('#input1').should('have.value', 1);
cy.get('#minus-button').should('not.be.disabled');
cy.get('#plus-button').should('not.be.disabled');
});
it('is properly disabled', () => {
cy.get('#input2').should('be.disabled');
cy.get('#minus-button2').should('be.disabled');
cy.get('#plus-button2').should('be.disabled');
});
it('can have different unit positions', () => {
cy.get('#numberInput1')
.children()
.first()
.should('have.class', 'pf-c-input-group');
cy.get('#numberInput1')
.children()
.last()
.should('have.class', 'pf-c-number-input__unit');
cy.get('#numberInput2')
.children()
.first()
.should('have.class', 'pf-c-number-input__unit');
cy.get('#numberInput2')
.children()
.last()
.should('have.class', 'pf-c-input-group');
});
});
|
jelly/patternfly-react | packages/react-core/src/components/ApplicationLauncher/__tests__/Generated/ApplicationLauncherSeparator.test.tsx | import React from 'react';
import { render } from '@testing-library/react';
import { ApplicationLauncherSeparator } from '../../ApplicationLauncherSeparator';
import { DropdownArrowContext } from '../../../Dropdown/dropdownConstants';
describe('ApplicationLauncherSeparator', () => {
it('should match snapshot', () => {
const { asFragment } = render(
<DropdownArrowContext.Provider value={{ sendRef: jest.fn(), keyHandler: undefined }}>
<ApplicationLauncherSeparator />
</DropdownArrowContext.Provider>
);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-core/src/components/DescriptionList/DescriptionListTermHelpText.tsx | <gh_stars>100-1000
import * as React from 'react';
import styles from '@patternfly/react-styles/css/components/DescriptionList/description-list';
import { css } from '@patternfly/react-styles';
export interface DescriptionListTermHelpTextProps extends React.HTMLProps<HTMLElement> {
/** Anything that can be rendered inside of list term */
children: React.ReactNode;
/** Additional classes added to the DescriptionListTermHelpText */
className?: string;
}
export const DescriptionListTermHelpText: React.FunctionComponent<DescriptionListTermHelpTextProps> = ({
children,
className,
...props
}: DescriptionListTermHelpTextProps) => (
<dt className={css(styles.descriptionListTerm, className)} {...props}>
{children}
</dt>
);
DescriptionListTermHelpText.displayName = 'DescriptionListTermHelpText';
|
jelly/patternfly-react | packages/react-core/src/layouts/Level/index.tsx | export * from './Level';
export * from './LevelItem';
|
jelly/patternfly-react | packages/react-integration/cypress/integration/clipboardcopy.spec.ts | describe('Clipboard Copy Demo Test', () => {
it('Navigate to demo section', () => {
cy.visit('http://localhost:3000/clipboard-copy-demo-nav-link');
});
it('Verify form input', () => {
cy.get('input').should('have.class', 'pf-c-form-control');
});
it('Verify content expands', () => {
cy.get('.pf-c-clipboard-copy__group [id*="toggle-"]').click();
cy.get('.pf-c-clipboard-copy__expandable-content').should('exist');
});
it('Verify inline clipboard copy', () => {
cy.get('#inline-copy').should('have.class', 'pf-m-inline');
cy.get('#inline-copy').should('have.class', 'pf-m-block');
});
});
|
jelly/patternfly-react | packages/react-charts/src/components/ChartCursorTooltip/ChartCursorFlyout.test.tsx | <gh_stars>0
import * as React from 'react';
import { render } from '@testing-library/react';
import { ChartArea } from '../ChartArea';
import { ChartGroup } from '../ChartGroup';
import { ChartCursorFlyout } from './ChartCursorFlyout';
import { ChartCursorTooltip } from './ChartCursorTooltip';
import { createContainer } from '../ChartUtils';
Object.values([true, false]).forEach(() => {
test('ChartTooltip', () => {
const { asFragment } = render(
<ChartCursorTooltip text="This is a tooltip" flyoutComponent={<ChartCursorFlyout />} />
);
expect(asFragment()).toMatchSnapshot();
});
});
test('allows tooltip via container component', () => {
const CursorVoronoiContainer = createContainer('cursor', 'voronoi');
const { asFragment } = render(
<ChartGroup
containerComponent={
<CursorVoronoiContainer
labels={(point: { y: number }) => 'y: ' + point.y}
labelComponent={<ChartCursorTooltip flyoutComponent={<ChartCursorFlyout />} />}
/>
}
height={200}
width={200}
>
<ChartArea
data={[
{ name: 'Cats', x: 1, y: 1 },
{ name: 'Cats', x: 2, y: 2 },
{ name: 'Cats', x: 3, y: 3.2 },
{ name: 'Cats', x: 4, y: 3.5 }
]}
/>
<ChartArea
data={[
{ name: 'Dogs', x: 1, y: 0.5 },
{ name: 'Dogs', x: 2, y: 1 },
{ name: 'Dogs', x: 3, y: 2 },
{ name: 'Dogs', x: 4, y: 2.5 },
{ name: 'Dogs', x: 5, y: 2.5 }
]}
/>
</ChartGroup>
);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-topology/src/components/decorators/index.ts | export { default as Decorator } from './Decorator';
|
jelly/patternfly-react | packages/react-core/src/components/Page/__tests__/PageHeader.test.tsx | import * as React from 'react';
import { render } from '@testing-library/react';
import { PageHeader } from '../PageHeader';
jest.mock('../Page');
test('Check page vertical layout example against snapshot', () => {
const Header = <PageHeader logo="Logo" headerTools="PageHeaderTools | Avatar" onNavToggle={() => undefined} />;
const { asFragment } = render(Header);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-core/src/components/Card/examples/CardExpandableWithIcon.tsx | import React from 'react';
import {
Card,
CardHeader,
CardActions,
CardBody,
CardFooter,
CardExpandableContent,
Checkbox,
Dropdown,
DropdownItem,
DropdownSeparator,
KebabToggle
} from '@patternfly/react-core';
import pfLogoSmall from './pf-logo-small.svg';
export const CardExpandableWithIcon: React.FunctionComponent = () => {
const [isOpen, setIsOpen] = React.useState<boolean>(false);
const [isChecked, setIsChecked] = React.useState<boolean>(false);
const [isExpanded, setIsExpanded] = 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 dropdownItems = [
<DropdownItem key="link">Link</DropdownItem>,
<DropdownItem key="action" component="button">
Action
</DropdownItem>,
<DropdownItem key="disabled link" isDisabled>
Disabled Link
</DropdownItem>,
<DropdownItem key="disabled action" isDisabled component="button">
Disabled Action
</DropdownItem>,
<DropdownSeparator key="separator" />,
<DropdownItem key="separated link">Separated Link</DropdownItem>,
<DropdownItem key="separated action" component="button">
Separated Action
</DropdownItem>
];
return (
<Card id="expandable-card-icon" isExpanded={isExpanded}>
<CardHeader
onExpand={onExpand}
toggleButtonProps={{
id: 'toggle-button2',
'aria-label': 'Patternfly Details',
'aria-expanded': isExpanded
}}
>
<img src={pfLogoSmall} alt="PatternFly logo" width="27px" />
<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-5"
name="check5"
/>
</CardActions>
</CardHeader>
<CardExpandableContent>
<CardBody>Body</CardBody>
<CardFooter>Footer</CardFooter>
</CardExpandableContent>
</Card>
);
};
|
jelly/patternfly-react | packages/react-charts/src/components/ChartTheme/styles/bullet-styles.ts | /* eslint-disable camelcase */
import chart_bullet_axis_tick_count from '@patternfly/react-tokens/dist/esm/chart_bullet_axis_tick_count';
import chart_bullet_comparative_measure_Width from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_Width';
import chart_bullet_comparative_measure_error_Width from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_error_Width';
import chart_bullet_comparative_measure_warning_Width from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_warning_Width';
import chart_bullet_label_subtitle_Fill from '@patternfly/react-tokens/dist/esm/chart_bullet_label_subtitle_Fill';
import chart_bullet_primary_measure_dot_size from '@patternfly/react-tokens/dist/esm/chart_bullet_primary_measure_dot_size';
import chart_bullet_primary_measure_segmented_Width from '@patternfly/react-tokens/dist/esm/chart_bullet_primary_measure_segmented_Width';
import chart_bullet_qualitative_range_Width from '@patternfly/react-tokens/dist/esm/chart_bullet_qualitative_range_Width';
import chart_global_FontSize_2xl from '@patternfly/react-tokens/dist/esm/chart_global_FontSize_2xl';
import chart_global_FontSize_sm from '@patternfly/react-tokens/dist/esm/chart_global_FontSize_sm';
import chart_global_FontSize_lg from '@patternfly/react-tokens/dist/esm/chart_global_FontSize_lg';
// Bullet styles
export const BulletStyles = {
axisTickCount: chart_bullet_axis_tick_count.value,
comparativeMeasureErrorWidth: chart_bullet_comparative_measure_error_Width.value,
comparativeMeasureWarningWidth: chart_bullet_comparative_measure_warning_Width.value,
comparativeMeasureWidth: chart_bullet_comparative_measure_Width.value,
label: {
groupTitle: {
// Victory props only
fontSize: chart_global_FontSize_2xl.value
},
subTitle: {
// Victory props only
fill: chart_bullet_label_subtitle_Fill.value,
fontSize: chart_global_FontSize_sm.value
},
title: {
// Victory props only
fontSize: chart_global_FontSize_lg.value
}
},
primaryDotMeasureSize: chart_bullet_primary_measure_dot_size.value,
primarySegmentedMeasureWidth: chart_bullet_primary_measure_segmented_Width.value,
qualitativeRangeWidth: chart_bullet_qualitative_range_Width.value
};
|
jelly/patternfly-react | packages/react-core/src/components/Panel/__tests__/Panel.test.tsx | import React from 'react';
import { render } from '@testing-library/react';
import { Panel } from '../Panel';
import { PanelMain } from '../PanelMain';
import { PanelMainBody } from '../PanelMainBody';
import { PanelHeader } from '../PanelHeader';
import { PanelFooter } from '../PanelFooter';
describe('Panel', () => {
test('renders content', () => {
const { asFragment } = render(<Panel>Foo</Panel>);
expect(asFragment()).toMatchSnapshot();
});
test('renders content with raised styling', () => {
const { asFragment } = render(<Panel variant="raised">Foo</Panel>);
expect(asFragment()).toMatchSnapshot();
});
test('renders content with bordered styling', () => {
const { asFragment } = render(<Panel variant="bordered">Foo</Panel>);
expect(asFragment()).toMatchSnapshot();
});
test('renders content with scrollable styling', () => {
const { asFragment } = render(<Panel isScrollable>Foo</Panel>);
expect(asFragment()).toMatchSnapshot();
});
});
describe('PanelMain', () => {
test('renders content', () => {
const { asFragment } = render(<PanelMain>Foo</PanelMain>);
expect(asFragment()).toMatchSnapshot();
});
test('renders content with the set maximum height', () => {
const { asFragment } = render(<PanelMain maxHeight={'80px'}>Foo</PanelMain>);
expect(asFragment()).toMatchSnapshot();
});
});
describe('PanelMainBody', () => {
test('renders content', () => {
const { asFragment } = render(<PanelMainBody>Foo</PanelMainBody>);
expect(asFragment()).toMatchSnapshot();
});
});
describe('PanelHeader', () => {
test('renders content', () => {
const { asFragment } = render(<PanelHeader>Foo</PanelHeader>);
expect(asFragment()).toMatchSnapshot();
});
});
describe('PanelFooter', () => {
test('renders content', () => {
const { asFragment } = render(<PanelFooter>Foo</PanelFooter>);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-core/src/components/DragDrop/examples/DragDropBasic.tsx | import React from 'react';
import { DragDrop, Draggable, Droppable } from '@patternfly/react-core';
interface ItemType {
id: string;
content: string;
}
interface SourceType {
droppableId: string;
index: number;
}
interface DestinationType extends SourceType {}
const getItems = (count: number) =>
Array.from({ length: count }, (_, idx) => idx).map(idx => ({
id: `item-${idx}`,
content: `item ${idx} `.repeat(idx === 4 ? 20 : 1)
}));
const reorder = (list: ItemType[], startIndex: number, endIndex: number) => {
const result = list;
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
export const DragDropBasic: React.FunctionComponent = () => {
const [items, setItems] = React.useState(getItems(10));
function onDrop(source: SourceType, dest: DestinationType) {
if (dest) {
const newItems = reorder(items, source.index, dest.index);
setItems(newItems);
return true;
}
return false;
}
return (
<DragDrop onDrop={onDrop}>
<Droppable>
{items.map(({ content }, i) => (
<Draggable key={i} style={{ padding: '8px' }}>
{content}
</Draggable>
))}
</Droppable>
</DragDrop>
);
};
|
jelly/patternfly-react | packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyInlineCompactCode.tsx | <reponame>jelly/patternfly-react
import React from 'react';
import { ClipboardCopy } from '@patternfly/react-core';
export const ClipboardCopyInlineCompactCode: React.FunctionComponent = () => (
<ClipboardCopy hoverTip="Copy" clickTip="Copied" variant="inline-compact" isCode>
2.3.4-2-redhat
</ClipboardCopy>
);
|
jelly/patternfly-react | packages/react-core/src/components/Truncate/__tests__/Truncate.test.tsx | import React from 'react';
import { render } from '@testing-library/react';
import { Truncate } from '../Truncate';
test('renders default truncation', () => {
const { asFragment } = render(
<Truncate content={'Vestibulum interdum risus et enim faucibus, sit amet molestie est accumsan.'} />
);
expect(asFragment()).toMatchSnapshot();
});
test('renders start truncation', () => {
const { asFragment } = render(
<Truncate
content={'Vestibulum interdum risus et enim faucibus, sit amet molestie est accumsan.'}
position={'start'}
/>
);
expect(asFragment()).toMatchSnapshot();
});
test('renders middle truncation', () => {
const { asFragment } = render(
<Truncate
content={'Vestibulum interdum risus et enim faucibus, sit amet molestie est accumsan.'}
position={'middle'}
/>
);
expect(asFragment()).toMatchSnapshot();
});
|
jelly/patternfly-react | packages/react-core/src/components/Card/examples/CardWithHeadingElement.tsx | import React from 'react';
import { Card, CardTitle, CardBody, CardFooter } from '@patternfly/react-core';
export const CardWithHeadingElement: React.FunctionComponent = () => (
<Card>
<CardTitle component="h4">Header within an {'<h4>'} element</CardTitle>
<CardBody>Body</CardBody>
<CardFooter>Footer</CardFooter>
</Card>
);
|
jelly/patternfly-react | packages/react-core/src/components/Breadcrumb/examples/BreadcrumbWithHeading.tsx | <filename>packages/react-core/src/components/Breadcrumb/examples/BreadcrumbWithHeading.tsx
import React from 'react';
import { Breadcrumb, BreadcrumbItem, BreadcrumbHeading } from '@patternfly/react-core';
export const BreadcrumbWithHeading: React.FunctionComponent = () => (
<Breadcrumb>
<BreadcrumbItem to="#">Section home</BreadcrumbItem>
<BreadcrumbItem to="#">Section title</BreadcrumbItem>
<BreadcrumbItem to="#">Section title</BreadcrumbItem>
<BreadcrumbItem to="#">Section title</BreadcrumbItem>
<BreadcrumbHeading to="#">Section title</BreadcrumbHeading>
</Breadcrumb>
);
|
jelly/patternfly-react | packages/react-core/src/components/Dropdown/__tests__/Generated/DropdownItem.test.tsx | <gh_stars>0
import React from 'react';
import { render } from '@testing-library/react';
import { DropdownItem } from '../../DropdownItem';
import { DropdownArrowContext } from '../../dropdownConstants';
describe('DropdownItem', () => {
it('should match snapshot', () => {
const { asFragment } = render(
<DropdownArrowContext.Provider value={{ sendRef: jest.fn(), keyHandler: undefined }}>
<DropdownItem
children={<>ReactNode</>}
className={"''"}
listItemClassName={'string'}
component={'a'}
isDisabled={false}
isPlainText={false}
isHovered={false}
href={'string'}
tooltip={null}
tooltipProps={undefined}
additionalChild={<div>ReactNode</div>}
customChild={<div>ReactNode</div>}
icon={null}
/>
</DropdownArrowContext.Provider>
);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-core/src/components/Divider/examples/DividerUsingHr.tsx | <reponame>jelly/patternfly-react
import React from 'react';
import { Divider } from '@patternfly/react-core';
export const DividerUsingHr: React.FunctionComponent = () => <Divider />;
|
jelly/patternfly-react | packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyReadOnly.tsx | import React from 'react';
import { ClipboardCopy } from '@patternfly/react-core';
export const ClipboardCopyReadOnly: React.FunctionComponent = () => (
<ClipboardCopy isReadOnly hoverTip="Copy" clickTip="Copied">
This is read-only
</ClipboardCopy>
);
|
jelly/patternfly-react | packages/react-core/src/components/Modal/__tests__/ModalBoxCloseButton.test.tsx | import * as React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ModalBoxCloseButton } from '../ModalBoxCloseButton';
describe('ModalBoxCloseButton', () => {
test('onClose called when clicked', () => {
const onClose = jest.fn();
render(<ModalBoxCloseButton className="test-box-close-button-class" onClose={onClose} />);
userEvent.click(screen.getByRole('button'));
expect(onClose).toHaveBeenCalledTimes(1);
});
});
|
jelly/patternfly-react | packages/react-core/src/helpers/Popper/thirdparty/popper-core/utils/mergeByName.ts | // @ts-nocheck
import { Modifier } from '../types';
/**
* @param modifiers
*/
export default function mergeByName(modifiers: Partial<Modifier<any, any>>[]): Partial<Modifier<any, any>>[] {
const merged = modifiers.reduce((merged, current) => {
const existing = merged[current.name];
merged[current.name] = existing
? {
...existing,
...current,
options: { ...existing.options, ...current.options },
data: { ...existing.data, ...current.data }
}
: current;
return merged;
}, {});
// IE11 does not support Object.values
return Object.keys(merged).map(key => merged[key]);
}
|
jelly/patternfly-react | packages/react-virtualized-extension/src/components/Virtualized/utils/animationFrame.ts | /**
* animationFrame.js
* https://github.com/bvaughn/react-virtualized/blob/9.21.0/source/utils/animationFrame.js
* <NAME>
*
* Forked from version 9.21.0
* */
// Properly handle server-side rendering.
let win: any;
if (typeof window !== 'undefined') {
win = window;
// eslint-disable-next-line no-restricted-globals
} else if (typeof self !== 'undefined') {
// eslint-disable-next-line no-restricted-globals
win = self;
} else {
win = {};
}
// requestAnimationFrame() shim by <NAME>
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
export const raf =
win.requestAnimationFrame ||
win.webkitRequestAnimationFrame ||
win.mozRequestAnimationFrame ||
win.oRequestAnimationFrame ||
win.msRequestAnimationFrame ||
function raf(callback: any) {
return win.setTimeout(callback, 1000 / 60);
};
export const caf =
win.cancelAnimationFrame ||
win.webkitCancelAnimationFrame ||
win.mozCancelAnimationFrame ||
win.oCancelAnimationFrame ||
win.msCancelAnimationFrame ||
function cT(id: any) {
win.clearTimeout(id);
};
|
jelly/patternfly-react | packages/react-core/src/components/MenuToggle/index.ts | <gh_stars>100-1000
export * from './MenuToggle';
|
jelly/patternfly-react | packages/react-core/src/components/DataList/examples/DataListActions.tsx | import React from 'react';
import {
Button,
Dropdown,
DropdownItem,
DropdownPosition,
KebabToggle,
DataList,
DataListItem,
DataListCell,
DataListItemRow,
DataListItemCells,
DataListAction
} from '@patternfly/react-core';
export const DataListActions: React.FunctionComponent = () => {
const [isOpen, setIsOpen] = React.useState(false);
const [isDeleted, setIsDeleted] = React.useState(false);
const onToggle = isOpen => {
setIsOpen(isOpen);
};
const onSelect = () => {
setIsOpen(!isOpen);
};
return (
<React.Fragment>
<DataList aria-label="single action data list example ">
{!isDeleted && (
<DataListItem aria-labelledby="single-action-item1">
<DataListItemRow>
<DataListItemCells
dataListCells={[
<DataListCell key="primary content">
<span id="single-action-item1">Single actionable Primary content</span>
</DataListCell>,
<DataListCell key="secondary content">Single actionable Secondary content</DataListCell>
]}
/>
<DataListAction
aria-labelledby="single-action-item1 single-action-action1"
id="single-action-action1"
aria-label="Actions"
>
<Button
onClick={() => {
if (confirm('Are you sure?')) {
setIsDeleted(true);
}
}}
variant="primary"
key="delete-action"
>
Delete
</Button>
</DataListAction>
</DataListItemRow>
</DataListItem>
)}
<DataListItem aria-labelledby="multi-actions-item1">
<DataListItemRow>
<DataListItemCells
dataListCells={[
<DataListCell key="primary content">
<span id="multi-actions-item1">Multi actions Primary content</span>
</DataListCell>,
<DataListCell key="secondary content">Multi actions Secondary content</DataListCell>
]}
/>
<DataListAction
aria-labelledby="multi-actions-item1 multi-actions-action1"
id="multi-actions-action1"
aria-label="Actions"
isPlainButtonAction
>
<Dropdown
isPlain
position={DropdownPosition.right}
isOpen={isOpen}
onSelect={onSelect}
toggle={<KebabToggle onToggle={onToggle} />}
dropdownItems={[
<DropdownItem key="link">Link</DropdownItem>,
<DropdownItem key="action" component="button">
Action
</DropdownItem>,
<DropdownItem key="disabled link" isDisabled>
Disabled Link
</DropdownItem>
]}
/>
</DataListAction>
</DataListItemRow>
</DataListItem>
</DataList>
</React.Fragment>
);
};
|
jelly/patternfly-react | packages/react-core/src/components/MultipleFileUpload/__tests__/MultipleFileUploadTitle.test.tsx | import React from 'react';
import { render, screen } from '@testing-library/react';
import { MultipleFileUploadTitle } from '../MultipleFileUploadTitle';
describe('MultipleFileUploadTitle', () => {
test('renders with expected class names', () => {
const { asFragment } = render(<MultipleFileUploadTitle />);
expect(asFragment()).toMatchSnapshot();
});
test('renders custom class names', () => {
const { asFragment } = render(<MultipleFileUploadTitle className="test" />);
expect(asFragment()).toMatchSnapshot();
});
test('renders with title icon', () => {
const { asFragment } = render(<MultipleFileUploadTitle icon="icon" />);
expect(asFragment()).toMatchSnapshot();
});
test('renders with title text', () => {
const { asFragment } = render(<MultipleFileUploadTitle text="text" />);
expect(asFragment()).toMatchSnapshot();
});
test('renders with title text separator', () => {
const { asFragment } = render(<MultipleFileUploadTitle text="text" textSeparator="text separator" />);
expect(asFragment()).toMatchSnapshot();
});
});
|
jelly/patternfly-react | packages/react-table/src/components/TableComposable/examples/ComposableTableNestedHeaders.tsx | <filename>packages/react-table/src/components/TableComposable/examples/ComposableTableNestedHeaders.tsx
import React from 'react';
import { TableComposable, Thead, Tr, Th, Tbody, Td, InnerScrollContainer, ThProps } from '@patternfly/react-table';
import { Stack, StackItem } from '@patternfly/react-core';
interface PodConnection {
source: {
podName: string;
port: { num: number; protocol: string };
};
destination: {
podName: string;
port: { num: number; protocol: string };
};
timestamp: string;
protocol: string;
flowRate: string;
traffic: string;
packets: number;
}
export const ComposableTableNestedHeaders: React.FunctionComponent = () => {
// In real usage, this data would come from some external source like an API via props.
const connections: PodConnection[] = [
{
source: { podName: 'api-pod-source-name', port: { num: 443, protocol: 'HTTPS' } },
destination: { podName: 'api-pod-destination-name', port: { num: 24, protocol: 'SMTP' } },
timestamp: '2021-06-22T19:58:24.000Z',
protocol: 'TCP',
flowRate: '1.9 Kbps',
traffic: '2.1 KB',
packets: 3
},
{
source: { podName: 'api-pod-source2-name', port: { num: 80, protocol: 'HTTP' } },
destination: { podName: 'api-pod-destination2-name', port: { num: 24, protocol: 'SMTP' } },
timestamp: '2021-06-22T21:42:01.000Z',
protocol: 'UDP',
flowRate: '3.4 Kbps',
traffic: '6.1 KB',
packets: 7
}
];
const columnNames = {
pods: 'Pods',
source: 'Source',
destination: 'Destination',
datetime: 'Date & Time',
ports: 'Ports',
protocol: 'Protocol',
flowRate: 'Flow rate',
traffic: 'Traffic',
packets: 'Packets'
};
// 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);
// Since OnSort specifies sorted columns by index, we need sortable values for our object by column index.
const getSortableRowValues = (connection: PodConnection): (string | number)[] => {
const { source, destination, timestamp, protocol, flowRate, traffic, packets } = connection;
return [
source.podName,
destination.podName,
timestamp,
source.port.num,
destination.port.num,
protocol,
flowRate,
traffic,
packets
];
};
// 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 sortedConnections = connections;
if (activeSortIndex !== null) {
sortedConnections = connections.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 (
<InnerScrollContainer>
<TableComposable aria-label="Nested column headers table" gridBreakPoint="">
<Thead hasNestedHeader>
<Tr>
<Th hasRightBorder colSpan={3}>
{columnNames.pods}
</Th>
<Th hasRightBorder colSpan={2}>
{columnNames.ports}
</Th>
<Th modifier="fitContent" hasRightBorder rowSpan={2} sort={getSortParams(5)}>
{columnNames.protocol}
</Th>
<Th modifier="fitContent" hasRightBorder rowSpan={2} sort={getSortParams(6)}>
{columnNames.flowRate}
</Th>
<Th modifier="fitContent" hasRightBorder rowSpan={2} sort={getSortParams(7)}>
{columnNames.traffic}
</Th>
<Th modifier="fitContent" rowSpan={2} sort={getSortParams(8)}>
{columnNames.packets}
</Th>
</Tr>
<Tr>
<Th isSubheader sort={getSortParams(0)}>
{columnNames.source}
</Th>
<Th isSubheader sort={getSortParams(1)}>
{columnNames.destination}
</Th>
<Th isSubheader modifier="fitContent" hasRightBorder sort={getSortParams(2)}>
{columnNames.datetime}
</Th>
<Th isSubheader modifier="fitContent" sort={getSortParams(3)}>
{columnNames.source}
</Th>
<Th isSubheader modifier="fitContent" hasRightBorder sort={getSortParams(4)}>
{columnNames.destination}
</Th>
</Tr>
</Thead>
<Tbody>
{sortedConnections.map(connection => (
<Tr key={connection.source.podName}>
<Td dataLabel={columnNames.source}>{connection.source.podName}</Td>
<Td dataLabel={columnNames.destination}>{connection.destination.podName}</Td>\
<Td dataLabel={columnNames.datetime}>
<div>
<span>{new Date(connection.timestamp).toDateString()}</span>{' '}
<span className="pf-u-color-200">{new Date(connection.timestamp).toLocaleTimeString()}</span>
</div>
</Td>
<Td dataLabel={columnNames.source}>
<Stack>
<StackItem>
<span>{connection.source.port.num}</span>
</StackItem>
<StackItem>
<span className="pf-u-color-200">({connection.source.port.protocol})</span>
</StackItem>
</Stack>
</Td>
<Td dataLabel={columnNames.destination}>
<Stack>
<StackItem>
<span>{connection.destination.port.num}</span>
</StackItem>
<StackItem>
<span className="pf-u-color-200">({connection.destination.port.protocol})</span>
</StackItem>
</Stack>
</Td>
<Td dataLabel={columnNames.protocol}>{connection.protocol}</Td>
<Td dataLabel={columnNames.flowRate}>{connection.flowRate}</Td>
<Td dataLabel={columnNames.traffic}>{connection.traffic}</Td>
<Td dataLabel={columnNames.packets}>{connection.packets}</Td>
</Tr>
))}
</Tbody>
</TableComposable>
</InnerScrollContainer>
);
};
|
Subsets and Splits