repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
jelly/patternfly-react
packages/react-charts/src/components/ChartDonutUtilization/ChartDonutUtilization.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import { ChartDonutUtilization } from './ChartDonutUtilization'; Object.values([true, false]).forEach(() => { test('ChartDonutUtilization', () => { const { asFragment } = render(<ChartDonutUtilization />); expect(asFragment()).toMatchSnapshot(); }); }); test('renders component data', () => { const { asFragment } = render(<ChartDonutUtilization data={{ x: 'Cats', y: 35 }} height={200} width={200} />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-log-viewer/src/LogViewer/LogViewerContext.tsx
<reponame>jelly/patternfly-react import { createContext, useContext } from 'react'; import { searchedKeyWordType } from './utils/utils'; export const useLogViewerContext = () => useContext(LogViewerContext); interface LogViewerContextInterface { parsedData: string[]; searchedInput: string; } export const LogViewerContext = createContext<LogViewerContextInterface | null>(null); interface LogViewerToolbarContextProps { searchedWordIndexes: searchedKeyWordType[]; rowInFocus: searchedKeyWordType; searchedInput: string; itemCount: number; currentSearchedItemCount: number; scrollToRow: (searchedRow: searchedKeyWordType) => void; setRowInFocus: (index: searchedKeyWordType) => void; setSearchedInput: (input: string) => void; setSearchedWordIndexes: (indexes: searchedKeyWordType[]) => void; setCurrentSearchedItemCount: (index: number) => void; } export const LogViewerToolbarContext = createContext<LogViewerToolbarContextProps | null>(null);
jelly/patternfly-react
packages/react-core/src/components/LoginPage/__tests__/LoginForm.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { LoginForm } from '../LoginForm'; describe('LoginForm', () => { test('should render Login form', () => { const { asFragment } = render(<LoginForm />); expect(asFragment()).toMatchSnapshot(); }); test('should call onChangeUsername callback', () => { const mockFn = jest.fn(); render(<LoginForm onChangeUsername={mockFn} rememberMeLabel="Remember me" />); userEvent.type(screen.getByText('Username'), 'updatedUserName'); expect(mockFn).toHaveBeenCalled(); }); test('should call onChangePassword callback', () => { const mockFn = jest.fn(); render(<LoginForm onChangePassword={mockFn} rememberMeLabel="Remember me" />); userEvent.type(screen.getByText('Password'), '<PASSWORD>'); expect(mockFn).toHaveBeenCalled(); }); test('should call onChangeRememberMe callback', () => { const mockFn = jest.fn(); render(<LoginForm onChangeRememberMe={mockFn} rememberMeLabel="Remember me" />); userEvent.click(screen.getByLabelText('Remember me')); expect(mockFn).toHaveBeenCalled(); }); test('LoginForm with rememberMeLabel', () => { const { asFragment } = render(<LoginForm rememberMeLabel="Remember me" />); expect(asFragment()).toMatchSnapshot(); }); test('LoginForm with show password', () => { const { asFragment } = render(<LoginForm isShowPasswordEnabled />); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/Card/__tests__/CardExpandableContent.test.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { CardContext } from '../Card'; import { CardExpandableContent } from '../CardExpandableContent'; import { render } from '@testing-library/react'; test('renders successfully', () => { const { asFragment } = render( <CardContext.Provider value={{ isExpanded: true }}> <CardExpandableContent /> </CardContext.Provider> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-topology/src/components/index.ts
<reponame>jelly/patternfly-react export * from './TopologyView'; export * from './TopologyControlBar'; export * from './TopologySideBar'; export { default as VisualizationProvider } from './VisualizationProvider'; export { default as VisualizationSurface } from './VisualizationSurface'; export { default as DefaultCreateConnector } from './DefaultCreateConnector'; export { default as DefaultRemoveConnector } from './DefaultRemoveConnector'; export { default as GraphComponent } from './GraphComponent'; export { default as SVGArrowMarker } from './SVGArrowMarker'; export { default as ElementWrapper } from './ElementWrapper'; export * from './contextmenu'; export * from './decorators'; export * from './groups'; export * from './nodes'; export * from './edges'; export * from './factories'; export * from './layers'; export * from './defs';
jelly/patternfly-react
packages/react-core/src/components/Select/__tests__/SelectGroup.test.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { render } from '@testing-library/react'; import { SelectGroup } from '../SelectGroup'; import { SelectProvider } from '../selectConstants'; describe('SelectGroup', () => { test('renders with children successfully', () => { const { asFragment } = render( <SelectProvider value={{ onSelect: () => {}, onFavorite: () => {}, onClose: () => {}, variant: 'single', inputIdPrefix: '', shouldResetOnSelect: true }} > <SelectGroup label="test"> <div>child</div> </SelectGroup> </SelectProvider> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/Text/__tests__/Text.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { TextContent } from '../TextContent'; import { Text, TextVariants } from '../Text'; import { TextList, TextListVariants } from '../TextList'; import { TextListItem, TextListItemVariants } from '../TextListItem'; test('Text example should match snapshot', () => { const { asFragment } = render( <TextContent> <Text component={TextVariants.h1}>Hello World</Text> <Text component={TextVariants.p}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla accumsan, metus ultrices eleifend gravida, nulla nunc varius lectus, nec rutrum justo nibh eu lectus. Ut vulputate semper dui. Fusce erat odio, sollicitudin vel erat vel, interdum mattis neque. Sub works as well! </Text> <Text component={TextVariants.h2}>Second level</Text> <Text component={TextVariants.p}> Curabitur accumsan turpis pharetra <strong>augue tincidunt</strong> blandit. Quisque condimentum maximus mi, sit amet commodo arcu rutrum id. Proin pretium urna vel cursus venenatis. Suspendisse potenti. Etiam mattis sem rhoncus lacus dapibus facilisis. Donec at dignissim dui. Ut et neque nisl. </Text> <TextList> <TextListItem>In fermentum leo eu lectus mollis, quis dictum mi aliquet.</TextListItem> <TextListItem>Morbi eu nulla lobortis, lobortis est in, fringilla felis.</TextListItem> <TextListItem> Aliquam nec felis in sapien venenatis viverra fermentum nec lectus. <TextList> <TextListItem>In fermentum leo eu lectus mollis, quis dictum mi aliquet.</TextListItem> <TextListItem>Morbi eu nulla lobortis, lobortis est in, fringilla felis.</TextListItem> </TextList> </TextListItem> <TextListItem>Ut non enim metus.</TextListItem> </TextList> <Text component={TextVariants.h3}>Third level</Text> <Text component={TextVariants.p}> Quisque ante lacus, malesuada ac auctor vitae, congue{' '} <Text component={TextVariants.a} href="#"> non ante </Text> . Phasellus lacus ex, semper ac tortor nec, fringilla condimentum orci. Fusce eu rutrum tellus. </Text> <TextList component={TextListVariants.ol}> <TextListItem>Donec blandit a lorem id convallis.</TextListItem> <TextListItem>Cras gravida arcu at diam gravida gravida.</TextListItem> <TextListItem>Integer in volutpat libero.</TextListItem> <TextListItem>Donec a diam tellus.</TextListItem> <TextListItem>Aenean nec tortor orci.</TextListItem> <TextListItem>Quisque aliquam cursus urna, non bibendum massa viverra eget.</TextListItem> <TextListItem>Vivamus maximus ultricies pulvinar.</TextListItem> </TextList> <Text component={TextVariants.blockquote}> Ut venenatis, nisl scelerisque sollicitudin fermentum, quam libero hendrerit ipsum, ut blandit est tellus sit amet turpis. </Text> <Text component={TextVariants.p}> Quisque at semper enim, eu hendrerit odio. Etiam auctor nisl et <em>justo sodales</em> elementum. Maecenas ultrices lacus quis neque consectetur, et lobortis nisi molestie. </Text> <Text component={TextVariants.p}> Sed sagittis enim ac tortor maximus rutrum. Nulla facilisi. Donec mattis vulputate risus in luctus. Maecenas vestibulum interdum commodo. </Text> <TextList component={TextListVariants.dl}> <TextListItem component={TextListItemVariants.dt}>Web</TextListItem> <TextListItem component={TextListItemVariants.dd}> The part of the Internet that contains websites and web pages </TextListItem> <TextListItem component={TextListItemVariants.dt}>HTML</TextListItem> <TextListItem component={TextListItemVariants.dd}>A markup language for creating web pages</TextListItem> <TextListItem component={TextListItemVariants.dt}>CSS</TextListItem> <TextListItem component={TextListItemVariants.dd}>A technology to make HTML look better</TextListItem> </TextList> <Text component={TextVariants.p}> Suspendisse egestas sapien non felis placerat elementum. Morbi tortor nisl, suscipit sed mi sit amet, mollis malesuada nulla. Nulla facilisi. Nullam ac erat ante. </Text> <Text component={TextVariants.h4}>Fourth level</Text> <Text component={TextVariants.p}> Nulla efficitur eleifend nisi, sit amet bibendum sapien fringilla ac. Mauris euismod metus a tellus laoreet, at elementum ex efficitur. </Text> <Text component={TextVariants.p}> Maecenas eleifend sollicitudin dui, faucibus sollicitudin augue cursus non. Ut finibus eleifend arcu ut vehicula. Mauris eu est maximus est porta condimentum in eu justo. Nulla id iaculis sapien. </Text> <Text component={TextVariants.small}>Sometimes you need small text to display things like date created</Text> <Text component={TextVariants.p}> Phasellus porttitor enim id metus volutpat ultricies. Ut nisi nunc, blandit sed dapibus at, vestibulum in felis. Etiam iaculis lorem ac nibh bibendum rhoncus. Nam interdum efficitur ligula sit amet ullamcorper. Etiam tristique, leo vitae porta faucibus, mi lacus laoreet metus, at cursus leo est vel tellus. Sed ac posuere est. Nunc ultricies nunc neque, vitae ultricies ex sodales quis. Aliquam eu nibh in libero accumsan pulvinar. Nullam nec nisl placerat, pretium metus vel, euismod ipsum. Proin tempor cursus nisl vel condimentum. Nam pharetra varius metus non pellentesque. </Text> <Text component={TextVariants.h5}>Fifth level</Text> <Text component={TextVariants.p}> Aliquam sagittis rhoncus vulputate. Cras non luctus sem, sed tincidunt ligula. Vestibulum at nunc elit. Praesent aliquet ligula mi, in luctus elit volutpat porta. Phasellus molestie diam vel nisi sodales, a eleifend augue laoreet. Sed nec eleifend justo. Nam et sollicitudin odio. </Text> <Text component={TextVariants.h6}>Sixth level</Text> <Text component={TextVariants.p}> Cras in nibh lacinia, venenatis nisi et, auctor urna. Donec pulvinar lacus sed diam dignissim, ut eleifend eros accumsan. Phasellus non tortor eros. Ut sed rutrum lacus. Etiam purus nunc, scelerisque quis enim vitae, malesuada ultrices turpis. Nunc vitae maximus purus, nec consectetur dui. Suspendisse euismod, elit vel rutrum commodo, ipsum tortor maximus dui, sed varius sapien odio vitae est. Etiam at cursus metus. </Text> </TextContent> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-console/src/components/SerialConsole/SerialConsole.tsx
<reponame>jelly/patternfly-react<gh_stars>0 import React from 'react'; import { css } from '@patternfly/react-styles'; import { Button, EmptyState, EmptyStateBody, EmptyStateIcon, Spinner } from '@patternfly/react-core'; import { XTerm, XTermProps } from './XTerm'; import { SerialConsoleActions } from './SerialConsoleActions'; import { constants } from '../common/constants'; import styles from '@patternfly/react-styles/css/components/Consoles/SerialConsole'; import '@patternfly/react-styles/css/components/Consoles/xterm.css'; import '@patternfly/react-styles/css/components/Consoles/SerialConsole.css'; const { CONNECTED, DISCONNECTED, LOADING } = constants; export interface SerialConsoleProps extends XTermProps { /** Initiate connection to backend. In other words, the calling components manages connection state. */ onConnect: () => void; /** Close connection to backend */ onDisconnect: () => void; /** Terminal produced data, like key-press */ onData: (e: string) => void; /** Terminal title has been changed */ onTitleChanged?: () => void; /** Connection status; a value from [''connected'; 'disconnected'; 'loading']. Default is 'loading' for a not matching value. */ /** The number of columns to resize to */ cols?: number; /** The number of rows to resize to */ rows?: number; fontFamily?: string; fontSize?: number; status?: string; /** Text content rendered inside the Connect button */ textConnect?: string; /** Text content rendered inside the Disconnect button */ textDisconnect?: string; /** Text content rendered inside the Reset button */ textReset?: string; /* Text content rendered inside the EmptyState for when console is disconnnected */ textDisconnected?: string; /* Text content rendered inside the EmptyState for when console is loading */ textLoading?: string; /** A reference object to attach to the SerialConsole. */ innerRef?: React.RefObject<any>; } const SerialConsoleBase: React.FunctionComponent<SerialConsoleProps> = ({ onConnect, onDisconnect, onTitleChanged = () => {}, onData, cols, rows, fontFamily, fontSize, status = 'loading', textConnect = 'Connect', textDisconnect, textReset, textDisconnected = 'Click Connect to open serial console.', textLoading = 'Loading ...', innerRef }) => { React.useEffect(() => { onConnect(); return () => { onDisconnect(); }; }, [onConnect, onDisconnect]); const onConnectClick = () => { onConnect(); focusTerminal(); }; const onDisconnectClick = () => { onDisconnect(); focusTerminal(); }; const onResetClick = () => { onDisconnect(); onConnect(); focusTerminal(); }; const focusTerminal = () => { innerRef && innerRef.current && innerRef.current.focusTerminal(); }; let terminal; switch (status) { case CONNECTED: terminal = ( <XTerm innerRef={innerRef} cols={cols} rows={rows} fontFamily={fontFamily} fontSize={fontSize} onTitleChanged={onTitleChanged} onData={onData} /> ); break; case DISCONNECTED: terminal = ( <EmptyState> <EmptyStateBody>{textDisconnected}</EmptyStateBody> <Button onClick={onConnectClick}>{textConnect}</Button> </EmptyState> ); break; case LOADING: default: terminal = ( <EmptyState> <EmptyStateIcon variant="container" component={Spinner} /> <EmptyStateBody>{textLoading}</EmptyStateBody> </EmptyState> ); break; } return ( <> {status !== DISCONNECTED && ( <SerialConsoleActions onDisconnect={onDisconnectClick} onReset={onResetClick} textDisconnect={textDisconnect} textReset={textReset} /> )} <div className={css(styles.consoleSerial)}>{terminal}</div> </> ); }; SerialConsoleBase.displayName = 'SerialConsoleBase'; export const SerialConsole = React.forwardRef((props: SerialConsoleProps, ref: React.Ref<HTMLDivElement>) => ( <SerialConsoleBase innerRef={ref as React.MutableRefObject<any>} {...props} /> )); SerialConsole.displayName = 'SerialConsole';
jelly/patternfly-react
packages/react-code-editor/src/components/CodeEditor/examples/CodeEditorShortcutMainHeader.tsx
import React from 'react'; import { CodeEditor, Language } from '@patternfly/react-code-editor'; import { Grid, GridItem, Chip } from '@patternfly/react-core'; export const CodeEditorShortcutMainHeader: React.FunctionComponent = () => { const onEditorDidMount = (editor, monaco) => { // eslint-disable-next-line no-console console.log(editor.getValue()); editor.layout(); editor.focus(); monaco.editor.getModels()[0].updateOptions({ tabSize: 5 }); }; const onChange = value => { // eslint-disable-next-line no-console console.log(value); }; const shortcuts = [ { keys: ['Opt', 'F1'], description: 'Accessibility helps' }, { keys: ['F1'], description: 'View all editor shortcuts' }, { keys: ['Ctrl', 'Space'], description: 'Activate auto complete' }, { keys: ['Cmd', 'S'], description: 'Save' } ]; const shortcutsPopoverProps = { bodyContent: ( <Grid span={6} hasGutter> {shortcuts.map(s => ( <> <GridItem style={{ textAlign: 'right', marginRight: '1em' }}> {s.keys .map(k => ( <Chip key={k} isReadOnly> {k} </Chip> )) .reduce((prev, curr) => ( <>{[prev, ' + ', curr]}</> ))} </GridItem> <GridItem>{s.description}</GridItem> </> ))} </Grid> ), 'aria-label': 'Shortcuts' }; return ( <CodeEditor headerMainContent="Shortcut Example" shortcutsPopoverProps={shortcutsPopoverProps} isLanguageLabelVisible code="Some example content" onChange={onChange} language={Language.javascript} onEditorDidMount={onEditorDidMount} height="400px" /> ); };
jelly/patternfly-react
packages/react-topology/src/components/TopologySideBar/__tests__/TopologySideBar.test.tsx
import * as React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { TopologySideBar } from '../index'; describe('TopologySideBar', () => { test('should display topology sidebar correctly', () => { render( <TopologySideBar className="my-test-class" show header={<span id="test-header-id">Header</span>}> <div id="test-canvas" /> </TopologySideBar> ); expect(screen.getByText('Header')).toBeInTheDocument(); }); test('should display topology sidebar w/ close correctly', () => { const mockClose = jest.fn(); render( <TopologySideBar className="my-test-class" show onClose={mockClose}> <div id="test-canvas" /> </TopologySideBar> ); userEvent.click(screen.getByRole('button', { name: 'Close' })); expect(mockClose).toHaveBeenCalled(); }); test('should hide the sidebar correctly', () => { render( <TopologySideBar className="my-test-class" show={false} header={<span id="test-header-id">Header</span>}> <div id="test-canvas">test canvas content</div> </TopologySideBar> ); expect(screen.queryByText('test canvas content')).toBeNull(); }); });
jelly/patternfly-react
packages/react-core/src/components/AboutModal/__tests__/AboutModalBoxBrand.test.tsx
<reponame>jelly/patternfly-react<gh_stars>0 import * as React from 'react'; import { render } from '@testing-library/react'; import { AboutModalBoxBrand } from '../AboutModalBoxBrand'; test('test About Modal Brand', () => { const { asFragment } = render(<AboutModalBoxBrand src="testimage.." alt="brand" />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/App.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import { Page, Nav, NavList, NavItem, PageSection, SkipToContent, PageSidebar, Avatar, Brand, PageHeader, PageHeaderTools, PageHeaderToolsItem, PageHeaderToolsGroup, Radio } from '@patternfly/react-core'; import imgBrand from './assets/images/imgBrand.svg'; import imgAvatar from './assets/images/imgAvatar.svg'; import Demos from './Demos'; import './App.css'; interface AppState { activeItem: number | string; isNavOpen: boolean; isDarkTheme: boolean; } class App extends React.Component<{}, AppState> { state: AppState = { activeItem: '', isNavOpen: true, isDarkTheme: false }; private onNavSelect = (selectedItem: { itemId: number | string }) => { this.setState({ activeItem: selectedItem.itemId }); }; private onThemeSelect = (isDarkTheme: boolean) => { this.setState({ isDarkTheme }); const htmlElement = document.getElementsByTagName('html')[0]; if (htmlElement) { if (isDarkTheme) { htmlElement.classList.add('pf-theme-dark'); } else { htmlElement.classList.remove('pf-theme-dark'); } } }; private getPages = () => ( <React.Fragment> {Demos.map(demo => ( <Route path={`/${demo.id}-nav-link`} render={() => ( <PageSection style={{ zIndex: 2 }} id={`/${demo.id}-page-section`}> {React.createElement(demo.componentType)} </PageSection> )} key={demo.id} /> ))} </React.Fragment> ); private pageId = 'ts-demo-app-page-id'; private getSkipToContentLink = () => <SkipToContent href={`#${this.pageId}`}>Skip to Content</SkipToContent>; render() { const { isNavOpen, activeItem, isDarkTheme } = this.state; const AppToolbar = ( <PageHeaderTools> <PageHeaderToolsGroup> <PageHeaderToolsItem style={{ marginRight: '10px' }}> <Radio id="light-theme" aria-label="Light theme" label={`Light theme`} name="light-theme" isChecked={!isDarkTheme} onChange={checked => checked && this.onThemeSelect(false)} /> </PageHeaderToolsItem> <PageHeaderToolsItem> <Radio id="dark-theme" label="Dark theme" aria-label="Dark theme" name="dark-theme" isChecked={isDarkTheme} onChange={checked => checked && this.onThemeSelect(true)} /> </PageHeaderToolsItem> </PageHeaderToolsGroup> <Avatar src={imgAvatar} alt="Avatar image" /> </PageHeaderTools> ); const AppHeader = ( <PageHeader logo={<Brand src={imgBrand} alt="Patternfly Logo" />} headerTools={AppToolbar} showNavToggle isNavOpen={isNavOpen} onNavToggle={() => this.setState({ isNavOpen: !isNavOpen })} /> ); const nav = ( <Nav onSelect={this.onNavSelect} aria-label="Nav"> <NavList> {Demos.map((demo, index) => ( <NavItem itemId={index} isActive={activeItem === index} key={demo.id}> <Link id={`${demo.id}-nav-item-link`} to={`/${demo.id}-nav-link`}> {demo.name} </Link> </NavItem> ))} </NavList> </Nav> ); const AppSidebar = <PageSidebar isNavOpen={isNavOpen} nav={nav} />; return ( <Router> <Page header={AppHeader} sidebar={AppSidebar} skipToContent={this.getSkipToContentLink()} isManagedSidebar mainContainerId={this.pageId} > {this.getPages()} </Page> </Router> ); } } export default App;
jelly/patternfly-react
packages/react-core/src/layouts/Level/__tests__/Level.test.tsx
<filename>packages/react-core/src/layouts/Level/__tests__/Level.test.tsx import * as React from 'react'; import { Level } from '../Level'; import { LevelItem } from '../LevelItem'; import { render } from '@testing-library/react'; test('Gutter', () => { const { asFragment } = render(<Level hasGutter />); expect(asFragment()).toMatchSnapshot(); }); test('item', () => { const { asFragment } = render(<LevelItem>Level Item</LevelItem>); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-table/src/components/TableComposable/examples/ComposableTableMisc.tsx
import React from 'react'; import { TableComposable, Thead, Tr, Th, Tbody, Td } from '@patternfly/react-table'; interface Repository { name: string; branches: string | null; prs: string | null; workspaces: string; lastCommit: string; } export const ComposableTableMisc: React.FunctionComponent = () => { // In real usage, this data would come from some external source like an API via props. const repositories: Repository[] = [ { name: 'one', branches: 'two', prs: 'three', workspaces: 'four', lastCommit: 'five' }, { name: 'one - 2', branches: null, prs: null, workspaces: 'four - 2', lastCommit: 'five - 2' }, { name: 'one - 3', branches: 'two - 3', prs: 'three - 3', workspaces: 'four - 3', lastCommit: 'five - 3' } ]; const columnNames = { name: 'Repositories', branches: 'Branches', prs: 'Pull requests', workspaces: 'Workspaces', lastCommit: 'Last commit' }; return ( <TableComposable aria-label="Misc table"> <Thead noWrap> <Tr> <Th info={{ tooltip: 'More information about repositories', className: 'repositories-info-tip', tooltipProps: { isContentLeftAligned: true } }} > {columnNames.name} </Th> <Th>{columnNames.branches}</Th> <Th info={{ popover: ( <div> More <strong>information</strong> on pull requests </div> ), ariaLabel: 'More information on pull requests', popoverProps: { headerContent: columnNames.prs, footerContent: <a href="#">Click here for even more info</a> } }} > {columnNames.prs} </Th> <Th>{columnNames.workspaces}</Th> <Th textCenter>{columnNames.lastCommit}</Th> </Tr> </Thead> <Tbody> {repositories.map((repo, rowIndex) => { const isOddRow = (rowIndex + 1) % 2; const customStyle = { borderLeft: '3px solid var(--pf-global--primary-color--100)' }; // Some arbitrary logic to demonstrate that cell styles can be based on anything const nameColSpan = repo.branches === null && repo.prs === null ? 3 : 1; const lastCommitTextCenter = rowIndex !== 2; return ( <Tr key={repo.name} className={isOddRow ? 'odd-row-class' : 'even-row-class'} style={isOddRow ? customStyle : {}} > <Td dataLabel={columnNames.name} colSpan={nameColSpan}> {repo.name} </Td> <Td dataLabel={columnNames.branches}>{repo.branches}</Td> <Td dataLabel={columnNames.prs}></Td> <Td dataLabel={columnNames.workspaces}></Td> <Td dataLabel={columnNames.lastCommit} textCenter={lastCommitTextCenter}></Td> </Tr> ); })} </Tbody> </TableComposable> ); };
jelly/patternfly-react
packages/react-core/src/components/ActionList/__tests__/ActionListItem.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import { ActionListItem } from '../ActionListItem'; describe('action list item', () => { test('renders successfully', () => { const { asFragment } = render(<ActionListItem>test</ActionListItem>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-console/src/components/AccessConsoles/index.ts
export * from './AccessConsoles';
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/__tests__/MultipleFileUploadStatusItem.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import { MultipleFileUploadStatusItem } from '../MultipleFileUploadStatusItem'; import FileImageIcon from '@patternfly/react-icons/dist/esm/icons/file-image-icon'; describe('MultipleFileUploadStatusItem', () => { test('renders with expected class names', () => { const { asFragment } = render(<MultipleFileUploadStatusItem progressId="test-progress-id" />); expect(asFragment()).toMatchSnapshot(); }); test('renders custom class names', () => { const { asFragment } = render(<MultipleFileUploadStatusItem className="test" progressId="test-progress-id" />); expect(asFragment()).toMatchSnapshot(); }); test('renders expected values from a passed file object', () => { const testFile = new File(['foo'], 'testFile.txt'); const { asFragment } = render(<MultipleFileUploadStatusItem file={testFile} progressId="test-progress-id" />); expect(asFragment()).toMatchSnapshot(); }); test('renders custom file name/size/icon when passed', () => { const testFile = new File(['foo'], 'testFile.txt'); const { asFragment } = render( <MultipleFileUploadStatusItem file={testFile} fileIcon={<FileImageIcon />} fileName="testCustomFileName.txt" fileSize={42} progressId="test-progress-id" /> ); expect(asFragment()).toMatchSnapshot(); }); test('renders custom progress value/variant when passed', () => { const testFile = new File(['foo'], 'testFile.txt'); const { asFragment } = render( <MultipleFileUploadStatusItem file={testFile} progressValue={42} progressVariant="warning" progressId="test-progress-id" /> ); expect(asFragment()).toMatchSnapshot(); }); test('renders custom aria labels', () => { const testFile = new File(['foo'], 'testFile.txt'); const { asFragment } = render( <MultipleFileUploadStatusItem file={testFile} buttonAriaLabel="buttonAriaLabel" progressAriaLabel="progressAriaLabel" progressAriaLabelledBy="progressAriaLabelledBy" progressId="test-progress-id" /> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-integration/cypress/integration/wizard.spec.ts
<reponame>jelly/patternfly-react describe('Wizard Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/wizard-demo-nav-link'); }); it('Verify wizard in modal launches in a dialog and has a custom width', () => { cy.get('#launchWiz').click(); cy.get('#modalWizId.pf-c-wizard').should('exist'); cy.get('.pf-c-modal-box').should('have.attr', 'style', 'width: 710px;'); cy.focused().click(); }); it('Verify wizard in modal sends focus to the new content', () => { cy.get('#launchWiz').click(); cy.get('#modalWizId.pf-c-wizard').should('exist'); cy.focused().should('have.class', 'pf-c-wizard__close'); cy.focused().click(); }); it('Verify in page wizard displays on page render', () => { cy.get('#inPageWizId.pf-c-wizard').should('exist'); }); });
jelly/patternfly-react
packages/react-core/src/components/AboutModal/__tests__/AboutModalBoxCloseButton.test.tsx
<gh_stars>0 import * as React from 'react'; import { render } from '@testing-library/react'; import { AboutModalBoxCloseButton } from '../AboutModalBoxCloseButton'; test('AboutModalBoxCloseButton Test', () => { const { asFragment } = render(<AboutModalBoxCloseButton />); expect(asFragment()).toMatchSnapshot(); }); test('AboutModalBoxCloseButton Test onclose', () => { const onClose = jest.fn(); const { asFragment } = render(<AboutModalBoxCloseButton onClose={onClose} />); expect(asFragment()).toMatchSnapshot(); }); test('AboutModalBoxCloseButton Test close button aria label', () => { const closeButtonAriaLabel = '<NAME>'; const { asFragment } = render(<AboutModalBoxCloseButton aria-label={closeButtonAriaLabel} />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/BackgroundImage/__tests__/BackgroundImage.test.tsx
import { BackgroundImage } from '../BackgroundImage'; import * as React from 'react'; import { render } from '@testing-library/react'; const images = { lg: '/assets/images/pfbg_1200.jpg', sm: '/assets/images/pfbg_768.jpg', sm2x: '/assets/images/pfbg_768@2x.jpg', xs: '/assets/images/pfbg_576.jpg', xs2x: '/assets/images/pfbg_576@2x.jpg' }; test('BackgroundImage', () => { const { asFragment } = render(<BackgroundImage src={images} />); expect(asFragment()).toMatchSnapshot(); }); test('allows passing in a single string as the image src', () => { const { asFragment } = render(<BackgroundImage src={images.lg} />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/demos/examples/DateTimePicker/DateTimePicker.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { Dropdown, DropdownToggle, DropdownItem, CalendarMonth, InputGroup, TextInput, Button, Popover } from '@patternfly/react-core'; import OutlinedCalendarAltIcon from '@patternfly/react-icons/dist/esm/icons/outlined-calendar-alt-icon'; import OutlinedClockIcon from '@patternfly/react-icons/dist/esm/icons/outlined-clock-icon'; export const DateTimePicker: React.FunctionComponent = () => { const [isCalendarOpen, setIsCalendarOpen] = React.useState(false); const [isTimeOpen, setIsTimeOpen] = React.useState(false); const [valueDate, setValueDate] = React.useState('MM-DD-YYYY'); const [valueTime, setValueTime] = React.useState('HH:MM'); const times = Array.from(new Array(10), (_, i) => i + 8); const defaultTime = '0:00'; const dateFormat = (date: Date) => date.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-'); const onToggleCalendar = () => { setIsCalendarOpen(!isCalendarOpen); setIsTimeOpen(false); }; const onToggleTime = (_value: boolean, _event: any) => { setIsTimeOpen(!isTimeOpen); setIsCalendarOpen(false); }; const onSelectCalendar = (newValueDate: Date) => { const newValue = dateFormat(newValueDate); setValueDate(newValue); setIsCalendarOpen(!isCalendarOpen); // setting default time when it is not picked if (valueTime === 'HH:MM') { setValueTime(defaultTime); } }; const onSelectTime = (ev: React.SyntheticEvent<HTMLDivElement>) => { setValueTime(ev.currentTarget.textContent); setIsTimeOpen(!isTimeOpen); }; const timeOptions = times.map(time => ( <DropdownItem key={time} component="button" value={`${time}:00`}> {`${time}:00`} </DropdownItem> )); const calendar = <CalendarMonth date={new Date(valueDate)} onChange={onSelectCalendar} />; const time = ( <Dropdown onSelect={onSelectTime} toggle={ <DropdownToggle aria-label="Toggle the time picker menu" toggleIndicator={null} onToggle={onToggleTime} style={{ padding: '6px 16px' }} > <OutlinedClockIcon /> </DropdownToggle> } isOpen={isTimeOpen} dropdownItems={timeOptions} /> ); const calendarButton = ( <Button variant="control" aria-label="Toggle the calendar" onClick={onToggleCalendar}> <OutlinedCalendarAltIcon /> </Button> ); return ( <div style={{ width: '300px' }}> <Popover position="bottom" bodyContent={calendar} showClose={false} isVisible={isCalendarOpen} hasNoPadding hasAutoWidth > <InputGroup> <TextInput type="text" id="date-time" aria-label="date and time picker demo" value={valueDate + ' ' + valueTime} isReadOnly /> {calendarButton} {time} </InputGroup> </Popover> </div> ); };
jelly/patternfly-react
packages/react-core/src/components/Tile/Tile.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Tile/tile'; import { css } from '@patternfly/react-styles'; export interface TileProps extends React.HTMLProps<HTMLDivElement> { /** Content rendered inside the banner */ children?: React.ReactNode; /** Additional classes added to the banner */ className?: string; /** Title of the tile */ title: string; /** Icon in the tile title */ icon?: React.ReactNode; /** Flag indicating if the tile is selected */ isSelected?: boolean; /** Flag indicating if the tile is disabled */ isDisabled?: boolean; /** Flag indicating if the tile header is stacked */ isStacked?: boolean; /** Flag indicating if the stacked tile icon is large */ isDisplayLarge?: boolean; } export const Tile: React.FunctionComponent<TileProps> = ({ children, title, icon, isStacked, isSelected, isDisabled, isDisplayLarge, className, ...props }: TileProps) => ( <div role="option" aria-selected={isSelected} {...(isDisabled && { 'aria-disabled': isDisabled })} className={css( styles.tile, isSelected && styles.modifiers.selected, isDisabled && styles.modifiers.disabled, isDisplayLarge && styles.modifiers.displayLg, className )} tabIndex={0} {...props} > <div className={css(styles.tileHeader, isStacked && styles.modifiers.stacked)}> {icon && <div className={css(styles.tileIcon)}>{icon}</div>} <div className={css(styles.tileTitle)}>{title}</div> </div> {children && <div className={css(styles.tileBody)}>{children}</div>} </div> ); Tile.displayName = 'Tile';
jelly/patternfly-react
packages/react-topology/src/components/factories/index.ts
<filename>packages/react-topology/src/components/factories/index.ts export { default as RegisterComponentFactory } from './RegisterComponentFactory'; export { default as RegisterElementFactory } from './RegisterElementFactory'; export { default as RegisterLayoutFactory } from './RegisterLayoutFactory'; export * from './components';
jelly/patternfly-react
packages/react-integration/cypress/integration/selectviewmore.spec.ts
<reponame>jelly/patternfly-react<gh_stars>100-1000 describe('Select Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/select-view-more-demo-nav-link'); }); it('Verify Select with view more button', () => { cy.clock(); cy.get('#view-more-select').click(); cy.get('.pf-c-select__menu').contains('View more'); cy.get('.pf-m-load').should('exist'); cy.get('button.pf-c-select__menu-item.pf-m-load').click(); cy.get('.pf-m-loading').should('exist'); cy.tick(16000); cy.get('.pf-m-load').should('exist'); cy.get('.pf-m-loading').should('not.exist'); cy.get('#view-more-select').click(); }); it('Verify Select with view more button checkboxes', () => { cy.clock(); cy.get('#view-more-select-check').click(); cy.get('.pf-c-select__menu').contains('View more'); cy.get('.pf-m-load').should('exist'); cy.get('button.pf-c-select__menu-item.pf-m-load').click(); cy.get('.pf-m-loading').should('exist'); cy.tick(16000); cy.get('.pf-m-load').should('exist'); cy.get('.pf-m-loading').should('not.exist'); }); });
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/MultipleFileUploadTitleText.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/MultipleFileUpload/multiple-file-upload'; import { css } from '@patternfly/react-styles'; export interface MultipleFileUploadTitleTextProps extends React.HTMLProps<HTMLDivElement> { /** Content rendered inside multiple file upload title text */ children?: React.ReactNode; /** Class to add to outer div */ className?: string; } export const MultipleFileUploadTitleText: React.FunctionComponent<MultipleFileUploadTitleTextProps> = ({ className, children, ...props }: MultipleFileUploadTitleTextProps) => ( <div className={css(styles.multipleFileUploadTitleText, className)} {...props}> {children} </div> ); MultipleFileUploadTitleText.displayName = 'MultipleFileUploadTitleText';
jelly/patternfly-react
packages/react-core/src/components/Hint/HintFooter.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Hint/hint'; import { css } from '@patternfly/react-styles'; export interface HintFooterProps { /** Content rendered inside the hint footer. */ children?: React.ReactNode; /** Additional classes applied to the hint footer. */ className?: string; } export const HintFooter: React.FunctionComponent<HintFooterProps> = ({ children, className, ...props }: HintFooterProps) => ( <div className={css(styles.hintFooter, className)} {...props}> {children} </div> ); HintFooter.displayName = 'HintFooter';
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/BackToTopDemo/BackToTopDemo.tsx
<reponame>jelly/patternfly-react<gh_stars>100-1000 import React from 'react'; import { BackToTop, Card, CardBody, Gallery, GalleryItem, PageSection, PageSectionVariants, TextContent, Text, Page } from '@patternfly/react-core'; export const BackToTopDemo = () => ( <Page> <PageSection variant={PageSectionVariants.light}> <TextContent> <Text component="h1">Main title</Text> <Text component="p"> Body text should be Overpass Regular at 16px.It should have leading of 24px because <br /> of it’s relative line height of 1.5. </Text> </TextContent> </PageSection> <PageSection hasOverflowScroll name="scrolling-section"> <Gallery hasGutter> {Array.apply(0, Array(60)).map((_x: any, i: number) => ( <GalleryItem key={i}> <Card key={i}> <CardBody> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas fermentum et urna eget semper. Sed tincidunt purus diam, id sollicitudin est pellentesque eget. Ut eget massa dignissim dolor pretium finibus at sit amet purus. Duis vulputate odio ac tristique convallis. Praesent porttitor condimentum varius. Duis pharetra in ligula nec ornare. Vivamus tincidunt nulla a semper semper. Duis tincidunt gravida elit non vehicula. Nunc eu sem venenatis, lobortis lorem sed, consectetur erat. Nulla accumsan, justo ac fringilla imperdiet, risus magna mollis libero, sit amet malesuada quam enim vel odio. Nullam vitae feugiat sem. Suspendisse potenti. Mauris dolor enim, pretium a pulvinar ut, commodo at risus. </CardBody> </Card> </GalleryItem> ))} </Gallery> </PageSection> <BackToTop scrollableSelector='[name="scrolling-section"]' /> </Page> ); export default BackToTopDemo;
jelly/patternfly-react
packages/react-core/src/components/Pagination/__tests__/Generated/OptionsToggle.test.tsx
<reponame>jelly/patternfly-react<gh_stars>0 /** * This test was generated */ import * as React from 'react'; import { render } from '@testing-library/react'; import { OptionsToggle } from '../../OptionsToggle'; // any missing imports can usually be resolved by adding them here import {} from '../..'; it('OptionsToggle should match snapshot (auto-generated)', () => { const { asFragment } = render( <OptionsToggle itemsTitle={"'items'"} optionsToggle={"'Select'"} itemsPerPageTitle={"'Items per page'"} firstIndex={0} lastIndex={0} itemCount={0} widgetId={"''"} showToggle={true} onToggle={(_isOpen: boolean) => undefined as any} isOpen={false} isDisabled={false} parentRef={null} toggleTemplate={''} onEnter={null} /> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/MultipleFileUploadTitleIcon.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/MultipleFileUpload/multiple-file-upload'; import { css } from '@patternfly/react-styles'; export interface MultipleFileUploadTitleIconProps extends React.HTMLProps<HTMLDivElement> { /** Content rendered inside multiple file upload title icon */ children?: React.ReactNode; /** Class to add to outer div */ className?: string; } export const MultipleFileUploadTitleIcon: React.FunctionComponent<MultipleFileUploadTitleIconProps> = ({ children, className, ...props }: MultipleFileUploadTitleIconProps) => ( <div className={css(styles.multipleFileUploadTitleIcon, className)} {...props}> {children} </div> ); MultipleFileUploadTitleIcon.displayName = 'MultipleFileUploadTitleIcon';
jelly/patternfly-react
packages/react-core/src/components/Accordion/__tests__/Accordion.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import { Accordion } from '../Accordion'; import { AccordionToggle } from '../AccordionToggle'; import { AccordionContent } from '../AccordionContent'; import { AccordionItem } from '../AccordionItem'; import { AccordionExpandedContentBody } from '../AccordionExpandedContentBody'; describe('Accordion', () => { test('Accordion default', () => { const { asFragment } = render(<Accordion aria-label="this is a simple accordion" />); expect(asFragment()).toMatchSnapshot(); }); test('Accordion with non-default headingLevel', () => { const { asFragment } = render( <Accordion asDefinitionList={false} headingLevel="h2"> <AccordionItem> <AccordionToggle id="item-1">Item One</AccordionToggle> <AccordionContent>Item One Content</AccordionContent> </AccordionItem> </Accordion> ); expect(asFragment()).toMatchSnapshot(); }); test('It should pass optional aria props', () => { render( <Accordion asDefinitionList> <AccordionToggle aria-label="Toggle details for" aria-labelledby="ex-toggle2 ex-item2" id="ex-toggle2" /> </Accordion> ); const button = screen.getByRole('button'); expect(button).toHaveAttribute('aria-label', 'Toggle details for'); expect(button).toHaveAttribute('aria-labelledby', 'ex-toggle2 ex-item2'); expect(button).toHaveAttribute('aria-expanded', 'false'); }); test('Toggle expanded', () => { render( <Accordion asDefinitionList> <AccordionToggle aria-label="Toggle details for" id="ex-toggle2" isExpanded /> </Accordion> ); const button = screen.getByRole('button'); expect(button).toHaveAttribute('aria-expanded', 'true'); expect(button).toHaveClass('pf-m-expanded'); }); test('renders content with custom Toggle and Content containers', () => { const container = 'a'; const { asFragment } = render( <Accordion headingLevel="h2"> <AccordionItem> <AccordionToggle id="item-1" component={container}> Item One </AccordionToggle> <AccordionContent component={container}>Item One Content</AccordionContent> </AccordionItem> </Accordion> ); expect(screen.getByText('Item One')).toBeInTheDocument(); expect(screen.getByText('Item One Content')).toBeInTheDocument(); }); test('Accordion bordered', () => { const { asFragment } = render( <Accordion isBordered> <AccordionItem> <AccordionToggle id="item-1">Item One</AccordionToggle> <AccordionContent>Item One Content</AccordionContent> </AccordionItem> </Accordion> ); expect(asFragment()).toMatchSnapshot(); }); test('Accordion display large', () => { const { asFragment } = render( <Accordion displaySize="large"> <AccordionItem> <AccordionToggle id="item-1">Item One</AccordionToggle> <AccordionContent>Item One Content</AccordionContent> </AccordionItem> </Accordion> ); expect(asFragment()).toMatchSnapshot(); }); test('Accordion custom content', () => { const { asFragment } = render( <Accordion> <AccordionItem> <AccordionToggle id="item-1">Item One</AccordionToggle> <AccordionContent isCustomContent> <AccordionExpandedContentBody>Item one content body 1</AccordionExpandedContentBody> <AccordionExpandedContentBody>Item one Content body 2</AccordionExpandedContentBody> </AccordionContent> </AccordionItem> </Accordion> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/DatePicker/examples/DatePickerControlled.tsx
<filename>packages/react-core/src/components/DatePicker/examples/DatePickerControlled.tsx import React from 'react'; import { Button, DatePicker } from '@patternfly/react-core'; export const DatePickerControlled: React.FunctionComponent = () => { const initialValue = '2020-03-17'; const [value, setValue] = React.useState(initialValue); return ( <React.Fragment> <Button onClick={() => setValue(initialValue)}>Reset date</Button> <DatePicker value={value} onChange={value => setValue(value)} /> </React.Fragment> ); };
jelly/patternfly-react
packages/react-integration/cypress/integration/labelgroupwithcategory.spec.ts
<reponame>jelly/patternfly-react describe('Label Group with Category Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/labelgroup-with-category-demo-nav-link'); }); it('Verify delete button on first label group', () => { const labelGroup = cy.get('.pf-c-label-group').first(); const labelGroupButton = labelGroup.get('#remove_group_category-1'); labelGroupButton.should('be.visible'); labelGroupButton.click(); labelGroup.should('not.exist'); }); it('Displays Tooltip', () => { cy.get('.pf-c-label-group__label') .last() .then((tooltipLink: JQuery<HTMLHeadingElement>) => { cy.get('.pf-c-tooltip').should('not.exist'); cy.wrap(tooltipLink) .trigger('mouseenter') .get('.pf-c-tooltip') .should('exist') .get('.pf-c-tooltip') .contains('Category 3 has a very long name'); }); }); });
jelly/patternfly-react
packages/react-core/src/demos/examples/HelperText/HelperTextStaticVariantStaticText.tsx
<reponame>jelly/patternfly-react import React from 'react'; import { Form, FormGroup, FormHelperText, TextInput, HelperText, HelperTextItem } from '@patternfly/react-core'; export const HelperTextStaticVariantStaticText: React.FunctionComponent = () => { const [value, setValue] = React.useState(''); const handleInputChange = (inputValue: string) => { setValue(inputValue); }; return ( <Form> <FormGroup label="<NAME>" fieldId="login-input-helper-text1"> <TextInput type="text" id="login-input-helper-text1" name="login-input-helper-text1" onChange={handleInputChange} aria-describedby="helper-text1" value={value} /> <FormHelperText isHidden={false} component="div"> <HelperText id="helper-text1"> <HelperTextItem variant={'default'}>Enter your middle name or your middle initial</HelperTextItem> </HelperText> </FormHelperText> </FormGroup> </Form> ); };
jelly/patternfly-react
packages/react-core/src/components/ApplicationLauncher/__tests__/Generated/ApplicationLauncherContent.test.tsx
<filename>packages/react-core/src/components/ApplicationLauncher/__tests__/Generated/ApplicationLauncherContent.test.tsx /** * This test was generated */ import * as React from 'react'; import { render } from '@testing-library/react'; import { ApplicationLauncherContent } from '../../ApplicationLauncherContent'; // any missing imports can usually be resolved by adding them here import {} from '../..'; it('ApplicationLauncherContent should match snapshot (auto-generated)', () => { const { asFragment } = render(<ApplicationLauncherContent children={<div>ReactNode</div>} />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/utils/format.ts
<reponame>jelly/patternfly-react // @ts-nocheck /** * @param str * @param args */ export default function format(str: string, ...args: string[]) { return [...args].reduce((p, c) => p.replace(/%s/, c), str); }
jelly/patternfly-react
packages/react-core/src/components/ContextSelector/__tests__/ContextSelectorToggle.test.tsx
<reponame>jelly/patternfly-react<filename>packages/react-core/src/components/ContextSelector/__tests__/ContextSelectorToggle.test.tsx<gh_stars>0 import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { ContextSelectorToggle } from '../ContextSelectorToggle'; describe('ContextSelectorToggle', () => { test('Renders ContextSelectorToggle', () => { const { asFragment } = render(<ContextSelectorToggle id="toggle-id" />); expect(asFragment()).toMatchSnapshot(); }); test('Verify onToggle is called ', () => { const mockfnOnToggle = jest.fn(); render(<ContextSelectorToggle onToggle={mockfnOnToggle} id="toggle-id" />); userEvent.click(screen.getByRole('button')); expect(mockfnOnToggle).toHaveBeenCalledTimes(1); }); test('Verify ESC press', () => { const { asFragment } = render(<ContextSelectorToggle isOpen id="toggle-id" />); userEvent.type(screen.getByRole('button'), '{esc}'); expect(asFragment()).toMatchSnapshot(); }); test('Verify ESC press with not isOpen', () => { const { asFragment } = render(<ContextSelectorToggle onToggle={jest.fn()} id="toggle-id" />); userEvent.type(screen.getByRole('button'), '{esc}'); expect(asFragment()).toMatchSnapshot(); }); test('Verify keydown tab ', () => { const { asFragment } = render(<ContextSelectorToggle isOpen id="toggle-id" />); userEvent.type(screen.getByRole('button'), '{tab}'); expect(asFragment()).toMatchSnapshot(); }); test('Verify keydown enter ', () => { const { asFragment } = render(<ContextSelectorToggle onToggle={jest.fn()} onEnter={jest.fn()} id="toggle-id" />); userEvent.type(screen.getByRole('button'), '{enter}'); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/ExpandableSection/__tests__/ExpandableSection.test.tsx
<filename>packages/react-core/src/components/ExpandableSection/__tests__/ExpandableSection.test.tsx import * as React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { ExpandableSection } from '../ExpandableSection'; import { ExpandableSectionToggle } from '../ExpandableSectionToggle'; const props = {}; test('ExpandableSection', () => { const { asFragment } = render(<ExpandableSection {...props}>test </ExpandableSection>); expect(asFragment()).toMatchSnapshot(); }); test('Renders ExpandableSection expanded', () => { const { asFragment } = render(<ExpandableSection isExpanded> test </ExpandableSection>); expect(asFragment()).toMatchSnapshot(); }); test('ExpandableSection onToggle called', () => { const mockfn = jest.fn(); render(<ExpandableSection onToggle={mockfn}> test </ExpandableSection>); userEvent.click(screen.getByRole('button')); expect(mockfn.mock.calls).toHaveLength(1); }); test('Renders Uncontrolled ExpandableSection', () => { const { asFragment } = render(<ExpandableSection toggleText="Show More"> test </ExpandableSection>); expect(asFragment()).toMatchSnapshot(); }); test('Detached ExpandableSection renders successfully', () => { const { asFragment } = render( <React.Fragment> <ExpandableSection {...props} isExpanded isDetached contentId="test"> test </ExpandableSection> <ExpandableSectionToggle isExpanded contentId="test" direction="up"> Toggle text </ExpandableSectionToggle> </React.Fragment> ); expect(asFragment()).toMatchSnapshot(); }); test('Disclosure ExpandableSection', () => { const { asFragment } = render( <ExpandableSection {...props} displaySize="large" isWidthLimited> test{' '} </ExpandableSection> ); expect(asFragment()).toMatchSnapshot(); }); test('Renders ExpandableSection indented', () => { const { asFragment } = render( <ExpandableSection isExpanded isIndented> {' '} test{' '} </ExpandableSection> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/dom-utils/getWindow.ts
// @ts-nocheck /* :: import type { Window } from '../types'; */ /* :: declare function getWindow(node: Node | Window): Window; */ /** * @param node */ export default function getWindow(node) { if (node.toString() !== '[object Window]') { const ownerDocument = node.ownerDocument; return ownerDocument ? ownerDocument.defaultView : window; } return node; }
jelly/patternfly-react
packages/react-core/src/components/TreeView/index.ts
export * from './TreeView'; export * from './TreeViewSearch';
jelly/patternfly-react
packages/react-console/src/components/SerialConsole/__tests__/SerialConsoleActions.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { SerialConsoleActions } from '../SerialConsoleActions'; test('Render SerialConsoleActions', () => { const { asFragment } = render(<SerialConsoleActions onDisconnect={jest.fn()} onReset={jest.fn()} />); expect(asFragment()).toMatchSnapshot(); }); test('Render SerialConsoleActions with custom texts', () => { const { asFragment } = render( <SerialConsoleActions onDisconnect={jest.fn()} onReset={jest.fn()} textDisconnect="My Disconnect Text" textReset="My Reconnect Text" /> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/ClipboardCopy/examples/ClipboardCopyReadOnlyExpanded.tsx
<gh_stars>0 import React from 'react'; import { ClipboardCopy, ClipboardCopyVariant } from '@patternfly/react-core'; export const ClipboardCopyReadOnlyExpanded: React.FunctionComponent = () => ( <ClipboardCopy isReadOnly hoverTip="Copy" clickTip="Copied" variant={ClipboardCopyVariant.expansion}> Got a lot of text here, need to see all of it? Click that arrow on the left side and check out the resulting expansion. </ClipboardCopy> );
jelly/patternfly-react
packages/react-core/src/components/Tabs/__tests__/TabButton.test.tsx
import React from 'react'; import { render } from '@testing-library/react'; import { TabButton } from '../TabButton'; test('should render tab button', () => { const { asFragment } = render(<TabButton>Tab button</TabButton>); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/Card/examples/CardWithModifiers.tsx
import React from 'react'; import { Card, CardTitle, CardBody, CardFooter, Checkbox } from '@patternfly/react-core'; export const CardWithModifiers: React.FunctionComponent = () => { const mods = ['isCompact', 'isFlat', 'isRounded', 'isLarge', 'isFullHeight', 'isPlain']; const [modifiers, setModifiers] = React.useState({}); return ( <React.Fragment> <div style={{ marginBottom: '12px' }}> {mods.map(mod => ( <Checkbox id={mod} key={mod} label={mod} isChecked={modifiers[mod]} onChange={checked => { modifiers[mod] = checked; setModifiers({ ...modifiers }); }} /> ))} </div> <div style={{ height: '15rem' }}> <Card {...modifiers}> <CardTitle>Header</CardTitle> <CardBody>Body</CardBody> <CardFooter>Footer</CardFooter> </Card> </div> </React.Fragment> ); };
jelly/patternfly-react
packages/react-core/src/components/DataList/examples/DataListExpandable.tsx
<filename>packages/react-core/src/components/DataList/examples/DataListExpandable.tsx<gh_stars>0 import React from 'react'; import { DataList, DataListItem, DataListItemRow, DataListCell, DataListAction, DataListToggle, DataListContent, DataListItemCells, Dropdown, DropdownItem, DropdownPosition, KebabToggle } from '@patternfly/react-core'; import CodeBranchIcon from '@patternfly/react-icons/dist/esm/icons/code-branch-icon'; export const DataListExpandable: React.FunctionComponent = () => { const [isOpen1, setIsOpen1] = React.useState(false); const [isOpen2, setIsOpen2] = React.useState(false); const [isOpen3, setIsOpen3] = React.useState(false); const [expanded, setExpanded] = React.useState(['ex-toggle1', 'ex-toggle3']); const onToggle1 = isOpen1 => { setIsOpen1(isOpen1); }; const onSelect1 = () => { setIsOpen1(!isOpen1); }; const onToggle2 = isOpen2 => { setIsOpen2(isOpen2); }; const onSelect2 = () => { setIsOpen2(!isOpen2); }; const onToggle3 = isOpen3 => { setIsOpen3(isOpen3); }; const onSelect3 = () => { setIsOpen3(!isOpen3); }; const toggle = id => { const index = expanded.indexOf(id); const newExpanded = index >= 0 ? [...expanded.slice(0, index), ...expanded.slice(index + 1, expanded.length)] : [...expanded, id]; setExpanded(newExpanded); }; return ( <React.Fragment> <DataList aria-label="Expandable data list example"> <DataListItem aria-labelledby="ex-item1" isExpanded={expanded.includes('ex-toggle1')}> <DataListItemRow> <DataListToggle onClick={() => toggle('ex-toggle1')} isExpanded={expanded.includes('ex-toggle1')} id="ex-toggle1" aria-controls="ex-expand1" /> <DataListItemCells dataListCells={[ <DataListCell isIcon key="icon"> <CodeBranchIcon /> </DataListCell>, <DataListCell key="primary content"> <div id="ex-item1">Primary content</div> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> <a href="#">link</a> </DataListCell>, <DataListCell key="secondary content"> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> </DataListCell>, <DataListCell key="secondary content 2"> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> </DataListCell> ]} /> <DataListAction aria-labelledby="ex-item1 ex-action1" id="ex-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> <DataListContent aria-label="Primary Content Details" id="ex-expand1" isHidden={!expanded.includes('ex-toggle1')} > <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </DataListContent> </DataListItem> <DataListItem aria-labelledby="ex-item2" isExpanded={expanded.includes('ex-toggle2')}> <DataListItemRow> <DataListToggle onClick={() => toggle('ex-toggle2')} isExpanded={expanded.includes('ex-toggle2')} id="ex-toggle2" aria-controls="ex-expand2" /> <DataListItemCells dataListCells={[ <DataListCell isIcon key="icon"> <CodeBranchIcon /> </DataListCell>, <DataListCell key="secondary content"> <div id="ex-item2">Secondary content</div> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> </DataListCell>, <DataListCell key="secondary content 2"> <span>Lorem ipsum dolor sit amet.</span> </DataListCell>, <DataListCell key="secondary content3"> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> </DataListCell> ]} /> <DataListAction aria-labelledby="ex-item2 ex-action2" id="ex-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> <DataListContent aria-label="Primary Content Details" id="ex-expand2" isHidden={!expanded.includes('ex-toggle2')} > <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p> </DataListContent> </DataListItem> <DataListItem aria-labelledby="ex-item3" isExpanded={expanded.includes('ex-toggle3')}> <DataListItemRow> <DataListToggle onClick={() => toggle('ex-toggle3')} isExpanded={expanded.includes('ex-toggle3')} id="ex-toggle3" aria-controls="ex-expand3" /> <DataListItemCells dataListCells={[ <DataListCell isIcon key="icon"> <CodeBranchIcon /> </DataListCell>, <DataListCell key="tertiary content"> <div id="ex-item3">Tertiary content</div> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> </DataListCell>, <DataListCell key="secondary content"> <span>Lorem ipsum dolor sit amet.</span> </DataListCell>, <DataListCell key="secondary content 2"> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> </DataListCell> ]} /> <DataListAction aria-labelledby="ex-item3 ex-action3" id="ex-action3" aria-label="Actions" isPlainButtonAction > <Dropdown isPlain position={DropdownPosition.right} isOpen={isOpen3} onSelect={onSelect3} toggle={<KebabToggle onToggle={onToggle3} />} dropdownItems={[ <DropdownItem key="link">Link</DropdownItem>, <DropdownItem key="action" component="button"> Action </DropdownItem>, <DropdownItem key="disabled link" isDisabled> Disabled Link </DropdownItem> ]} /> </DataListAction> </DataListItemRow> <DataListContent aria-label="Primary Content Details" id="ex-expand3" isHidden={!expanded.includes('ex-toggle3')} hasNoPadding > This expanded section has no padding. </DataListContent> </DataListItem> </DataList> </React.Fragment> ); };
jelly/patternfly-react
packages/react-core/src/helpers/Popper/thirdparty/popper-core/dom-utils/getParentNode.ts
<reponame>jelly/patternfly-react // @ts-nocheck import getNodeName from './getNodeName'; import getDocumentElement from './getDocumentElement'; /** * @param element */ export default function getParentNode(element: Node | ShadowRoot): Node { if (getNodeName(element) === 'html') { return element; } return ( // $FlowFixMe: this is a quicker (but less type safe) way to save quite some bytes from the bundle element.assignedSlot || // step into the shadow DOM of the parent of a slotted node element.parentNode || // DOM Element detected // $FlowFixMe: need a better way to handle this... element.host || // ShadowRoot detected // $FlowFixMe: HTMLElement is a Node getDocumentElement(element) // fallback ); }
jelly/patternfly-react
packages/react-integration/cypress/integration/login-page.spec.ts
<gh_stars>100-1000 describe('Login Page Demo Test', () => { it('Navigate to login page section', () => { cy.visit('http://localhost:3000/login-page-demo-nav-link'); }); it('Verify initial state', () => { cy.get('input[name="pf-login-username-id"]').then(userNameInput => expect(userNameInput.text()).to.equal('')); cy.get('input[name="pf-login-password-id"]').then(passwordInput => expect(passwordInput.text()).to.equal('')); cy.get('#pf-login-remember-me-id').then(rememberMeBox => expect(rememberMeBox.is(':checked')).to.be.false); cy.get('.pf-c-form__helper-text.pf-m-error').should('not.exist'); cy.get('.pf-c-login__main-footer-links') .find('.pf-c-login__main-footer-links-item') .then(links => expect(links.length).to.equal(5)); }); it('Verify error is shown on invalid credentials', () => { cy.get('.pf-c-login__main-body .pf-c-button.pf-m-primary').then((loginButton: JQuery<HTMLButtonElement>) => { cy.wrap(loginButton).click(); cy.get('.pf-c-form__helper-text.pf-m-error').then(errorMessage => { expect(errorMessage.length).to.equal(1); }); cy.get('input[name="pf-login-username-id"][aria-invalid="true"]').then(userNameInput => { expect(userNameInput.length).to.equal(1); }); cy.get('input[name="pf-login-password-id"][aria-invalid="true"]').then(passwordInput => { expect(passwordInput.length).to.equal(1); }); }); }); it('Verify show/hide password toggles', () => { cy.get('[type="password"]').should('exist'); cy.get('[aria-label="Test show password"]').should('exist'); cy.get('[type="password"]') .clear() .type('<PASSWORD>'); cy.get('[type="password"]').should('have.value', '<PASSWORD>'); cy.get('[aria-label="Test show password"]').click(); cy.get('[type="password"]').should('not.exist'); cy.get('[aria-label="Test show password"]').should('not.exist'); cy.get('[aria-label="Test hide password"]').should('exist'); cy.get('#pf-login-password-id').should('have.value', '<PASSWORD>'); cy.get('[aria-label="Test hide password"]').click(); cy.get('[type="password"]').should('exist'); cy.get('[aria-label="Test show password"]').should('exist'); cy.get('[aria-label="Test hide password"]').should('not.exist'); }); });
jelly/patternfly-react
packages/react-integration/cypress/integration/descriptionlistbreakpoints.spec.ts
<filename>packages/react-integration/cypress/integration/descriptionlistbreakpoints.spec.ts<gh_stars>100-1000 describe('Description List Breakpoints Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/description-list-breakpoints-demo-nav-link'); }); it('Verify 1Col modifier applied for all viewport sizes ', () => { cy.get('#1-col-description-list.pf-m-1-col').should('exist'); cy.get('#1-col-description-list.pf-m-1-col-on-md').should('exist'); cy.get('#1-col-description-list.pf-m-1-col-on-lg').should('exist'); cy.get('#1-col-description-list.pf-m-1-col-on-xl').should('exist'); cy.get('#1-col-description-list.pf-m-1-col-on-2xl').should('exist'); }); it('Verify 2Col modifier applied for all viewport sizes ', () => { cy.get('#2-col-description-list.pf-m-2-col').should('exist'); cy.get('#2-col-description-list.pf-m-2-col-on-md').should('exist'); cy.get('#2-col-description-list.pf-m-2-col-on-lg').should('exist'); cy.get('#2-col-description-list.pf-m-2-col-on-xl').should('exist'); cy.get('#2-col-description-list.pf-m-2-col-on-2xl').should('exist'); }); it('Verify 3Col modifier applied for all viewport sizes ', () => { cy.get('#3-col-description-list.pf-m-3-col').should('exist'); cy.get('#3-col-description-list.pf-m-3-col-on-md').should('exist'); cy.get('#3-col-description-list.pf-m-3-col-on-lg').should('exist'); cy.get('#3-col-description-list.pf-m-3-col-on-xl').should('exist'); cy.get('#3-col-description-list.pf-m-3-col-on-2xl').should('exist'); }); it('Verify description list has layout breakpoints', () => { const list = cy.get('#orientation-description-list'); list.should('have.class', 'pf-m-horizontal-on-sm'); list.should('have.class', 'pf-m-vertical-on-md'); list.should('have.class', 'pf-m-horizontal-on-lg'); list.should('have.class', 'pf-m-vertical-on-xl'); list.should('have.class', 'pf-m-horizontal-on-2xl'); }); });
jelly/patternfly-react
packages/react-core/src/components/TextInputGroup/TextInputGroupMain.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/TextInputGroup/text-input-group'; import { css } from '@patternfly/react-styles'; import { TextInputGroupContext } from './TextInputGroup'; export interface TextInputGroupMainProps extends Omit<React.HTMLProps<HTMLDivElement>, 'onChange'> { /** Content rendered inside the text input group main div */ children?: React.ReactNode; /** Additional classes applied to the text input group main container */ className?: string; /** Icon to be shown on the left side of the text input group main container */ icon?: React.ReactNode; /** Type that the input accepts. */ type?: | 'text' | 'date' | 'datetime-local' | 'email' | 'month' | 'number' | 'password' | 'search' | 'tel' | 'time' | 'url'; /** Suggestion that will show up like a placeholder even with text in the input */ hint?: string; /** Callback for when there is a change in the input field*/ onChange?: (value: string, event: React.FormEvent<HTMLInputElement>) => void; /** Callback for when the input field is focused*/ onFocus?: (event?: any) => void; /** Callback for when focus is lost on the input field*/ onBlur?: (event?: any) => void; /** Accessibility label for the input */ 'aria-label'?: string; /** Value for the input */ value?: string | number; /** Placeholder value for the input */ placeholder?: string; } export const TextInputGroupMain: React.FunctionComponent<TextInputGroupMainProps> = ({ children, className, icon, type = 'text', hint, onChange = (): any => undefined, onFocus, onBlur, 'aria-label': ariaLabel = 'Type to filter', value: inputValue, placeholder: inputPlaceHolder, ...props }: TextInputGroupMainProps) => { const { isDisabled } = React.useContext(TextInputGroupContext); const handleChange = (event: React.FormEvent<HTMLInputElement>) => { onChange(event.currentTarget.value, event); }; return ( <div className={css(styles.textInputGroupMain, icon && styles.modifiers.icon, className)} {...props}> {children} <span className={css(styles.textInputGroupText)}> {hint && ( <input className={css(styles.textInputGroupTextInput, styles.modifiers.hint)} type="text" disabled aria-hidden="true" value={hint} /> )} {icon && <span className={css(styles.textInputGroupIcon)}>{icon}</span>} <input type={type} className={css(styles.textInputGroupTextInput)} aria-label={ariaLabel} disabled={isDisabled} onChange={handleChange} onFocus={onFocus} onBlur={onBlur} value={inputValue || ''} placeholder={inputPlaceHolder} /> </span> </div> ); }; TextInputGroupMain.displayName = 'TextInputGroupMain';
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/CustomCircleNode.tsx
<reponame>jelly/patternfly-react<filename>packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/CustomCircleNode.tsx import * as React from 'react'; import { observer } from 'mobx-react'; import { WithCreateConnectorProps, Dimensions, Node, WithContextMenuProps, WithDragNodeProps, WithSelectionProps, WithDndDragProps, WithDndDropProps, ShapeProps, useAnchor, EllipseAnchor, action } from '@patternfly/react-topology'; import DemoDefaultNode from './DemoDefaultNode'; type CustomCircleNodeProps = { element: Node; droppable?: boolean; canDrop?: boolean; } & WithSelectionProps & WithDragNodeProps & WithDndDragProps & WithDndDropProps & WithCreateConnectorProps & WithContextMenuProps; const CustomCircle: React.FunctionComponent<ShapeProps> = ({ element, className }) => { useAnchor(EllipseAnchor); React.useEffect(() => { // init height action(() => element.setDimensions(new Dimensions(40, 40)))(); }, [element]); const r = element.getDimensions().width / 2; return ( <circle className={className} cx={r} cy={r} r={r} onClick={() => { const size = element.getDimensions().width === 40 ? 80 : 40; action(() => element.setDimensions(new Dimensions(size, size)))(); }} /> ); }; const CustomCircleNode: React.FunctionComponent<CustomCircleNodeProps> = props => ( <DemoDefaultNode getCustomShape={() => CustomCircle} {...props} /> ); export default observer(CustomCircleNode);
jelly/patternfly-react
packages/react-topology/src/layouts/ConcentricGroup.ts
<reponame>jelly/patternfly-react import { LayoutGroup } from './LayoutGroup'; export class ConcentricGroup extends LayoutGroup {}
jelly/patternfly-react
packages/react-core/src/components/MultipleFileUpload/__tests__/MultipleFileUploadStatus.test.tsx
<filename>packages/react-core/src/components/MultipleFileUpload/__tests__/MultipleFileUploadStatus.test.tsx import React from 'react'; import { render, screen } from '@testing-library/react'; import { MultipleFileUploadStatus } from '../MultipleFileUploadStatus'; import InProgressIcon from '@patternfly/react-icons/dist/esm/icons/in-progress-icon'; describe('MultipleFileUploadStatus', () => { test('renders with expected class names', () => { const { asFragment } = render(<MultipleFileUploadStatus>Foo</MultipleFileUploadStatus>); expect(asFragment()).toMatchSnapshot(); }); test('renders custom class names', () => { const { asFragment } = render(<MultipleFileUploadStatus className="test">Foo</MultipleFileUploadStatus>); expect(asFragment()).toMatchSnapshot(); }); test('renders status toggle text', () => { const { asFragment } = render(<MultipleFileUploadStatus statusToggleText="test">Foo</MultipleFileUploadStatus>); expect(asFragment()).toMatchSnapshot(); }); test('renders status toggle icon', () => { const { asFragment } = render( <MultipleFileUploadStatus statusToggleIcon={<InProgressIcon />}>Foo</MultipleFileUploadStatus> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/AlertGroup/examples/AlertGroupSingularDynamicOverflow.tsx
<gh_stars>0 import React from 'react'; import { Alert, AlertProps, AlertGroup, AlertActionCloseButton, AlertVariant, InputGroup } from '@patternfly/react-core'; export const AlertGroupSingularDynamicOverflow: React.FunctionComponent = () => { const [alerts, setAlerts] = React.useState<Partial<AlertProps>[]>([]); const [overflowMessage, setOverflowMessage] = React.useState<string>(''); const maxDisplayed = 4; const getOverflowMessage = (alertsNumber: number) => { const overflow = alertsNumber - maxDisplayed; if (overflow > 0) { return `View ${overflow} more alerts`; } return ''; }; const addAlert = (title: string, variant: AlertProps['variant'], key: React.Key) => { setAlerts(prevAlerts => [...prevAlerts, { title, variant, key }]); setOverflowMessage(getOverflowMessage(alerts.length + 1)); }; const removeAlert = (key: React.Key) => { const newAlerts = alerts.filter(alert => alert.key !== key); setAlerts(newAlerts); setOverflowMessage(getOverflowMessage(newAlerts.length)); }; const btnClasses = ['pf-c-button', 'pf-m-secondary'].join(' '); const getUniqueId = () => new Date().getTime(); const addSuccessAlert = () => { addAlert('Toast success alert', 'success', getUniqueId()); }; const addDangerAlert = () => { addAlert('Toast danger alert', 'danger', getUniqueId()); }; const addInfoAlert = () => { addAlert('Toast info alert', 'info', getUniqueId()); }; const onOverflowClick = () => { // eslint-disable-next-line no-console console.log('Overflow message clicked'); }; return ( <React.Fragment> <InputGroup style={{ marginBottom: '16px' }}> <button onClick={addSuccessAlert} type="button" className={btnClasses}> Add single success alert </button> <button onClick={addDangerAlert} type="button" className={btnClasses}> Add single danger alert </button> <button onClick={addInfoAlert} type="button" className={btnClasses}> Add single info alert </button> </InputGroup> <AlertGroup isLiveRegion onOverflowClick={onOverflowClick} overflowMessage={overflowMessage}> {alerts.slice(0, maxDisplayed).map(({ key, variant, title }) => ( <Alert isInline variant={AlertVariant[variant]} title={title} actionClose={ <AlertActionCloseButton title={title as string} variantLabel={`${variant} alert`} onClose={() => removeAlert(key)} /> } key={key} /> ))} </AlertGroup> </React.Fragment> ); };
jelly/patternfly-react
packages/react-core/src/components/DualListSelector/index.ts
export * from './DualListSelector'; export * from './DualListSelectorControl'; export * from './DualListSelectorControlsWrapper'; export * from './DualListSelectorPane'; export * from './DualListSelectorList'; export * from './DualListSelectorListItem'; export * from './DualListSelectorTree';
jelly/patternfly-react
packages/react-topology/src/components/defs/__tests__/Defs.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import { Defs } from '../Defs'; describe('Defs', () => { it('should render initially empty', () => { render( <div data-testid="wrapper-test-id"> <Defs /> </div> ); expect(screen.getByTestId('wrapper-test-id').querySelector('defs')).toBeNull(); }); });
jelly/patternfly-react
packages/react-console/src/components/common/constants.tsx
const NONE_TYPE = '_none_'; const SERIAL_CONSOLE_TYPE = 'SerialConsole'; const SPICE_CONSOLE_TYPE = 'SpiceConsole'; const VNC_CONSOLE_TYPE = 'VncConsole'; const RDP_CONSOLE_TYPE = 'RdpConsole'; const DESKTOP_VIEWER_CONSOLE_TYPE = 'DesktopViewer'; const CONNECTING = 'connecting'; const CONNECTED = 'connected'; const DISCONNECTED = 'disconnected'; const LOADING = 'loading'; const DEFAULT_VV_FILENAME = 'console.vv'; const DEFAULT_VV_MIMETYPE = 'application/x-virt-viewer'; const DEFAULT_RDP_FILENAME = 'console.rdp'; const DEFAULT_RDP_MIMETYPE = 'application/rdp'; const DEFAULT_RDP_PORT = 3389; export const constants = { NONE_TYPE, SERIAL_CONSOLE_TYPE, SPICE_CONSOLE_TYPE, VNC_CONSOLE_TYPE, RDP_CONSOLE_TYPE, DESKTOP_VIEWER_CONSOLE_TYPE, CONNECTING, CONNECTED, DISCONNECTED, LOADING, DEFAULT_VV_FILENAME, DEFAULT_VV_MIMETYPE, DEFAULT_RDP_FILENAME, DEFAULT_RDP_MIMETYPE, DEFAULT_RDP_PORT };
jelly/patternfly-react
packages/react-core/src/components/Tooltip/__tests__/Tooltip.test.tsx
<filename>packages/react-core/src/components/Tooltip/__tests__/Tooltip.test.tsx import * as React from 'react'; import { render } from '@testing-library/react'; import { Tooltip } from '../Tooltip'; test('tooltip renders', () => { const { asFragment } = render( <Tooltip position="top" content={ <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam id feugiat augue, nec fringilla turpis. </div> } > <div>Toggle tooltip</div> </Tooltip> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/TextInputGroup/__tests__/TextInputGroupMain.test.tsx
import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import '@testing-library/jest-dom'; import { TextInputGroupMain } from '../TextInputGroupMain'; import { TextInputGroupContext } from '../TextInputGroup'; import SearchIcon from '@patternfly/react-icons/dist/esm/icons/search-icon'; describe('TextInputGroupMain', () => { it('renders without children', () => { render(<TextInputGroupMain data-testid="TextInputGroupMain" />); expect(screen.getByTestId('TextInputGroupMain')).toBeVisible(); }); it('renders children', () => { render(<TextInputGroupMain>Test</TextInputGroupMain>); expect(screen.getByText('Test')).toBeVisible(); }); it('renders with class pf-c-text-input-group__main', () => { render(<TextInputGroupMain>Test</TextInputGroupMain>); const inputGroupMain = screen.getByText('Test'); expect(inputGroupMain).toHaveClass('pf-c-text-input-group__main'); }); it('does not render with class pf-m-icon when an icon prop is not passed', () => { render(<TextInputGroupMain>Test</TextInputGroupMain>); const inputGroupMain = screen.getByText('Test'); expect(inputGroupMain).not.toHaveClass('pf-m-icon'); }); it('renders with class pf-m-icon when an icon prop is passed', () => { render(<TextInputGroupMain icon="icon">Test</TextInputGroupMain>); const inputGroupMain = screen.getByText('Test'); expect(inputGroupMain).toHaveClass('pf-m-icon'); }); it('renders with custom class names provided via prop', () => { render(<TextInputGroupMain className="custom-class">Test</TextInputGroupMain>); const inputGroupMain = screen.getByText('Test'); expect(inputGroupMain).toHaveClass('custom-class'); }); it('renders with class pf-c-text-input-group__text on the inputs parent', () => { render(<TextInputGroupMain>Test</TextInputGroupMain>); const inputGroupText = screen.getByRole('textbox').parentNode; expect(inputGroupText).toHaveClass('pf-c-text-input-group__text'); }); it('renders the input with class pf-c-text-input-group__text-input', () => { render(<TextInputGroupMain>Test</TextInputGroupMain>); const input = screen.getByRole('textbox'); expect(input).toHaveClass('pf-c-text-input-group__text-input'); }); it('does not render the icon when it is not passed', () => { render(<TextInputGroupMain />); const icon = screen.queryByRole('img', { hidden: true }); expect(icon).not.toBeInTheDocument(); }); it('renders the icon when passed', () => { render(<TextInputGroupMain icon={<SearchIcon />} />); const icon = screen.getByRole('img', { hidden: true }); expect(icon).toBeInTheDocument(); }); it('renders the icon as aria hidden', () => { render(<TextInputGroupMain icon={<SearchIcon />} />); const icon = screen.getByRole('img', { hidden: true }); expect(icon).toHaveAttribute('aria-hidden', 'true'); }); it('passes the aria-label prop to the input', () => { render(<TextInputGroupMain aria-label="Test label">Test</TextInputGroupMain>); const input = screen.getByRole('textbox'); expect(input).toHaveAccessibleName('Test label'); }); it('passes the value prop to the input', () => { render(<TextInputGroupMain value="value text">Test</TextInputGroupMain>); const inputValue = screen.getByDisplayValue('value text'); expect(inputValue).toBeVisible(); }); it('passes the placeholder prop to the input', () => { render(<TextInputGroupMain placeholder="placeholder text">Test</TextInputGroupMain>); const inputPlaceholder = screen.getByPlaceholderText('placeholder text'); expect(inputPlaceholder).toBeVisible(); }); it('defaults to an input type of text', () => { render(<TextInputGroupMain>Test</TextInputGroupMain>); const input = screen.getByRole('textbox'); expect(input).toHaveAttribute('type', 'text'); }); it('updates the input type when a different type is passed', () => { render(<TextInputGroupMain type="search">Test</TextInputGroupMain>); const textInput = screen.queryByRole('textbox'); const searchInput = screen.getByRole('searchbox'); expect(textInput).not.toBeInTheDocument(); expect(searchInput).toBeVisible(); }); it('does not disable the input when TextInputGroupContext isDisabled is false', () => { render( <TextInputGroupContext.Provider value={{ isDisabled: false }}> <TextInputGroupMain /> </TextInputGroupContext.Provider> ); const input = screen.getByRole('textbox'); expect(input).not.toBeDisabled(); }); it('disables the input when TextInputGroupContext isDisabled is true', () => { render( <TextInputGroupContext.Provider value={{ isDisabled: true }}> <TextInputGroupMain /> </TextInputGroupContext.Provider> ); const input = screen.getByRole('textbox'); expect(input).toBeDisabled(); }); it("doesn't render the hint input when a hint prop isn't passed", () => { // we set the type of the main input to search here so that we can accurately target the hint input render(<TextInputGroupMain type="search">Test</TextInputGroupMain>); const hintInput = screen.queryByRole('textbox', { hidden: true }); expect(hintInput).not.toBeInTheDocument(); }); it('renders the hint input when a hint prop is passed', () => { // we set the type of the main input to search here so that we can accurately target the hint input render( <TextInputGroupMain hint="Test" type="search"> Test </TextInputGroupMain> ); const hintInput = screen.getByRole('textbox', { hidden: true }); expect(hintInput).toBeInTheDocument(); }); it('renders the hint input with classes pf-c-text-input-group__text-input and pf-m-hint', () => { // we set the type of the main input to search here so that we can accurately target the hint input render( <TextInputGroupMain hint="Test" type="search"> Test </TextInputGroupMain> ); const hintInput = screen.getByRole('textbox', { hidden: true }); expect(hintInput).toHaveClass('pf-m-hint'); expect(hintInput).toHaveClass('pf-c-text-input-group__text-input'); }); it('renders the hint input as disabled', () => { // we set the type of the main input to search here so that we can accurately target the hint input render( <TextInputGroupMain hint="Test" type="search"> Test </TextInputGroupMain> ); const hintInput = screen.getByRole('textbox', { hidden: true }); expect(hintInput).toBeDisabled(); }); it('renders the hint input as aria-hidden', () => { // we set the type of the main input to search here so that we can accurately target the hint input render( <TextInputGroupMain hint="Test" type="search"> Test </TextInputGroupMain> ); const hintInput = screen.getByRole('textbox', { hidden: true }); expect(hintInput).toHaveAttribute('aria-hidden', 'true'); }); it('passes the hint prop to the hint input as its value', () => { // we set the type of the main input to search here so that we can accurately target the hint input render( <TextInputGroupMain hint="value text" type="search"> Test </TextInputGroupMain> ); const hintInput = screen.getByDisplayValue('value text'); expect(hintInput).toBeVisible(); }); it('does not call onChange callback when the input does not change', () => { const onChangeMock = jest.fn(); render(<TextInputGroupMain onChange={onChangeMock}>Test</TextInputGroupMain>); expect(onChangeMock).not.toHaveBeenCalled(); }); it('calls the onChange callback when the input changes', () => { const onChangeMock = jest.fn(); render(<TextInputGroupMain onChange={onChangeMock}>Test</TextInputGroupMain>); const input = screen.getByRole('textbox'); userEvent.type(input, 'Test'); expect(onChangeMock).toHaveBeenCalledTimes(4); }); it('does not call onFocus callback when the input does not get focus', () => { const onFocusMock = jest.fn(); render(<TextInputGroupMain onFocus={onFocusMock}>Test</TextInputGroupMain>); expect(onFocusMock).not.toHaveBeenCalled(); }); it('calls the onFocus callback when the input is focused', () => { const onFocusMock = jest.fn(); render(<TextInputGroupMain onFocus={onFocusMock}>Test</TextInputGroupMain>); const input = screen.getByRole('textbox'); userEvent.click(input); expect(onFocusMock).toHaveBeenCalledTimes(1); }); it('does not call onBlur callback when the input does not lose focus', () => { const onBlurMock = jest.fn(); render(<TextInputGroupMain onBlur={onBlurMock}>Test</TextInputGroupMain>); const input = screen.getByRole('textbox'); userEvent.click(input); expect(onBlurMock).not.toHaveBeenCalled(); }); it('calls the onBlur callback when the input loses focus', () => { const onBlurMock = jest.fn(); render(<TextInputGroupMain onBlur={onBlurMock}>Test</TextInputGroupMain>); const input = screen.getByRole('textbox'); userEvent.click(input); userEvent.click(document.body); expect(onBlurMock).toHaveBeenCalledTimes(1); }); it('matches the snapshot', () => { const { asFragment } = render(<TextInputGroupMain>Test</TextInputGroupMain>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/Drawer/DrawerHead.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Drawer/drawer'; import { css } from '@patternfly/react-styles'; import { DrawerPanelBody } from './DrawerPanelBody'; export interface DrawerHeadProps extends React.HTMLProps<HTMLDivElement> { /** Additional classes added to the drawer head. */ className?: string; /** Content to be rendered in the drawer head */ children?: React.ReactNode; /** Indicates if there should be no padding around the drawer panel body of the head*/ hasNoPadding?: boolean; } export const DrawerHead: React.FunctionComponent<DrawerHeadProps> = ({ // eslint-disable-next-line @typescript-eslint/no-unused-vars className = '', children, hasNoPadding = false, ...props }: DrawerHeadProps) => ( <DrawerPanelBody hasNoPadding={hasNoPadding}> <div className={css(styles.drawerHead, className)} {...props}> {children} </div> </DrawerPanelBody> ); DrawerHead.displayName = 'DrawerHead';
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/ChipGroupDemo/ChipGroupWithOverflowChipEventHandler.tsx
import React, { Component } from 'react'; import { Chip, ChipGroup } from '@patternfly/react-core'; interface ChipGroupWithOverflowChipEventHandlerState { chipArray: { name: string; }[]; shouldShowAdditionalText: boolean; } export class ChipGroupWithOverflowChipEventHandler extends Component<{}, ChipGroupWithOverflowChipEventHandlerState> { deleteItem: (id: string) => void; constructor(props: {}) { super(props); this.state = { chipArray: [ { name: 'Lemons' }, { name: 'Limes' }, { name: 'Peaches' }, { name: 'Pears' }, { name: 'Tangerines' } ], shouldShowAdditionalText: false }; this.deleteItem = (id: string) => { const copyOfChipArray = this.state.chipArray; const index = copyOfChipArray.findIndex(chipObj => chipObj.name === id); if (index !== -1) { copyOfChipArray.splice(index, 1); this.setState({ chipArray: copyOfChipArray }); } }; this.handleOverflowChipClick = this.handleOverflowChipClick.bind(this); } componentDidMount() { window.scrollTo(0, 0); } handleOverflowChipClick() { this.setState({ shouldShowAdditionalText: !this.state.shouldShowAdditionalText }); } render() { const { chipArray } = this.state; return ( <> <ChipGroup onOverflowChipClick={() => this.handleOverflowChipClick()}> {chipArray.map(chip => ( <Chip key={chip.name} onClick={() => this.deleteItem(chip.name)}> {chip.name} </Chip> ))} </ChipGroup> {this.state.shouldShowAdditionalText && ( <h1 className="pf-c-title pf-m-2xl pf-u-p-lg">Full results are currently expanded.</h1> )} </> ); } }
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/themes/bullet-theme.ts
<gh_stars>100-1000 /* eslint-disable camelcase */ import chart_bullet_Height from '@patternfly/react-tokens/dist/esm/chart_bullet_Height'; import chart_bullet_comparative_measure_Fill_Color from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_Fill_Color'; import chart_bullet_comparative_measure_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_stroke_Color'; import chart_bullet_comparative_measure_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_stroke_Width'; import chart_bullet_comparative_measure_error_Fill_Color from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_error_Fill_Color'; import chart_bullet_comparative_measure_error_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_error_stroke_Color'; import chart_bullet_comparative_measure_error_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_error_stroke_Width'; import chart_bullet_comparative_measure_warning_Fill_Color from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_warning_Fill_Color'; import chart_bullet_comparative_measure_warning_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_warning_stroke_Color'; import chart_bullet_comparative_measure_warning_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_bullet_comparative_measure_warning_stroke_Width'; import chart_bullet_group_title_divider_Fill_Color from '@patternfly/react-tokens/dist/esm/chart_bullet_group_title_divider_Fill_Color'; import chart_bullet_group_title_divider_stroke_Color from '@patternfly/react-tokens/dist/esm/chart_bullet_group_title_divider_stroke_Color'; import chart_bullet_group_title_divider_stroke_Width from '@patternfly/react-tokens/dist/esm/chart_bullet_group_title_divider_stroke_Width'; import chart_color_black_100 from '@patternfly/react-tokens/dist/esm/chart_color_black_100'; import chart_color_black_200 from '@patternfly/react-tokens/dist/esm/chart_color_black_200'; import chart_color_black_300 from '@patternfly/react-tokens/dist/esm/chart_color_black_300'; import chart_color_black_400 from '@patternfly/react-tokens/dist/esm/chart_color_black_400'; import chart_color_black_500 from '@patternfly/react-tokens/dist/esm/chart_color_black_500'; import chart_color_red_100 from '@patternfly/react-tokens/dist/esm/chart_color_red_100'; import chart_color_red_200 from '@patternfly/react-tokens/dist/esm/chart_color_red_200'; import chart_color_red_300 from '@patternfly/react-tokens/dist/esm/chart_color_red_300'; import chart_color_red_400 from '@patternfly/react-tokens/dist/esm/chart_color_red_400'; import chart_color_red_500 from '@patternfly/react-tokens/dist/esm/chart_color_red_500'; import chart_global_layout_Padding from '@patternfly/react-tokens/dist/esm/chart_global_layout_Padding'; // See https://docs.google.com/document/d/1cw10pJFXWruB1SA8TQwituxn5Ss6KpxYPCOYGrH8qAY/edit# // See https://www.patternfly.org/v3/pattern-library/data-visualization/bullet-chart/#design // Bullet theme export const BulletTheme = { chart: { height: chart_bullet_Height.value } }; // Bullet comparative measure error theme export const BulletComparativeErrorMeasureTheme = { bar: { height: chart_bullet_Height.value, style: { data: { fill: chart_bullet_comparative_measure_error_Fill_Color.value, stroke: chart_bullet_comparative_measure_error_stroke_Color.value, strokeWidth: chart_bullet_comparative_measure_error_stroke_Width.value } } } }; // Bullet comparative measure theme export const BulletComparativeMeasureTheme = { bar: { height: chart_bullet_Height.value, style: { data: { fill: chart_bullet_comparative_measure_Fill_Color.value, stroke: chart_bullet_comparative_measure_stroke_Color.value, strokeWidth: chart_bullet_comparative_measure_stroke_Width.value } } } }; // Bullet comparative measure warning theme export const BulletComparativeWarningMeasureTheme = { bar: { height: chart_bullet_Height.value, style: { data: { fill: chart_bullet_comparative_measure_warning_Fill_Color.value, stroke: chart_bullet_comparative_measure_warning_stroke_Color.value, strokeWidth: chart_bullet_comparative_measure_warning_stroke_Width.value } } } }; // Bullet group title theme export const BulletGroupTitleTheme = { chart: { padding: { bottom: 0, left: 0, right: 0, top: chart_global_layout_Padding.value } as any // Victory incorrectly typed ThemeBaseProps.padding as number instead of PaddingProps }, line: { style: { data: { fill: chart_bullet_group_title_divider_Fill_Color.value, stroke: chart_bullet_group_title_divider_stroke_Color.value, strokeWidth: chart_bullet_group_title_divider_stroke_Width.value } } } }; // Bullet primary dot measure theme export const BulletPrimaryDotMeasureTheme = { group: { height: chart_bullet_Height.value } }; // Bullet primary negative measure theme export const BulletPrimaryNegativeMeasureTheme = { group: { colorScale: [ chart_color_red_100.value, chart_color_red_200.value, chart_color_red_300.value, chart_color_red_400.value, chart_color_red_500.value ], height: chart_bullet_Height.value } }; // Bullet primary segmented measure theme export const BulletPrimarySegmentedMeasureTheme = { group: { height: chart_bullet_Height.value } }; // Bullet qualitative range theme export const BulletQualitativeRangeTheme = { group: { colorScale: [ chart_color_black_100.value, chart_color_black_200.value, chart_color_black_300.value, chart_color_black_400.value, chart_color_black_500.value ], height: chart_bullet_Height.value } };
jelly/patternfly-react
packages/react-table/src/components/Table/utils/decorators/textCenter.ts
<reponame>jelly/patternfly-react import { ITransform } from '../../TableTypes'; export const textCenter: ITransform = () => ({ textCenter: true });
jelly/patternfly-react
packages/react-core/src/components/Checkbox/examples/CheckboxDisabled.tsx
import React from 'react'; import { Checkbox } from '@patternfly/react-core'; export const CheckboxDisabled: React.FunctionComponent = () => ( <React.Fragment> <Checkbox id="disabled-check-1" label="Disabled CheckBox 1" defaultChecked isDisabled /> <Checkbox id="disabled-check-2" label="Disabled CheckBox 2" isDisabled /> </React.Fragment> );
jelly/patternfly-react
packages/react-core/src/components/DescriptionList/examples/DescriptionListHorizontalCustomTermWidth.tsx
<gh_stars>0 import React from 'react'; import { Button, DescriptionList, DescriptionListTerm, DescriptionListGroup, DescriptionListDescription } from '@patternfly/react-core'; import PlusCircleIcon from '@patternfly/react-icons/dist/esm/icons/plus-circle-icon'; export const DescriptionListHorizontalCustomTermWidth: React.FunctionComponent = () => ( <DescriptionList isHorizontal horizontalTermWidthModifier={{ default: '12ch', sm: '15ch', md: '20ch', lg: '28ch', xl: '30ch', '2xl': '35ch' }} > <DescriptionListGroup> <DescriptionListTerm>Name longer than the default term width</DescriptionListTerm> <DescriptionListDescription>Example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Namespace</DescriptionListTerm> <DescriptionListDescription> <a href="#">mary-test</a> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Labels</DescriptionListTerm> <DescriptionListDescription>example</DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Pod selector</DescriptionListTerm> <DescriptionListDescription> <Button variant="link" isInline icon={<PlusCircleIcon />}> app=MyApp </Button> </DescriptionListDescription> </DescriptionListGroup> <DescriptionListGroup> <DescriptionListTerm>Annotation</DescriptionListTerm> <DescriptionListDescription>2 Annotations</DescriptionListDescription> </DescriptionListGroup> </DescriptionList> );
jelly/patternfly-react
packages/react-core/src/components/Dropdown/__tests__/DropdownToggleAction.test.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { DropdownToggleAction } from '../DropdownToggleAction'; test('renders with text', () => { const { asFragment } = render(<DropdownToggleAction id="action" aria-label="action" />); expect(asFragment()).toMatchSnapshot(); }); test('isDisabled', () => { const { asFragment } = render(<DropdownToggleAction id="action" aria-label="action" isDisabled />); expect(asFragment()).toMatchSnapshot(); }); test('passing class', () => { const { asFragment } = render(<DropdownToggleAction id="action" aria-label="action" className="abc" />); expect(asFragment()).toMatchSnapshot(); }); test('checkbox passes value and event to onClick handler', () => { const onClickMock = jest.fn(); render(<DropdownToggleAction id="action" aria-label="acton" onClick={onClickMock} />); userEvent.click(screen.getByRole('button')); expect(onClickMock).toHaveBeenCalled(); });
jelly/patternfly-react
packages/react-integration/cypress/integration/alertdefaulttimeout.spec.ts
<reponame>jelly/patternfly-react<filename>packages/react-integration/cypress/integration/alertdefaulttimeout.spec.ts describe('Alert Demo Test', () => { it('Verify alert timeout', () => { cy.clock(); cy.visit('http://localhost:3000/alert-default-timeout-demo-nav-link'); cy.get('#alert-default-timeout').should('not.exist'); cy.get('#default-button').click(); cy.get('#alert-default-timeout').should('exist'); cy.tick(8000); cy.get('#alert-default-timeout').should('not.exist'); }); });
jelly/patternfly-react
packages/react-integration/cypress/integration/chipgroupwithcategory.spec.ts
describe('Chip Group with Category Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/chipgroup-with-category-demo-nav-link'); }); it('Verify delete button on first chip group', () => { const chipGroup = cy.get('.pf-c-chip-group').first(); const chipGroupButton = chipGroup.get('#remove_group_category-1'); chipGroupButton.should('be.visible'); chipGroupButton.click(); chipGroup.should('not.exist'); }); it('Displays Tooltip', () => { cy.get('.pf-c-chip-group__label') .last() .then((tooltipLink: JQuery<HTMLHeadingElement>) => { cy.get('.pf-c-tooltip').should('not.exist'); cy.wrap(tooltipLink) .trigger('mouseenter') .get('.pf-c-tooltip') .should('exist') .get('.pf-c-tooltip') .contains('Category 3 has a very long name'); }); }); });
jelly/patternfly-react
packages/react-core/src/components/Modal/ModalBoxHeader.tsx
<filename>packages/react-core/src/components/Modal/ModalBoxHeader.tsx<gh_stars>100-1000 import * as React from 'react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/ModalBox/modal-box'; export interface ModalBoxHeaderProps { /** Content rendered inside the Header */ children?: React.ReactNode; /** Additional classes added to the button */ className?: string; /** Optional help section for the Modal Header */ help?: React.ReactNode; } export const ModalBoxHeader: React.FunctionComponent<ModalBoxHeaderProps> = ({ children = null, className = '', help = null, ...props }: ModalBoxHeaderProps) => ( <header className={css(styles.modalBoxHeader, help && styles.modifiers.help, className)} {...props}> {help && ( <React.Fragment> <div className={css(styles.modalBoxHeaderMain)}>{children}</div> <div className="pf-c-modal-box__header-help">{help}</div> </React.Fragment> )} {!help && children} </header> ); ModalBoxHeader.displayName = 'ModalBoxHeader';
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/LabelGroupDemo/LabelGroupEditableDemo.tsx
import { Label, LabelGroup } from '@patternfly/react-core'; import React, { Component } from 'react'; interface LabelState { label1: string; label2: string; label3: string; } export class LabelGroupEditableDemo extends Component<{}, LabelState> { state = { label1: 'Editable label', label2: 'Editable label 2', label3: 'Editable label 3' }; componentDidMount() { window.scrollTo(0, 0); } onEditCancel = (prevText: string, label: string) => { this.setState({ [label]: prevText } as Pick<LabelState, keyof LabelState>); }; onEditComplete = (newText: string, label: string) => { this.setState({ [label]: newText } as Pick<LabelState, keyof LabelState>); }; render() { return ( <LabelGroup numLabels={5} isEditable hasEditableTextArea editableTextAreaProps={{ 'aria-label': 'New label' }}> <Label color="blue" onClose={() => {}} onEditCancel={prevText => this.onEditCancel(prevText, 'label1')} onEditComplete={newText => this.onEditComplete(newText, 'label1')} isEditable editableProps={{ 'aria-label': 'Editable text', id: 'editable-label-1' }} > {this.state.label1} </Label> <Label color="green">Static label</Label> <Label color="blue" onClose={() => {}} onEditCancel={prevText => this.onEditCancel(prevText, 'label2')} onEditComplete={newText => this.onEditComplete(newText, 'label2')} isEditable editableProps={{ 'aria-label': 'Editable text 2', id: 'editable-label-2' }} > {this.state.label2} </Label> <Label color="blue" onClose={() => {}} onEditCancel={prevText => this.onEditCancel(prevText, 'label3')} onEditComplete={newText => this.onEditComplete(newText, 'label3')} isEditable editableProps={{ 'aria-label': 'Editable text 3', id: 'editable-label-3' }} > {this.state.label3} </Label> </LabelGroup> ); } }
jelly/patternfly-react
packages/react-core/src/components/Checkbox/examples/CheckboxControlled.tsx
import React from 'react'; import { Checkbox } from '@patternfly/react-core'; export const CheckboxControlled: React.FunctionComponent = () => { const [isChecked1, setIsChecked1] = React.useState<boolean>(false); const [isChecked2, setIsChecked2] = React.useState<boolean>(false); const [isChecked3, setIsChecked3] = React.useState<boolean>(false); const [isChecked4, setIsChecked4] = React.useState<boolean>(false); const handleChange = (checked: boolean, event: React.FormEvent<HTMLInputElement>) => { const target = event.currentTarget; const name = target.name; switch (name) { case 'check1': setIsChecked1(checked); break; case 'check2': setIsChecked2(checked); break; case 'check3': setIsChecked3(checked); break; case 'check4': setIsChecked4(checked); break; default: // eslint-disable-next-line no-console console.log(name); } }; React.useEffect(() => { if (isChecked1 !== null) { setIsChecked2(isChecked1); setIsChecked3(isChecked1); } }, [isChecked1]); React.useEffect(() => { setIsChecked1((isChecked2 && isChecked3) || (isChecked2 || isChecked3 ? null : false)); }, [isChecked2, isChecked3]); return ( <React.Fragment> <Checkbox label="Parent CheckBox" isChecked={isChecked1} onChange={handleChange} id="controlled-check-1" name="check1" /> <Checkbox className="nested" label="Child CheckBox 1" isChecked={isChecked2} onChange={handleChange} id="controlled-check-2" name="check2" /> <Checkbox className="nested" label="Child CheckBox 2" isChecked={isChecked3} onChange={handleChange} id="controlled-check-3" name="check3" /> <Checkbox label="Controlled CheckBox" isChecked={isChecked4} onChange={handleChange} id="controlled-check-4" name="check4" /> </React.Fragment> ); };
jelly/patternfly-react
packages/react-charts/src/components/ChartBar/index.ts
export * from './ChartBar';
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/StyleGroup.tsx
import * as React from 'react'; import { DefaultGroup, Node, observer, ScaleDetailsLevel, ShapeProps, WithContextMenuProps, WithDragNodeProps, WithSelectionProps } from '@patternfly/react-topology'; import AlternateIcon from '@patternfly/react-icons/dist/esm/icons/regions-icon'; import DefaultIcon from '@patternfly/react-icons/dist/esm/icons/builder-image-icon'; import useDetailsLevel from '@patternfly/react-topology/dist/esm/hooks/useDetailsLevel'; const ICON_PADDING = 20; export enum DataTypes { Default, Alternate } type StyleGroupProps = { element: Node; collapsible: boolean; collapsedWidth?: number; collapsedHeight?: number; onCollapseChange?: (group: Node, collapsed: boolean) => void; getCollapsedShape?: (node: Node) => React.FunctionComponent<ShapeProps>; collapsedShadowOffset?: number; // defaults to 10 } & WithContextMenuProps & WithDragNodeProps & WithSelectionProps; const StyleGroup: React.FunctionComponent<StyleGroupProps> = ({ element, onContextMenu, contextMenuOpen, collapsedWidth = 75, collapsedHeight = 75, ...rest }) => { const data = element.getData(); const detailsLevel = useDetailsLevel(); const getTypeIcon = (dataType?: DataTypes): any => { switch (dataType) { case DataTypes.Alternate: return AlternateIcon; default: return DefaultIcon; } }; const renderIcon = (): React.ReactNode => { const iconSize = Math.min(collapsedWidth, collapsedHeight) - ICON_PADDING * 2; const Component = getTypeIcon(data.dataType); return ( <g transform={`translate(${(collapsedWidth - iconSize) / 2}, ${(collapsedHeight - iconSize) / 2})`}> <Component style={{ color: '#393F44' }} width={iconSize} height={iconSize} /> </g> ); }; const passedData = React.useMemo(() => { const newData = { ...data }; Object.keys(newData).forEach(key => { if (newData[key] === undefined) { delete newData[key]; } }); return newData; }, [data]); return ( <DefaultGroup onContextMenu={data.showContextMenu ? onContextMenu : undefined} contextMenuOpen={contextMenuOpen} element={element} collapsible collapsedWidth={collapsedWidth} collapsedHeight={collapsedHeight} showLabel={detailsLevel === ScaleDetailsLevel.high} {...rest} {...passedData} > {element.isCollapsed() ? renderIcon() : null} </DefaultGroup> ); }; export default observer(StyleGroup);
jelly/patternfly-react
packages/react-inline-edit-extension/src/components/Body/Body.tsx
<gh_stars>100-1000 import * as React from 'react'; import { TableBodyProps, isRowExpanded, IRowData, IExtraRowData, TableBody, IRow, IComputedData } from '@patternfly/react-table'; import { showIdWarnings, TableEditConfirmation } from '../../utils'; import { IEditedCellData } from '../InlineEdit/editableTableBody'; const resolveCascadeEditability = (rows: ExtendedIRow[]) => { // eslint-disable-next-line no-undef const isRowExpandedIndexes = new Set( rows.map((row, idx) => (isRowExpanded(row, rows) ? idx : null)).filter(row => row !== null) ); // flag parents and their children which are edited together rows .filter( (row, idx) => row.parent !== undefined && row.isEditing && isRowExpandedIndexes.has(idx) && row.isEditableTogetherWithParent && rows[row.parent].isEditing ) .forEach(row => { rows[row.parent].isChildEditing = true; row.isParentEditing = true; }); const lastVisibleRow = rows.filter((row, idx) => !row.parent || isRowExpandedIndexes.has(idx)).pop(); // flag last parent row if there are only descendants under it if (lastVisibleRow && lastVisibleRow.isParentEditing) { let parentRow = lastVisibleRow; while (parentRow.parent !== undefined && parentRow.isEditableTogetherWithParent) { parentRow = rows[parentRow.parent]; } parentRow.isLastVisibleParent = true; } }; const onRow = ( event: React.MouseEvent<Element, MouseEvent>, row: IRow, rowProps: IExtraRowData, computedData: IComputedData, { onRowClick, editConfig }: InlineEditBodyProps ) => { const target = event.target as any; const cell = target.closest('[data-key]'); // eslint-disable-next-line radix const cellNumber = parseInt(cell && cell.getAttribute('data-key'), 10); const hasCellNumber = !Number.isNaN(cellNumber); let onEditCellClicked: () => void; if (hasCellNumber && editConfig && typeof editConfig.onEditCellClicked === 'function') { // resolve closest (e.g. for dropdowns) usable id of a clicked element inside a cell const idElement = target.closest('[id]'); const elementId = idElement && cell.contains(idElement) ? idElement.getAttribute('id') || null : null; if (!elementId) { showIdWarnings(row, target); } onEditCellClicked = () => { editConfig.onEditCellClicked(event as any, row, { ...rowProps, columnIndex: cellNumber, elementId }); }; } // give priority to fire onChange/onBlur callbacks setTimeout(() => { if (!row.isEditing) { onRowClick(event, row, rowProps, computedData); if (onEditCellClicked) { // edit cell after rerender setTimeout(onEditCellClicked, 0); } } else if (onEditCellClicked) { onEditCellClicked(); } }, 0); }; export interface EditConfig { editConfirmationType?: typeof TableEditConfirmation | keyof typeof TableEditConfirmation; onEditCellClicked?: (value: React.MouseEvent, row: IRowData, extra: IEditedCellData) => void; onEditConfirmed?: (value: React.MouseEvent, row: IRowData, rowProps: IExtraRowData) => void; onEditCanceled?: (value: React.MouseEvent, row: IRowData, rowProps: IExtraRowData) => void; } export interface InlineEditBodyProps extends TableBodyProps { editConfig: EditConfig; } export interface BodyProps extends TableBodyProps { BodyComponent: typeof TableBody; editConfig: EditConfig; } interface ExtendedIRow extends IRow { editConfig: EditConfig; isTableEditing: boolean; } export const Body = ({ BodyComponent, rows = [], editConfig, onRowClick = () => {}, ...props }: BodyProps) => { const isTableEditing = rows.some(row => row.isEditing); const mappedRows = rows.map(row => ({ ...row, editConfig, isTableEditing })) as ExtendedIRow[]; resolveCascadeEditability(mappedRows); return ( <BodyComponent {...props} rows={mappedRows} onRowClick={(event, row, rowProps, computedData) => onRow(event as any, row, rowProps, computedData, { onRowClick, editConfig }) } /> ); };
jelly/patternfly-react
packages/react-core/src/components/Card/examples/CardWithNoHeader.tsx
<gh_stars>0 import React from 'react'; import { Card, CardBody, CardFooter } from '@patternfly/react-core'; export const CardWithNoHeader: React.FunctionComponent = () => ( <Card> <CardBody>This card has no header</CardBody> <CardFooter>Footer</CardFooter> </Card> );
jelly/patternfly-react
packages/react-core/src/components/DataList/examples/DataListSmGridBreakpoint.tsx
import React from 'react'; import { DataList, DataListItem, DataListItemRow, DataListItemCells, DataListCell } from '@patternfly/react-core'; export const DataListSmGridBreakpoint: React.FunctionComponent = () => ( <DataList aria-label="Simple data list example" gridBreakpoint="sm"> <DataListItem aria-labelledby="simple-item1"> <DataListItemRow> <DataListItemCells dataListCells={[ <DataListCell key="primary content"> <span id="simple-item1">Primary content</span> </DataListCell>, <DataListCell key="secondary content"> Really really really really really really really really really really really really really really long description that should be truncated before it ends </DataListCell> ]} /> </DataListItemRow> </DataListItem> </DataList> );
jelly/patternfly-react
packages/react-topology/src/components/TopologyControlBar/__tests__/TopologyControlBar.test.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { TopologyControlBar, createTopologyControlButtons, defaultControlButtonsOptions } from '../TopologyControlBar'; describe('TopologyControlBar', () => { test('should display the default controls correctly', () => { const controlButtons = createTopologyControlButtons(); const onButtonClick = jest.fn(); const { asFragment } = render( <TopologyControlBar className="default-test-class" id="default-test-id" controlButtons={controlButtons} onButtonClick={onButtonClick} /> ); userEvent.click(screen.getByText('Zoom In')); expect(onButtonClick).toHaveBeenCalledTimes(1); expect(asFragment()).toMatchSnapshot(); }); test('should accept button options correctly', () => { const zoomInCallback = jest.fn(); const controlButtons = createTopologyControlButtons({ ...defaultControlButtonsOptions, zoomInCallback, zoomInAriaLabel: 'test-zoom-in-aria-label', zoomInIcon: <span>test zoom in</span>, zoomInTip: 'test zoom in tooltip', fitToScreenHidden: true, resetViewDisabled: true, legend: false }); const { asFragment } = render( <TopologyControlBar className="default-test-class" id="default-test-id" controlButtons={controlButtons} /> ); userEvent.click(screen.getByText('test zoom in')); expect(zoomInCallback).toHaveBeenCalledTimes(1); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-table/src/components/Table/examples/LegacyTableEmptyState.tsx
import React from 'react'; import { Table, TableHeader, TableBody, TableProps } from '@patternfly/react-table'; import { Bullseye, EmptyState, EmptyStateVariant, EmptyStateIcon, Title, EmptyStateBody, Button } from '@patternfly/react-core'; import SearchIcon from '@patternfly/react-icons/dist/esm/icons/search-icon'; // This example has been simplified to focus on the empty state. In real usage, // you may want to derive your rows from typed underlying data and minimal state. See other examples. export const LegacyTableEmptyState: React.FunctionComponent = () => { const columns: TableProps['cells'] = ['Repositories', 'Branches', 'Pull requests', 'Workspaces', 'Last commit']; const rows: TableProps['rows'] = [ { heightAuto: true, cells: [ { props: { colSpan: 8 }, title: ( <Bullseye> <EmptyState variant={EmptyStateVariant.small}> <EmptyStateIcon icon={SearchIcon} /> <Title headingLevel="h2" size="lg"> No results found </Title> <EmptyStateBody>Clear all filters and try again.</EmptyStateBody> <Button variant="link">Clear all filters</Button> </EmptyState> </Bullseye> ) } ] } ]; return ( <Table aria-label="Table text with modifiers" cells={columns} rows={rows}> <TableHeader /> <TableBody /> </Table> ); };
jelly/patternfly-react
packages/react-core/src/helpers/constants.ts
<filename>packages/react-core/src/helpers/constants.ts export const KEY_CODES = { ARROW_UP: 38, ARROW_DOWN: 40, ESCAPE_KEY: 27, TAB: 9, ENTER: 13, SPACE: 32 }; export const SIDE = { RIGHT: 'right', LEFT: 'left', BOTH: 'both', NONE: 'none' }; export const KEYHANDLER_DIRECTION = { UP: 'up', DOWN: 'down', RIGHT: 'right', LEFT: 'left' }; export enum ValidatedOptions { success = 'success', error = 'error', warning = 'warning', default = 'default' } export const KeyTypes = { Tab: 'Tab', Space: ' ', Escape: 'Escape', Enter: 'Enter', ArrowUp: 'ArrowUp', ArrowDown: 'ArrowDown', ArrowLeft: 'ArrowLeft', ArrowRight: 'ArrowRight' };
jelly/patternfly-react
packages/react-core/src/components/Page/__tests__/PageNavigation.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import { PageNavigation } from '../PageNavigation'; describe('page navigation', () => { test('Verify basic render', () => { const { asFragment } = render(<PageNavigation>test</PageNavigation>); expect(asFragment()).toMatchSnapshot(); }); test('Verify limited width', () => { const { asFragment } = render(<PageNavigation isWidthLimited>test</PageNavigation>); expect(asFragment()).toMatchSnapshot(); }); test('Verify top sticky', () => { const { asFragment } = render(<PageNavigation sticky="top">test</PageNavigation>); expect(asFragment()).toMatchSnapshot(); }); test('Verify bottom sticky', () => { const { asFragment } = render(<PageNavigation sticky="bottom">test</PageNavigation>); expect(asFragment()).toMatchSnapshot(); }); test('Verify top shadow', () => { const { asFragment } = render(<PageNavigation hasShadowTop>test</PageNavigation>); expect(asFragment()).toMatchSnapshot(); }); test('Verify bottom shadow', () => { const { asFragment } = render(<PageNavigation hasShadowBottom>test</PageNavigation>); expect(asFragment()).toMatchSnapshot(); }); test('Verify overflow scroll', () => { const { asFragment } = render(<PageNavigation hasOverflowScroll>test</PageNavigation>); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-core/src/components/DatePicker/examples/DatePickerControlledCalendar.tsx
<reponame>jelly/patternfly-react<filename>packages/react-core/src/components/DatePicker/examples/DatePickerControlledCalendar.tsx<gh_stars>0 import React from 'react'; import { Button, DatePicker } from '@patternfly/react-core'; export const DatePickerControlledCalendar: React.FunctionComponent = () => { const dateRef = React.useRef(null); const onClick = () => { if (dateRef.current) { dateRef.current.toggleCalendar(); } }; return ( <React.Fragment> <Button onClick={onClick}>Toggle calendar</Button> <DatePicker ref={dateRef} /> </React.Fragment> ); };
jelly/patternfly-react
packages/react-core/src/components/ProgressStepper/ProgressStep.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/ProgressStepper/progress-stepper'; import { css } from '@patternfly/react-styles'; import CheckCircleIcon from '@patternfly/react-icons/dist/esm/icons/check-circle-icon'; import ResourcesFullIcon from '@patternfly/react-icons/dist/esm/icons/resources-full-icon'; import ExclamationTriangleIcon from '@patternfly/react-icons/dist/esm/icons/exclamation-triangle-icon'; import ExclamationCircleIcon from '@patternfly/react-icons/dist/esm/icons/exclamation-circle-icon'; export interface ProgressStepProps extends React.DetailedHTMLProps<React.LiHTMLAttributes<HTMLLIElement>, HTMLLIElement> { /** Content rendered inside the progress step. */ children?: React.ReactNode; /** Additional classes applied to the progress step container. */ className?: string; /** Variant of the progress step. Each variant has a default icon. */ variant?: 'default' | 'success' | 'info' | 'pending' | 'warning' | 'danger'; /** Flag indicating the progress step is the current step. */ isCurrent?: boolean; /** Custom icon of a progress step. Will override default icons provided by the variant. */ icon?: React.ReactNode; /** Description text of a progress step. */ description?: string; /** ID of the title of the progress step. */ titleId?: string; /** Accessible label for the progress step. Should communicate all information being communicated by the progress * step's icon, including the variant and the completed status. */ 'aria-label'?: string; /** Forwards the step ref to rendered function. Use this prop to add a popover to the step.*/ popoverRender?: (stepRef: React.RefObject<any>) => React.ReactNode; } const variantIcons = { default: undefined as any, pending: undefined as any, success: <CheckCircleIcon />, info: <ResourcesFullIcon />, warning: <ExclamationTriangleIcon />, danger: <ExclamationCircleIcon /> }; const variantStyle = { default: '', info: styles.modifiers.info, success: styles.modifiers.success, pending: styles.modifiers.pending, warning: styles.modifiers.warning, danger: styles.modifiers.danger }; export const ProgressStep: React.FunctionComponent<ProgressStepProps> = ({ children, className, variant, isCurrent, description, icon, titleId, 'aria-label': ariaLabel, popoverRender, ...props }: ProgressStepProps) => { const _icon = icon !== undefined ? icon : variantIcons[variant]; const Component = popoverRender !== undefined ? 'span' : 'div'; const stepRef = React.useRef(); if (props.id === undefined || titleId === undefined) { /* eslint-disable no-console */ console.warn( 'ProgressStep: The titleId and id properties are required to make this component accessible, and one or both of these properties are missing.' ); } return ( <li className={css( styles.progressStepperStep, variantStyle[variant], isCurrent && styles.modifiers.current, className )} aria-label={ariaLabel} {...(isCurrent && { 'aria-current': 'step' })} {...props} > <div className={css(styles.progressStepperStepConnector)}> <span className={css(styles.progressStepperStepIcon)}>{_icon && _icon}</span> </div> <div className={css(styles.progressStepperStepMain)}> <Component className={css(styles.progressStepperStepTitle, popoverRender && styles.modifiers.helpText)} id={titleId} ref={stepRef} {...(popoverRender && { tabIndex: 0, role: 'button', type: 'button' })} {...(props.id !== undefined && titleId !== undefined && { 'aria-labelledby': `${props.id} ${titleId}` })} > {children} {popoverRender && popoverRender(stepRef)} </Component> {description && <div className={css(styles.progressStepperStepDescription)}>{description}</div>} </div> </li> ); }; ProgressStep.displayName = 'ProgressStep';
jelly/patternfly-react
packages/react-topology/src/behavior/withRemoveConnector.tsx
import * as React from 'react'; import { observer } from 'mobx-react'; import { Edge } from '../types'; import DefaultRemoveConnector from '../components/DefaultRemoveConnector'; interface ElementProps { element: Edge; } export interface WithRemoveConnectorProps { onShowRemoveConnector?: () => void; onHideRemoveConnector?: () => void; } type RemoveRenderer = (edge: Edge, onRemove: (e: Edge) => void, size?: number) => React.ReactElement; const defaultRenderRemove: RemoveRenderer = (edge: Edge, onRemove: (e: Edge) => void) => { const removeEdge = () => { onRemove(edge); }; return ( <DefaultRemoveConnector startPoint={edge.getStartPoint()} endPoint={edge.getEndPoint()} onRemove={removeEdge} /> ); }; export const withRemoveConnector = <P extends WithRemoveConnectorProps & ElementProps>( onRemove: (edge: Edge) => void, renderRemove: RemoveRenderer = defaultRenderRemove ) => (WrappedComponent: React.ComponentType<P>) => { const Component: React.FunctionComponent<Omit<P, keyof WithRemoveConnectorProps>> = props => { const [show, setShow] = React.useState(false); const onShowRemoveConnector = React.useCallback(() => setShow(true), []); const onHideRemoveConnector = React.useCallback(() => setShow(false), []); return ( <WrappedComponent {...(props as any)} onShowRemoveConnector={onShowRemoveConnector} onHideRemoveConnector={onHideRemoveConnector} > {show && renderRemove(props.element, onRemove)} </WrappedComponent> ); }; Component.displayName = `withRemoveConnector(${WrappedComponent.displayName || WrappedComponent.name})`; return observer(Component); };
jelly/patternfly-react
packages/react-core/src/components/Modal/__tests__/ModalBoxFooter.test.tsx
import * as React from 'react'; import { render } from '@testing-library/react'; import { ModalBoxFooter } from '../ModalBoxFooter'; test('ModalBoxFooter Test', () => { const { asFragment } = render( <ModalBoxFooter className="test-box-footer-class">This is a ModalBox Footer</ModalBoxFooter> ); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-code-editor/src/components/CodeEditor/examples/CodeEditorWithActions.tsx
import React from 'react'; import { CodeEditor } from '@patternfly/react-code-editor'; export const CodeEditorWithActions: React.FunctionComponent = () => ( <CodeEditor isUploadEnabled isDownloadEnabled isCopyEnabled isLanguageLabelVisible height="400px" /> );
jelly/patternfly-react
packages/react-integration/demo-app-ts/src/components/demos/TopologyDemo/components/actionsComponentFactory.tsx
<reponame>jelly/patternfly-react import * as React from 'react'; import { GraphElement, ComponentFactory, withContextMenu, ContextMenuSeparator, ContextMenuItem, withDragNode, withSelection, ModelKind, NodeComponentProps, DefaultNode, withPanZoom, GraphComponent, ContextSubMenuItem, withDndDrop, nodeDropTargetSpec, nodeDragSourceSpec } from '@patternfly/react-topology'; import GroupHull from './GroupHull'; import CustomPathNode from './CustomPathNode'; const contextMenuItem = (label: string, i: number): React.ReactElement => { if (label === '-') { return <ContextMenuSeparator key={`separator:${i.toString()}`} />; } if (label.includes('->')) { const parent = label.slice(0, label.indexOf('->')); const children = label.slice(label.indexOf('->') + 2).split(','); return ( <ContextSubMenuItem label={parent} key={parent}> {children.map((child, j) => contextMenuItem(child.trim(), j))} </ContextSubMenuItem> ); } return ( // eslint-disable-next-line no-alert <ContextMenuItem key={label} onClick={() => alert(`Selected: ${label}`)}> {label} </ContextMenuItem> ); }; const createContextMenuItems = (...labels: string[]): React.ReactElement[] => labels.map(contextMenuItem); const defaultMenu = createContextMenuItems( 'First', 'Second', 'Third', '-', 'Fourth', 'Sub Menu-> Child1, Child2, Child3, -, Child4' ); const actionsComponentFactory: ComponentFactory = ( kind: ModelKind, type: string ): React.ComponentType<{ element: GraphElement }> | undefined => { if (kind === ModelKind.graph) { return withPanZoom()(GraphComponent); } if (type === 'group') { return withDragNode({ canCancel: false })(GroupHull); } if (type === 'default-node' || type === 'node') { return withDndDrop<any, any, { droppable?: boolean; hover?: boolean; canDrop?: boolean }, NodeComponentProps>( nodeDropTargetSpec() )(withDragNode(nodeDragSourceSpec(type))(withSelection()(withContextMenu(() => defaultMenu)(DefaultNode)))); } if (type === 'custom-node') { return withDndDrop<any, any, { droppable?: boolean; hover?: boolean; canDrop?: boolean }, NodeComponentProps>( nodeDropTargetSpec() )(withDragNode(nodeDragSourceSpec(type))(withSelection()(withContextMenu(() => defaultMenu)(CustomPathNode)))); } return undefined; }; export default actionsComponentFactory;
jelly/patternfly-react
packages/react-topology/src/anchors/__tests__/RectAnchor.spec.ts
<gh_stars>100-1000 import RectAnchor from '../RectAnchor'; import { Rect, Point } from '../../geom'; import { BaseNode } from '../../elements'; describe('RectAnchor', () => { it('should return node center location', () => { const node = new BaseNode(); node.setBounds(new Rect(4, 5, 0, 0)); expect(new RectAnchor(node).getLocation(new Point())).toEqual({ x: 4, y: 5 }); }); it('should return node anchor location', () => { const node = new BaseNode(); node.setBounds(new Rect(0, 0, 10, 10)); expect(new RectAnchor(node).getLocation(new Point(100, 5))).toEqual({ x: 10, y: 5 }); expect(new RectAnchor(node).getLocation(new Point(5, 100))).toEqual({ x: 5, y: 10 }); expect(new RectAnchor(node).getLocation(new Point(100, 100))).toEqual({ x: 10, y: 10 }); expect(new RectAnchor(node, 4).getLocation(new Point(100, 5))).toEqual({ x: 14, y: 5 }); expect(new RectAnchor(node, 4).getLocation(new Point(5, 100))).toEqual({ x: 5, y: 14 }); expect(new RectAnchor(node, 4).getLocation(new Point(100, 100))).toEqual({ x: 14, y: 14 }); }); it('should return node center reference point', () => { const node = new BaseNode(); node.setBounds(new Rect(0, 0, 10, 10)); expect(new RectAnchor(node).getReferencePoint()).toEqual({ x: 5, y: 5 }); }); });
jelly/patternfly-react
packages/react-core/src/components/Divider/examples/DividerVerticalFlexInsetMedium.tsx
<filename>packages/react-core/src/components/Divider/examples/DividerVerticalFlexInsetMedium.tsx<gh_stars>0 import React from 'react'; import { Divider, Flex, FlexItem } from '@patternfly/react-core'; export const DividerVerticalFlexInsetMedium: React.FunctionComponent = () => ( <Flex> <FlexItem>first item</FlexItem> <Divider orientation={{ default: 'vertical' }} inset={{ default: 'insetMd' }} /> <FlexItem>second item</FlexItem> </Flex> );
jelly/patternfly-react
packages/react-core/src/components/Popover/PopoverContext.tsx
import * as React from 'react'; interface PopoverContextProps { headerComponent?: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'; } export const PopoverContext = React.createContext<Partial<PopoverContextProps>>({});
jelly/patternfly-react
packages/react-core/src/components/NumberInput/__tests__/NumberInput.test.tsx
<filename>packages/react-core/src/components/NumberInput/__tests__/NumberInput.test.tsx import React from 'react'; import { render } from '@testing-library/react'; import { NumberInput } from '../NumberInput'; describe('numberInput', () => { test('renders defaults & extra props', () => { const { asFragment } = render(<NumberInput className="custom" id="numberInput1" />); expect(asFragment()).toMatchSnapshot(); }); test('renders value', () => { const { asFragment } = render(<NumberInput value={90} />); expect(asFragment()).toMatchSnapshot(); }); test('renders disabled', () => { const { asFragment } = render(<NumberInput value={90} isDisabled />); expect(asFragment()).toMatchSnapshot(); }); test('disables lower threshold', () => { const { asFragment } = render(<NumberInput value={0} min={0} />); expect(asFragment()).toMatchSnapshot(); }); test('disables upper threshold', () => { const { asFragment } = render(<NumberInput value={100} max={100} />); expect(asFragment()).toMatchSnapshot(); }); test('renders unit', () => { const { asFragment } = render(<NumberInput value={5} unit="%" unitPosition="after" />); expect(asFragment()).toMatchSnapshot(); }); test('renders unit & position', () => { const { asFragment } = render(<NumberInput value={5} unit="$" unitPosition="before" />); expect(asFragment()).toMatchSnapshot(); }); test('renders custom width', () => { const { asFragment } = render(<NumberInput value={5} widthChars={10} />); expect(asFragment()).toMatchSnapshot(); }); test('passes input props successfully', () => { const { asFragment } = render(<NumberInput value={5} onChange={jest.fn()} inputName="test-name" />); expect(asFragment()).toMatchSnapshot(); }); test('passes button props successfully', () => { const { asFragment } = render( <NumberInput value={5} onMinus={jest.fn()} minusBtnProps={{ id: 'minus-id' }} onPlus={jest.fn()} plusBtnProps={{ id: 'plus-id' }} /> ); expect(asFragment()).toMatchSnapshot(); }); });
jelly/patternfly-react
packages/react-console/src/components/DesktopViewer/ConsoleDetailPropType.tsx
<reponame>jelly/patternfly-react export interface ConsoleDetailPropType { address: string; port: string | number; tlsPort?: string | number; }
jelly/patternfly-react
packages/react-core/src/components/SkipToContent/SkipToContent.tsx
import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/SkipToContent/skip-to-content'; import buttonStyles from '@patternfly/react-styles/css/components/Button/button'; import { css } from '@patternfly/react-styles'; import { PickOptional } from '../../helpers/typeUtils'; export interface SkipToContentProps extends React.HTMLProps<HTMLAnchorElement> { /** The skip to content link. */ href: string; /** Content to display within the skip to content component, typically a string. */ children?: React.ReactNode; /** Additional styles to apply to the skip to content component. */ className?: string; /** Forces the skip to content to display. This is primarily for demonstration purposes and would not normally be used. */ show?: boolean; } export class SkipToContent extends React.Component<SkipToContentProps> { static displayName = 'SkipToContent'; static defaultProps: PickOptional<SkipToContentProps> = { show: false }; componentRef = React.createRef<HTMLAnchorElement>(); componentDidMount() { if (this.props.show && this.componentRef.current) { this.componentRef.current.focus(); } } render() { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { children, className, href, show, type, ...rest } = this.props; return ( <a {...rest} className={css(buttonStyles.button, buttonStyles.modifiers.primary, styles.skipToContent, className)} ref={this.componentRef} href={href} > {children} </a> ); } }
jelly/patternfly-react
packages/react-integration/cypress/integration/tableselectable.spec.ts
describe('Table Selectable Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/table-selectable-demo-nav-link'); }); it('Verify table string', () => { cy.get('caption').contains('Selectable Table'); }); it('Check number of rows', () => { cy.get('.pf-c-table') .find('tr') .should('have.length', 4); }); it('Check number of columns', () => { cy.get('thead') .find('th') .should('have.length', 5); // There should be a canSelectAll input cy.get('thead') .find('td') .should('have.length', 1); }); it('Test selectable checkbox', () => { for (let i = 1; i <= 3; i++) { cy.get(`tbody tr:nth-child(${i}) .pf-c-table__check > label > input`).check(); } for (let i = 1; i <= 3; i++) { cy.get(`tbody tr:nth-child(${i}) .pf-c-table__check > label > input`).should('be.checked'); } }); it('Test selectable radio', () => { // Switch to radio buttons table cy.get('input[name=selectVariant][value=radio]').click(); for (let i = 1; i <= 3; i++) { cy.get(`tbody tr:nth-child(${i}) .pf-c-table__check > label > input`).check(); } // Only last radio input should be checked in the end of the iteration for (let i = 1; i <= 3; i++) { if (i < 3) { cy.get(`tbody tr:nth-child(${i}) .pf-c-table__check > label > input`).should('not.be.checked'); } else { cy.get(`tbody tr:nth-child(${i}) .pf-c-table__check > label > input`).should('be.checked'); } } }); it('Check that first column canSelectAll input is missing', () => { cy.get('thead') .find('td') .should('have.length', 0); }); });
jelly/patternfly-react
packages/react-core/src/components/index.ts
<filename>packages/react-core/src/components/index.ts /** Keep alphabetically sorted */ export * from './AboutModal'; export * from './Accordion'; export * from './ActionList'; export * from './Alert'; export * from './AlertGroup'; export * from './ApplicationLauncher'; export * from './Avatar'; export * from './BackToTop'; export * from './Backdrop'; export * from './BackgroundImage'; export * from './Badge'; export * from './Banner'; export * from './Brand'; export * from './Breadcrumb'; export * from './Button'; export * from './CalendarMonth'; export * from './Card'; export * from './Checkbox'; export * from './Chip'; export * from './ChipGroup'; export * from './ClipboardCopy'; export * from './CodeBlock'; export * from './ContextSelector'; export * from './DataList'; export * from './DatePicker'; export * from './DescriptionList'; export * from './Divider'; export * from './Drawer'; export * from './Dropdown'; export * from './DualListSelector'; export * from './EmptyState'; export * from './ExpandableSection'; export * from './FileUpload'; export * from './Form'; export * from './FormSelect'; export * from './HelperText'; export * from './Hint'; export * from './InputGroup'; export * from './JumpLinks'; export * from './Label'; export * from './LabelGroup'; export * from './List'; export * from './LoginPage'; export * from './Masthead'; export * from './Menu'; export * from './MenuToggle'; export * from './Modal'; export * from './MultipleFileUpload'; export * from './Nav'; export * from './NotificationBadge'; export * from './NotificationDrawer'; export * from './OptionsMenu'; export * from './OverflowMenu'; export * from './Page'; export * from './Pagination'; export * from './Popover'; export * from './Progress'; export * from './ProgressStepper'; export * from './Radio'; export * from './SearchInput'; export * from './Select'; export * from './Sidebar'; export * from './SimpleList'; export * from './Skeleton'; export * from './SkipToContent'; export * from './Slider'; export * from './Spinner'; export * from './Switch'; export * from './Tabs'; export * from './Text'; export * from './TextArea'; export * from './TextInput'; export * from './Tile'; export * from './TimePicker'; export * from './Title'; export * from './ToggleGroup'; export * from './Toolbar'; export * from './Tooltip'; export * from './NumberInput'; export * from './TreeView'; export * from './Wizard'; export * from './DragDrop'; export * from './TextInputGroup'; export * from './Panel'; export * from './Truncate';
jelly/patternfly-react
packages/react-core/src/components/Modal/__tests__/ModalBoxHeader.test.tsx
<gh_stars>0 import * as React from 'react'; import { render } from '@testing-library/react'; import { ModalBoxHeader } from '../ModalBoxHeader'; test('ModalBoxHeader Test', () => { const { asFragment } = render(<ModalBoxHeader>This is a ModalBox header</ModalBoxHeader>); expect(asFragment()).toMatchSnapshot(); }); test('ModalBoxHeader help renders', () => { const { asFragment } = render(<ModalBoxHeader help={<div>test</div>}>This is a ModalBox header</ModalBoxHeader>); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/components/DatePicker/__tests__/DatePicker.test.tsx
import { render } from '@testing-library/react'; import { DatePicker } from '../DatePicker'; import React from 'react'; test('disabled date picker', () => { const { asFragment } = render(<DatePicker value="2020-11-20" isDisabled aria-label="disabled date picker" />); expect(asFragment()).toMatchSnapshot(); });
jelly/patternfly-react
packages/react-core/src/demos/examples/Tabs/ModalTabs.tsx
import React from 'react'; import DashboardWrapper from '../DashboardWrapper'; import { PageSection, TextContent, Text, Gallery, Card, CardBody, CardTitle, PageSectionVariants, Modal, ModalVariant, Tab, Tabs, TabTitleText, List, ListItem, Grid, GridItem, TabContent } from '@patternfly/react-core'; interface Product { id: number; name: string; description: string; } const products: Product[] = [ { id: 0, name: 'PatternFly', description: 'PatternFly is a community project that promotes design commonality and improves user experience.' }, { id: 1, name: 'ActiveMQ', description: 'The ActiveMQ component allows messages to be sent to a JMS Queue or Topic; or messages to be consumed from a JMS Queue or Topic using Apache ActiveMQ.' }, { id: 2, name: 'Apache Spark', description: 'This documentation page covers the Apache Spark component for the Apache Camel.' } ]; export const ModalTabs: React.FunctionComponent = () => { const [isModalOpen, setIsModalOpen] = React.useState(false); const [selectedProduct, setSelectedProduct] = React.useState<Product>(); const [activeTabKey, setActiveTabKey] = React.useState<string | number>(0); const onCardClick = React.useCallback( (product: Product) => () => { setSelectedProduct(product); setIsModalOpen(true); }, [] ); const onCardKeyPress = React.useCallback( (product: Product) => (event: React.KeyboardEvent<HTMLElement>) => { if (event.key === 'Enter' || event.key === ' ') { onCardClick(product)(); } }, [] ); const closeModal = React.useCallback(() => { setSelectedProduct(undefined); setIsModalOpen(false); setActiveTabKey(0); }, []); const onTabSelect = React.useCallback( (_event: React.MouseEvent<HTMLElement, MouseEvent>, tabIndex: string | number) => setActiveTabKey(tabIndex), [] ); return ( <React.Fragment> <DashboardWrapper mainContainerId="main-content-card-view-default-nav"> <PageSection variant={PageSectionVariants.light}> <TextContent> <Text component="h1">Projects</Text> <Text component="p">Click any project card to view Tabs within Modals.</Text> </TextContent> </PageSection> <PageSection isFilled> <Gallery hasGutter> {products.map(product => ( <Card isSelectable isSelectableRaised isCompact key={product.id} onClick={onCardClick(product)} onKeyPress={onCardKeyPress(product)} > <CardTitle>{product.name}</CardTitle> <CardBody>{product.description}</CardBody> </Card> ))} </Gallery> </PageSection> </DashboardWrapper> {selectedProduct && ( <Modal variant={ModalVariant.small} title={selectedProduct.name} isOpen={isModalOpen} onClose={closeModal}> <Grid hasGutter> <GridItem> <Tabs activeKey={activeTabKey} onSelect={onTabSelect} isSecondary> <Tab eventKey={0} tabContentId="details-tab" title={<TabTitleText>Details</TabTitleText>} /> <Tab eventKey={1} tabContentId="doc-tab" title={<TabTitleText>Documentation</TabTitleText>} /> </Tabs> </GridItem> <GridItem> <TabContent eventKey={0} id="details-tab" hidden={activeTabKey !== 0}> {selectedProduct.description} </TabContent> <TabContent eventKey={1} id="doc-tab" hidden={activeTabKey !== 1}> <List> <ListItem> <a>Doc link 1</a> </ListItem> <ListItem> <a>Doc link 2</a> </ListItem> <ListItem> <a>Doc link 3</a> </ListItem> </List> </TabContent> </GridItem> </Grid> </Modal> )} </React.Fragment> ); };
jelly/patternfly-react
packages/react-topology/src/utils/Stateful.ts
<filename>packages/react-topology/src/utils/Stateful.ts import { action, observable } from 'mobx'; import { WithState, State } from '../types'; export default class Stateful implements WithState { @observable.shallow private state: State = {}; getState<S = {}>(): S { return this.state as S; } @action setState(state: State): void { if (state) { Object.assign(this.state, state); } } }
jelly/patternfly-react
packages/react-charts/src/components/ChartTheme/themes/light/multi-color-unordered-theme.ts
/* eslint-disable camelcase */ import chart_color_blue_100 from '@patternfly/react-tokens/dist/esm/chart_color_blue_100'; import chart_color_blue_200 from '@patternfly/react-tokens/dist/esm/chart_color_blue_200'; import chart_color_blue_300 from '@patternfly/react-tokens/dist/esm/chart_color_blue_300'; import chart_color_blue_400 from '@patternfly/react-tokens/dist/esm/chart_color_blue_400'; import chart_color_blue_500 from '@patternfly/react-tokens/dist/esm/chart_color_blue_500'; import chart_color_green_100 from '@patternfly/react-tokens/dist/esm/chart_color_green_100'; import chart_color_green_200 from '@patternfly/react-tokens/dist/esm/chart_color_green_200'; import chart_color_green_300 from '@patternfly/react-tokens/dist/esm/chart_color_green_300'; import chart_color_green_400 from '@patternfly/react-tokens/dist/esm/chart_color_green_400'; import chart_color_green_500 from '@patternfly/react-tokens/dist/esm/chart_color_green_500'; import chart_color_cyan_100 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_100'; import chart_color_cyan_200 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_200'; import chart_color_cyan_300 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_300'; import chart_color_cyan_400 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_400'; import chart_color_cyan_500 from '@patternfly/react-tokens/dist/esm/chart_color_cyan_500'; import chart_color_purple_100 from '@patternfly/react-tokens/dist/esm/chart_color_purple_100'; import chart_color_purple_200 from '@patternfly/react-tokens/dist/esm/chart_color_purple_200'; import chart_color_purple_300 from '@patternfly/react-tokens/dist/esm/chart_color_purple_300'; import chart_color_purple_400 from '@patternfly/react-tokens/dist/esm/chart_color_purple_400'; import chart_color_purple_500 from '@patternfly/react-tokens/dist/esm/chart_color_purple_500'; import chart_color_gold_100 from '@patternfly/react-tokens/dist/esm/chart_color_gold_100'; import chart_color_gold_200 from '@patternfly/react-tokens/dist/esm/chart_color_gold_200'; import chart_color_gold_300 from '@patternfly/react-tokens/dist/esm/chart_color_gold_300'; import chart_color_gold_400 from '@patternfly/react-tokens/dist/esm/chart_color_gold_400'; import chart_color_gold_500 from '@patternfly/react-tokens/dist/esm/chart_color_gold_500'; import chart_color_orange_100 from '@patternfly/react-tokens/dist/esm/chart_color_orange_100'; import chart_color_orange_200 from '@patternfly/react-tokens/dist/esm/chart_color_orange_200'; import chart_color_orange_300 from '@patternfly/react-tokens/dist/esm/chart_color_orange_300'; import chart_color_orange_400 from '@patternfly/react-tokens/dist/esm/chart_color_orange_400'; import chart_color_orange_500 from '@patternfly/react-tokens/dist/esm/chart_color_orange_500'; import chart_color_black_100 from '@patternfly/react-tokens/dist/esm/chart_color_black_100'; import chart_color_black_200 from '@patternfly/react-tokens/dist/esm/chart_color_black_200'; import chart_color_black_300 from '@patternfly/react-tokens/dist/esm/chart_color_black_300'; import chart_color_black_400 from '@patternfly/react-tokens/dist/esm/chart_color_black_400'; import chart_color_black_500 from '@patternfly/react-tokens/dist/esm/chart_color_black_500'; import { ColorTheme } from '../color-theme'; // The color order below improves the color contrast in unordered charts; area & line // See https://github.com/patternfly/patternfly-next/issues/1551 const COLOR_SCALE = [ chart_color_blue_300.value, chart_color_gold_300.value, chart_color_green_300.value, chart_color_purple_300.value, chart_color_orange_300.value, chart_color_cyan_300.value, chart_color_black_300.value, chart_color_blue_100.value, chart_color_gold_500.value, chart_color_green_100.value, chart_color_purple_500.value, chart_color_orange_100.value, chart_color_cyan_500.value, chart_color_black_100.value, chart_color_blue_500.value, chart_color_gold_100.value, chart_color_green_500.value, chart_color_purple_100.value, chart_color_orange_500.value, chart_color_cyan_100.value, chart_color_black_500.value, chart_color_blue_200.value, chart_color_gold_400.value, chart_color_green_200.value, chart_color_purple_400.value, chart_color_orange_200.value, chart_color_cyan_400.value, chart_color_black_200.value, chart_color_blue_400.value, chart_color_gold_200.value, chart_color_green_400.value, chart_color_purple_200.value, chart_color_orange_400.value, chart_color_cyan_200.value, chart_color_black_400.value ]; export const LightMultiColorUnorderedTheme = ColorTheme({ COLOR_SCALE });
jelly/patternfly-react
packages/react-integration/cypress/integration/jumplinks.spec.ts
<filename>packages/react-integration/cypress/integration/jumplinks.spec.ts<gh_stars>100-1000 describe('Jump Link Demo Test', () => { it('Navigate to demo section', () => { cy.visit('http://localhost:3000/jump-links-demo-nav-link'); }); it('Should jump on click', () => { cy.get('#ts-demo-app-page-id').then(el => { const firstScroll = el.scrollTop(); expect(firstScroll).to.eq(0); }); cy.get('#heading-2').click(); cy.get('#ts-demo-app-page-id').then(el => { expect(el.scrollTop()).to.not.eq(0); }); }); });
jelly/patternfly-react
packages/react-topology/src/components/groups/DefaultGroupCollapsed.tsx
<filename>packages/react-topology/src/components/groups/DefaultGroupCollapsed.tsx import * as React from 'react'; import { observer } from 'mobx-react'; import { css } from '@patternfly/react-styles'; import styles from '@patternfly/react-styles/css/components/Topology/topology-components'; import ExpandIcon from '@patternfly/react-icons/dist/esm/icons/expand-alt-icon'; import { Layer } from '../layers'; import { GROUPS_LAYER } from '../../const'; import { createSvgIdUrl, useCombineRefs, useHover, useSize } from '../../utils'; import { BadgeLocation, LabelPosition, Node } from '../../types'; import { useDragNode, WithContextMenuProps, WithDndDropProps, WithDragNodeProps, WithSelectionProps } from '../../behavior'; import { Ellipse } from '../nodes/shapes'; import NodeLabel from '../nodes/labels/NodeLabel'; import { NODE_SHADOW_FILTER_ID_HOVER } from '../nodes/NodeShadows'; import LabelBadge from '../nodes/labels/LabelBadge'; import { CollapsibleGroupProps } from './types'; type DefaultGroupCollapsedProps = { className?: string; element: Node; droppable?: boolean; canDrop?: boolean; dropTarget?: boolean; dragging?: boolean; hover?: boolean; label?: string; // Defaults to element.getLabel() secondaryLabel?: string; showLabel?: boolean; // Defaults to true 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 & WithDragNodeProps & WithSelectionProps & WithDndDropProps & WithContextMenuProps>; const DefaultGroupCollapsed: React.FunctionComponent<DefaultGroupCollapsedProps> = ({ className, element, collapsible, selected, onSelect, children, hover, label, secondaryLabel, showLabel = true, truncateLength, collapsedWidth, collapsedHeight, getCollapsedShape, onCollapseChange, collapsedShadowOffset = 8, dndDropRef, dragNodeRef, canDrop, dropTarget, onContextMenu, contextMenuOpen, dragging, labelPosition, badge, badgeColor, badgeTextColor, badgeBorderColor, badgeClassName, badgeLocation, labelIconClass, labelIcon, labelIconPadding }) => { const [hovered, hoverRef] = useHover(); const [labelHover, labelHoverRef] = useHover(); const dragLabelRef = useDragNode()[1]; const [shapeSize, shapeRef] = useSize([collapsedWidth, collapsedHeight]); const refs = useCombineRefs<SVGPathElement>(hoverRef, dragNodeRef, shapeRef); const isHover = hover !== undefined ? hover : hovered; const childCount = element.getAllNodeChildren().length; const [badgeSize, badgeRef] = useSize([childCount]); const groupClassName = css( styles.topologyGroup, className, canDrop && 'pf-m-highlight', canDrop && dropTarget && 'pf-m-drop-target', dragging && 'pf-m-dragging', selected && 'pf-m-selected' ); const ShapeComponent = getCollapsedShape ? getCollapsedShape(element) : Ellipse; const filter = isHover || dragging || dropTarget ? createSvgIdUrl(NODE_SHADOW_FILTER_ID_HOVER) : undefined; return ( <g ref={labelHoverRef} onContextMenu={onContextMenu} onClick={onSelect} className={groupClassName}> <Layer id={GROUPS_LAYER}> <g ref={refs} onClick={onSelect}> {ShapeComponent && ( <> <g transform={`translate(${collapsedShadowOffset * 2}, 0)`}> <ShapeComponent className={css(styles.topologyNodeBackground, 'pf-m-disabled')} element={element} width={collapsedWidth} height={collapsedHeight} /> </g> <g transform={`translate(${collapsedShadowOffset}, 0)`}> <ShapeComponent className={css(styles.topologyNodeBackground, 'pf-m-disabled')} element={element} width={collapsedWidth} height={collapsedHeight} /> </g> <ShapeComponent className={css(styles.topologyNodeBackground)} key={isHover || dragging || dropTarget ? 'shape-background-hover' : 'shape-background'} // update key to force remount and filter update element={element} width={collapsedWidth} height={collapsedHeight} dndDropRef={dndDropRef} filter={filter} /> </> )} </g> </Layer> {shapeSize && childCount && ( <LabelBadge className={styles.topologyGroupCollapsedBadge} ref={badgeRef} x={shapeSize.width - 8} y={(shapeSize.width - (badgeSize?.height ?? 0)) / 2} badge={`${childCount}`} badgeColor={badgeColor} badgeTextColor={badgeTextColor} badgeBorderColor={badgeBorderColor} /> )} {showLabel && ( <NodeLabel className={styles.topologyGroupLabel} x={labelPosition === LabelPosition.right ? collapsedWidth + 8 : collapsedWidth / 2} y={labelPosition === LabelPosition.right ? collapsedHeight / 2 : collapsedHeight + 6} paddingX={8} paddingY={5} dragRef={dragNodeRef ? dragLabelRef : undefined} status={element.getNodeStatus()} secondaryLabel={secondaryLabel} truncateLength={truncateLength} badge={badge} badgeColor={badgeColor} badgeTextColor={badgeTextColor} badgeBorderColor={badgeBorderColor} badgeClassName={badgeClassName} badgeLocation={badgeLocation} labelIconClass={labelIconClass} labelIcon={labelIcon} labelIconPadding={labelIconPadding} onContextMenu={onContextMenu} contextMenuOpen={contextMenuOpen} hover={isHover || labelHover} actionIcon={collapsible ? <ExpandIcon /> : undefined} onActionIconClick={() => onCollapseChange(element, false)} > {label || element.getLabel()} </NodeLabel> )} {children} </g> ); }; export default observer(DefaultGroupCollapsed);
jelly/patternfly-react
packages/react-core/src/components/Drawer/Drawer.tsx
<gh_stars>0 import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/Drawer/drawer'; import { css } from '@patternfly/react-styles'; export enum DrawerColorVariant { default = 'default', light200 = 'light-200' } export interface DrawerProps extends React.HTMLProps<HTMLDivElement> { /** Additional classes added to the Drawer. */ className?: string; /** Content rendered in the left hand panel */ children?: React.ReactNode; /** Indicates if the drawer is expanded */ isExpanded?: boolean; /** Indicates if the content element and panel element are displayed side by side. */ isInline?: boolean; /** Indicates if the drawer will always show both content and panel. */ isStatic?: boolean; /** Position of the drawer panel */ position?: 'left' | 'right' | 'bottom'; /** Callback when drawer panel is expanded after waiting 250ms for animation to complete. */ onExpand?: () => void; } export interface DrawerContextProps { isExpanded: boolean; isStatic: boolean; onExpand?: () => void; position?: string; drawerRef?: React.RefObject<HTMLDivElement>; isInline: boolean; } export const DrawerContext = React.createContext<Partial<DrawerContextProps>>({ isExpanded: false, isStatic: false, onExpand: () => {}, position: 'right', drawerRef: null, isInline: false }); export const Drawer: React.FunctionComponent<DrawerProps> = ({ className = '', children, isExpanded = false, isInline = false, isStatic = false, position = 'right', onExpand = () => {}, ...props }: DrawerProps) => { const drawerRef = React.useRef<HTMLDivElement>(); return ( <DrawerContext.Provider value={{ isExpanded, isStatic, onExpand, position, drawerRef, isInline }}> <div className={css( styles.drawer, isExpanded && styles.modifiers.expanded, isInline && styles.modifiers.inline, isStatic && styles.modifiers.static, position === 'left' && styles.modifiers.panelLeft, position === 'bottom' && styles.modifiers.panelBottom, className )} ref={drawerRef} {...props} > {children} </div> </DrawerContext.Provider> ); }; Drawer.displayName = 'Drawer';