Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: introduce as prop for Hyperlink #3082

Merged
merged 1 commit into from
Jan 31, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/Button/Button.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from 'react';
import { IntlProvider } from 'react-intl';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import renderer from 'react-test-renderer';
Expand Down Expand Up @@ -96,7 +97,11 @@ describe('<Button />', () => {
test('test button as hyperlink', () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const ref = (_current: HTMLAnchorElement) => {}; // Check typing of a ref - should not show type errors.
render(<Button as={Hyperlink} ref={ref} destination="https://www.poop.com/💩">Button</Button>);
render(
<IntlProvider locale="en">
<Button as={Hyperlink} ref={ref} destination="https://www.poop.com/💩">Button</Button>
</IntlProvider>,
);
expect(screen.getByRole('link').getAttribute('href')).toEqual('https://www.poop.com/💩');
});
});
Expand Down
70 changes: 50 additions & 20 deletions src/Hyperlink/Hyperlink.test.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import React from 'react';
import { IntlProvider } from 'react-intl';
import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import Hyperlink from '.';
import Hyperlink, { HyperlinkProps } from '.';

const destination = 'destination';
const destination = 'http://destination.example';
const content = 'content';
const onClick = jest.fn();
const onClick = jest.fn().mockImplementation((e) => e.preventDefault());
const props = {
destination,
onClick,
Expand All @@ -20,13 +20,37 @@ const externalLinkProps = {
...props,
};

interface LinkProps extends HyperlinkProps {
to: string;
}

function Link({ to, children, ...rest }: LinkProps) {
return (
<a
data-testid="custom-hyperlink-element"
href={to}
{...rest}
>
{children}
</a>
);
}

function HyperlinkWrapper({ children, ...rest }: HyperlinkProps) {
return (
<IntlProvider locale="en">
<Hyperlink {...rest}>{children}</Hyperlink>
</IntlProvider>
);
}

describe('correct rendering', () => {
beforeEach(() => {
onClick.mockClear();
jest.clearAllMocks();
});

it('renders Hyperlink', async () => {
const { getByRole } = render(<Hyperlink {...props}>{content}</Hyperlink>);
const { getByRole } = render(<HyperlinkWrapper {...props}>{content}</HyperlinkWrapper>);
const wrapper = getByRole('link');
expect(wrapper).toBeInTheDocument();

Expand All @@ -36,12 +60,29 @@ describe('correct rendering', () => {
expect(wrapper).toHaveAttribute('href', destination);
expect(wrapper).toHaveAttribute('target', '_self');

// Clicking on the link should call the onClick handler
await userEvent.click(wrapper);
expect(onClick).toHaveBeenCalledTimes(1);
});

it('renders with custom element type via "as" prop', () => {
const propsWithoutDestination = {
to: destination, // `to` simulates common `Link` components' prop
};
const { getByRole } = render(<HyperlinkWrapper as={Link} {...propsWithoutDestination}>{content}</HyperlinkWrapper>);
const wrapper = getByRole('link');
expect(wrapper).toBeInTheDocument();

expect(wrapper).toHaveClass('pgn__hyperlink');
expect(wrapper).toHaveClass('standalone-link');
expect(wrapper).toHaveTextContent(content);
expect(wrapper).toHaveAttribute('href', destination);
expect(wrapper).toHaveAttribute('target', '_self');
expect(wrapper).toHaveAttribute('data-testid', 'custom-hyperlink-element');
});

it('renders an underlined Hyperlink', async () => {
const { getByRole } = render(<Hyperlink isInline {...props}>{content}</Hyperlink>);
const { getByRole } = render(<HyperlinkWrapper isInline {...props}>{content}</HyperlinkWrapper>);
const wrapper = getByRole('link');
expect(wrapper).toBeInTheDocument();
expect(wrapper).toHaveClass('pgn__hyperlink');
Expand All @@ -50,7 +91,7 @@ describe('correct rendering', () => {
});

it('renders external Hyperlink', () => {
const { getByRole, getByTestId } = render(<Hyperlink {...externalLinkProps}>{content}</Hyperlink>);
const { getByRole, getByTestId } = render(<HyperlinkWrapper {...externalLinkProps}>{content}</HyperlinkWrapper>);
const wrapper = getByRole('link');
const icon = getByTestId('hyperlink-icon');
const iconSvg = icon.querySelector('svg');
Expand All @@ -66,19 +107,8 @@ describe('correct rendering', () => {

describe('security', () => {
it('prevents reverse tabnabbing for links with target="_blank"', () => {
const { getByRole } = render(<Hyperlink {...externalLinkProps}>{content}</Hyperlink>);
const { getByRole } = render(<HyperlinkWrapper {...externalLinkProps}>{content}</HyperlinkWrapper>);
const wrapper = getByRole('link');
expect(wrapper).toHaveAttribute('rel', 'noopener noreferrer');
});
});

describe('event handlers are triggered correctly', () => {
it('should fire onClick', async () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like onClick is still something we have an example for on the docs site https://deploy-preview-3082--paragon-openedx.netlify.app/components/hyperlink/#with-onclick

I think it might be worth keeping this test to cover the off chance someone accidentally removes onClick={onClick} from the Hyperlink component.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed this test case, as its behavior is technically already covered within the "renders Hyperlink" test case, i.e.:

// Clicking on the link should call the onClick handler
await userEvent.click(wrapper);
expect(onClick).toHaveBeenCalledTimes(1);

const spy = jest.fn();
const { getByRole } = render(<Hyperlink {...props} onClick={spy}>{content}</Hyperlink>);
const wrapper = getByRole('link');
expect(spy).toHaveBeenCalledTimes(0);
await userEvent.click(wrapper);
expect(spy).toHaveBeenCalledTimes(1);
});
});
15 changes: 14 additions & 1 deletion src/Hyperlink/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ categories:
- Buttonlike
status: 'Needs Work'
designStatus: 'Done'
devStatus: 'To Do'
devStatus: 'Done'
notes: |
Improve prop naming. Deprecate content prop.
Use React.forwardRef for ref forwarding.
Expand Down Expand Up @@ -100,3 +100,16 @@ notes: |
</div>
</div>
```

## with custom link element (e.g., using a router)

``Hyperlink`` typically relies on the standard HTML anchor tag (i.e., ``a``); however, this behavior may be overriden when the destination link is to an internal route where it should be using routing instead (e.g., ``Link`` from React Router).

```jsx live
<Hyperlink
as={GatsbyLink}
to="/components/button"
>
Button
</Hyperlink>
```
100 changes: 70 additions & 30 deletions src/Hyperlink/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import React from 'react';
import React, { forwardRef } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {
type BsPrefixRefForwardingComponent as ComponentWithAsProp,
type BsPrefixProps,
} from 'react-bootstrap/esm/helpers';
import { defineMessages, useIntl } from 'react-intl';
import { Launch } from '../../icons';
import Icon from '../Icon';
// @ts-ignore
import { customPropTypeRequirement } from '../utils/propTypes/utils';

export const HYPER_LINK_EXTERNAL_LINK_ALT_TEXT = 'in a new tab';
export const HYPER_LINK_EXTERNAL_LINK_TITLE = 'Opens in a new tab';

interface Props extends Omit<React.ComponentPropsWithRef<'a'>, 'href' | 'target'> {
export interface HyperlinkProps extends BsPrefixProps, Omit<React.ComponentPropsWithRef<'a'>, 'href' | 'target'> {
/** specifies the URL */
destination: string;
destination?: string;
/** Content of the hyperlink */
children: React.ReactNode;
/** Custom class names for the hyperlink */
Expand All @@ -24,22 +28,42 @@ interface Props extends Omit<React.ComponentPropsWithRef<'a'>, 'href' | 'target'
isInline?: boolean;
/** specify if we need to show launch Icon. By default, it will be visible. */
showLaunchIcon?: boolean;
/** specifies where the link should open. The default behavior is `_self`, which means that the URL will be
* loaded into the same browsing context as the current one.
* If the target is `_blank` (opening a new window) `rel='noopener'` will be added to the anchor tag to prevent
* any potential [reverse tabnabbing attack](https://www.owasp.org/index.php/Reverse_Tabnabbing).
*/
target?: '_blank' | '_self';
}

const Hyperlink = React.forwardRef<HTMLAnchorElement, Props>(({
export type HyperlinkType = ComponentWithAsProp<'a', HyperlinkProps>;

const messages = defineMessages({
externalLinkAltText: {
id: 'Hyperlink.externalLinkAltText',
defaultMessage: 'in a new tab',
},
externalLinkTitle: {
id: 'Hyperlink.externalLinkTitle',
defaultMessage: 'Opens in a new tab',
},
});

const Hyperlink = forwardRef<HTMLAnchorElement, HyperlinkProps>(({
as: Component = 'a',
className,
destination,
children,
target,
target = '_self',
onClick,
externalLinkAlternativeText,
externalLinkTitle,
variant,
isInline,
showLaunchIcon,
variant = 'default',
isInline = false,
showLaunchIcon = true,
...attrs
}, ref) => {
const intl = useIntl();
let externalLinkIcon;

if (target === '_blank') {
Expand All @@ -63,11 +87,11 @@ const Hyperlink = React.forwardRef<HTMLAnchorElement, Props>(({
externalLinkIcon = (
<span
className="pgn__hyperlink__external-icon"
title={externalLinkTitle}
title={externalLinkTitle || intl.formatMessage(messages.externalLinkTitle)}
>
<Icon
src={Launch}
screenReaderText={externalLinkAlternativeText}
screenReaderText={externalLinkAlternativeText || intl.formatMessage(messages.externalLinkAltText)}
style={{ height: '1em', width: '1em' }}
data-testid="hyperlink-icon"
/>
Expand All @@ -76,8 +100,13 @@ const Hyperlink = React.forwardRef<HTMLAnchorElement, Props>(({
}
}

const additionalProps: Record<string, any> = { ...attrs };
if (destination) {
additionalProps.href = destination;
}

return (
<a
<Component
ref={ref}
className={classNames(
'pgn__hyperlink',
Expand All @@ -88,31 +117,27 @@ const Hyperlink = React.forwardRef<HTMLAnchorElement, Props>(({
},
className,
)}
href={destination}
target={target}
onClick={onClick}
{...attrs}
{...additionalProps}
>
{children}
{externalLinkIcon}
</a>
</Component>
);
});

Hyperlink.defaultProps = {
className: undefined,
target: '_self',
onClick: () => {},
externalLinkAlternativeText: HYPER_LINK_EXTERNAL_LINK_ALT_TEXT,
externalLinkTitle: HYPER_LINK_EXTERNAL_LINK_TITLE,
variant: 'default',
isInline: false,
showLaunchIcon: true,
};

Hyperlink.propTypes = {
/** specifies the URL */
destination: PropTypes.string.isRequired,
/** specifies the component element type to render for the hyperlink */
// @ts-ignore
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[inform] It's unclear why TS throws an error on the as prop type; as its functional, opting to @ts-ignore for now.

as: PropTypes.elementType,
/** specifies the URL; required iff `as` prop is a standard anchor tag */
destination: customPropTypeRequirement(
PropTypes.string,
({ as }: { as: React.ElementType }) => as && as === 'a',
// "[`destination` is required when]..."
'the `as` prop is a standard anchor element (i.e., "a")',
),
/** Content of the hyperlink */
// @ts-ignore
children: PropTypes.node.isRequired,
Expand All @@ -138,4 +163,19 @@ Hyperlink.propTypes = {
showLaunchIcon: PropTypes.bool,
};

Hyperlink.defaultProps = {
as: 'a',
className: undefined,
destination: undefined,
externalLinkAlternativeText: undefined,
externalLinkTitle: undefined,
isInline: false,
onClick: undefined,
showLaunchIcon: true,
target: '_self',
variant: 'default',
};

Hyperlink.displayName = 'Hyperlink';

export default Hyperlink;
15 changes: 12 additions & 3 deletions src/MailtoLink/MailtoLink.test.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import { render } from '@testing-library/react';
import { IntlProvider } from 'react-intl';

import MailtoLink from '.';

Expand All @@ -11,10 +12,18 @@ const content = 'content';

const baseProps = { subject, body, content };

function MailtoLinkWrapper(props) {
return (
<IntlProvider locale="en">
<MailtoLink {...props} />
</IntlProvider>
);
}

describe('correct rendering', () => {
it('renders MailtoLink with single to, cc, and bcc recipient', () => {
const singleRecipientLink = (
<MailtoLink
<MailtoLinkWrapper
{...baseProps}
to={emailAddress}
cc={emailAddress}
Expand All @@ -31,7 +40,7 @@ describe('correct rendering', () => {

it('renders mailtoLink with many to, cc, and bcc recipients', () => {
const multiRecipientLink = (
<MailtoLink
<MailtoLinkWrapper
{...baseProps}
to={emailAddresses}
cc={emailAddresses}
Expand All @@ -46,7 +55,7 @@ describe('correct rendering', () => {
});

it('renders empty mailtoLink', () => {
const { getByText } = render(<MailtoLink content={content} />);
const { getByText } = render(<MailtoLinkWrapper content={content} />);
const linkElement = getByText('content');
expect(linkElement.getAttribute('href')).toEqual('mailto:');
});
Expand Down
Loading