An open source design system that's fully customizable and agent ready
TypeScript
XDSLink (#97)
Andrey Goder0e8bebbfbf44
diff --git a/apps/storybook/stories/Link.stories.tsx b/apps/storybook/stories/Link.stories.tsxnew file mode 100644index 0000000000..d63f429650--- /dev/null+++ b/apps/storybook/stories/Link.stories.tsx@@ -0,0 +1,267 @@+import type {Meta, StoryObj} from '@storybook/react';+import {XDSLink} from '@xds/core/Link';+import {XDSText} from '@xds/core/Text';++const meta: Meta<typeof XDSLink> = {+ title: 'Core/XDSLink',+ component: XDSLink,+ tags: ['autodocs'],+ argTypes: {+ label: {+ control: 'text',+ description: 'Accessible label (required)',+ },+ href: {+ control: 'text',+ description: 'Link destination URL',+ },+ color: {+ control: 'select',+ options: [+ 'active',+ 'primary',+ 'secondary',+ 'disabled',+ 'placeholder',+ 'inherit',+ ],+ description: 'Text color',+ },+ hasUnderline: {+ control: 'boolean',+ description: 'Always show underline',+ },+ isDisabled: {+ control: 'boolean',+ description: 'Disabled state',+ },+ isExternalLink: {+ control: 'boolean',+ description: 'Opens in new tab with external icon',+ },+ tooltip: {+ control: 'text',+ description: 'Tooltip text on hover',+ },+ standalone: {+ control: 'boolean',+ description: 'Standalone (applies base font sizing)',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSLink>;++export const Default: Story = {+ args: {+ label: 'Documentation',+ href: '/docs',+ children: 'Documentation',+ },+};++export const Secondary: Story = {+ args: {+ label: 'Privacy Policy',+ href: '/privacy',+ color: 'secondary',+ children: 'Privacy Policy',+ },+};++export const Primary: Story = {+ args: {+ label: 'Learn more',+ href: '/learn',+ color: 'primary',+ children: 'Learn more',+ },+};++export const WithUnderline: Story = {+ args: {+ label: 'Always underlined',+ href: '/underlined',+ hasUnderline: true,+ children: 'Always underlined',+ },+};++export const Disabled: Story = {+ args: {+ label: 'Disabled link',+ href: '/disabled',+ isDisabled: true,+ children: 'Disabled link',+ },+};++export const ExternalLink: Story = {+ args: {+ label: 'GitHub',+ href: 'https://github.com',+ isExternalLink: true,+ children: 'GitHub',+ },+};++export const WithTooltip: Story = {+ args: {+ label: 'Settings',+ href: '/settings',+ tooltip: 'Configure your preferences',+ children: 'Settings',+ },+};++export const Standalone: Story = {+ args: {+ label: 'Standalone Link',+ href: '/standalone',+ standalone: true,+ children: 'Standalone Link',+ },+};++export const InlineWithText: Story = {+ render: () => (+ <XDSText type="body">+ Read the{' '}+ <XDSLink label="documentation" href="/docs">+ documentation+ </XDSLink>{' '}+ for more information about using XDS components.+ </XDSText>+ ),+};++export const AllVariants: Story = {+ render: () => (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '12px',+ maxWidth: '600px',+ }}>+ <div style={{display: 'flex', gap: '16px', alignItems: 'center'}}>+ <XDSLink label="Active (default)" href="/active" standalone>+ Active (default)+ </XDSLink>+ <XDSLink label="Primary" href="/primary" color="primary" standalone>+ Primary+ </XDSLink>+ <XDSLink+ label="Secondary"+ href="/secondary"+ color="secondary"+ standalone>+ Secondary+ </XDSLink>+ <XDSLink label="Inherit" href="/inherit" color="inherit" standalone>+ Inherit+ </XDSLink>+ </div>+ <div style={{display: 'flex', gap: '16px', alignItems: 'center'}}>+ <XDSLink+ label="With underline"+ href="/underlined"+ hasUnderline+ standalone>+ With underline+ </XDSLink>+ <XDSLink+ label="External"+ href="https://example.com"+ isExternalLink+ standalone>+ External+ </XDSLink>+ <XDSLink+ label="With tooltip"+ href="/tooltip"+ tooltip="Helpful info"+ standalone>+ With tooltip+ </XDSLink>+ </div>+ <div style={{display: 'flex', gap: '16px', alignItems: 'center'}}>+ <XDSLink label="Disabled active" href="/disabled" isDisabled standalone>+ Disabled active+ </XDSLink>+ <XDSLink+ label="Disabled secondary"+ href="/disabled"+ color="secondary"+ isDisabled+ standalone>+ Disabled secondary+ </XDSLink>+ </div>+ </div>+ ),+};++export const ExternalLinks: Story = {+ render: () => (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',+ }}>+ <XDSLink+ label="GitHub"+ href="https://github.com"+ isExternalLink+ standalone>+ GitHub+ </XDSLink>+ <XDSLink+ label="MDN Web Docs"+ href="https://developer.mozilla.org"+ isExternalLink+ standalone>+ MDN Web Docs+ </XDSLink>+ <XDSLink+ label="React Documentation"+ href="https://react.dev"+ isExternalLink+ hasUnderline+ standalone>+ React Documentation+ </XDSLink>+ </div>+ ),+};++export const LinksWithTooltips: Story = {+ render: () => (+ <div style={{display: 'flex', gap: '16px', alignItems: 'center'}}>+ <XDSLink+ label="Settings"+ href="/settings"+ tooltip="Configure your account settings"+ standalone>+ Settings+ </XDSLink>+ <XDSLink+ label="Profile"+ href="/profile"+ tooltip="View and edit your profile"+ standalone>+ Profile+ </XDSLink>+ <XDSLink+ label="Help"+ href="/help"+ tooltip="Get help and support"+ color="secondary"+ standalone>+ Help+ </XDSLink>+ </div>+ ),+};diff --git a/packages/core/src/Link/README.md b/packages/core/src/Link/README.mdnew file mode 100644index 0000000000..a1cff49a2e--- /dev/null+++ b/packages/core/src/Link/README.md@@ -0,0 +1,81 @@+# /packages/core/src/Link++XDSLink component for styled anchor links with multiple variants and features.++<!-- SYNC: When files in this directory change, update this document. -->++## Features++- **Variants**: `default`, `subtle`, `inherit`+- **External links**: Opens in new tab with external link icon+- **Tooltip support**: Display tooltip text on hover+- **Underline control**: Always show underline or only on hover+- **Inline support**: Inherits parent font styles when used within text+- **Standalone mode**: Applies base font sizing for independent links+- **Disabled state**: Visual and interaction disabled+- **Focus visible**: Accessible focus outline++## Usage++```tsx+import { XDSLink } from '@xds/core/Link';++// Basic link+<XDSLink label="Documentation" href="/docs">Documentation</XDSLink>++// External link (opens in new tab with icon)+<XDSLink label="GitHub" href="https://github.com" isExternalLink>GitHub</XDSLink>++// Link with tooltip+<XDSLink label="Settings" href="/settings" tooltip="Configure your preferences">+ Settings+</XDSLink>++// Always underlined link+<XDSLink label="Privacy Policy" href="/privacy" hasUnderline>Privacy Policy</XDSLink>++// Inline within text (inherits parent font styles)+<XDSText>Read the <XDSLink label="docs" href="/docs">documentation</XDSLink> for more info.</XDSText>++// Standalone link+<XDSLink label="Settings" href="/settings" standalone>Settings</XDSLink>++// Subtle variant+<XDSLink label="Privacy" href="/privacy" variant="subtle">Privacy Policy</XDSLink>++// Disabled link+<XDSLink label="Disabled" href="/disabled" isDisabled>Disabled Link</XDSLink>+```++## Props++| Prop | Type | Default | Description |+| ---------------- | ------------------------------------ | ----------- | ----------------------------------- |+| `label` | `string` | — | Accessible label (required) |+| `href` | `string` | — | Link destination URL |+| `variant` | `'default' \| 'subtle' \| 'inherit'` | `'default'` | Visual style variant |+| `hasUnderline` | `boolean` | `false` | Always show underline |+| `isDisabled` | `boolean` | `false` | Disables the link |+| `isExternalLink` | `boolean` | `false` | Opens in new tab with external icon |+| `target` | `string` | — | Where to open linked document |+| `onClick` | `MouseEventHandler` | — | Click event handler |+| `tooltip` | `string` | — | Tooltip text displayed on hover |+| `standalone` | `boolean` | `false` | Applies base font sizing |+| `children` | `ReactNode` | — | Link content (required) |++## Files++| File | Role | Purpose |+| ------------------ | ----- | ----------------------------------- |+| `index.ts` | Entry | Exports XDSLink component and types |+| `XDSLink.tsx` | Core | XDSLink component implementation |+| `XDSLink.test.tsx` | Test | Unit tests for XDSLink component |++## Implementation Notes++- `XDSLinkVariant` type is derived from the `variants` StyleX object using `keyof typeof variants`+- By default, links inherit font family, size, line-height, and weight from parent elements+- Use `standalone` prop when the link is not inline within other text content+- `isExternalLink` automatically sets `target="_blank"` and `rel="noopener noreferrer"` for security+- Disabled state uses `aria-disabled` and `pointer-events: none` for accessibility+- Tooltip wraps the link in `XDSTooltip` component when provideddiff --git a/packages/core/src/Link/XDSLink.test.tsx b/packages/core/src/Link/XDSLink.test.tsxnew file mode 100644index 0000000000..5dbef1df66--- /dev/null+++ b/packages/core/src/Link/XDSLink.test.tsx@@ -0,0 +1,167 @@+/**+ * @file XDSLink.test.tsx+ * @input Uses vitest, @testing-library/react, XDSLink component+ * @output Unit tests for XDSLink component behavior+ * @position Testing; validates XDSLink.tsx implementation+ *+ * SYNC: When XDSLink.tsx changes, update tests to match new behavior+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {XDSLink} from './XDSLink';++describe('XDSLink', () => {+ it('renders children as link text', () => {+ render(+ <XDSLink label="Click me" href="/test">+ Click me+ </XDSLink>,+ );+ expect(screen.getByRole('link', {name: 'Click me'})).toBeInTheDocument();+ });++ it('renders with href attribute', () => {+ render(+ <XDSLink label="Link" href="/destination">+ Link+ </XDSLink>,+ );+ expect(screen.getByRole('link')).toHaveAttribute('href', '/destination');+ });++ it('renders with aria-label from label prop', () => {+ render(+ <XDSLink label="Accessible label" href="/test">+ Visible text+ </XDSLink>,+ );+ expect(screen.getByRole('link')).toHaveAttribute(+ 'aria-label',+ 'Accessible label',+ );+ });++ it('renders with different variants', () => {+ const {rerender} = render(+ <XDSLink label="Default" href="/test" variant="default">+ Default+ </XDSLink>,+ );+ expect(screen.getByRole('link')).toBeInTheDocument();++ rerender(+ <XDSLink label="Subtle" href="/test" variant="subtle">+ Subtle+ </XDSLink>,+ );+ expect(screen.getByRole('link')).toBeInTheDocument();++ rerender(+ <XDSLink label="Inherit" href="/test" variant="inherit">+ Inherit+ </XDSLink>,+ );+ expect(screen.getByRole('link')).toBeInTheDocument();+ });++ it('applies hasUnderline style when true', () => {+ render(+ <XDSLink label="Underlined" href="/test" hasUnderline>+ Underlined Link+ </XDSLink>,+ );+ expect(screen.getByRole('link')).toBeInTheDocument();+ });++ it('applies isDisabled state correctly', () => {+ render(+ <XDSLink label="Disabled Link" href="/test" isDisabled>+ Disabled Link+ </XDSLink>,+ );+ const link = screen.getByRole('link');+ expect(link).toHaveAttribute('aria-disabled', 'true');+ expect(link).toHaveAttribute('tabIndex', '-1');+ });++ it('renders external link with icon and target="_blank"', () => {+ render(+ <XDSLink label="External" href="https://example.com" isExternalLink>+ External Link+ </XDSLink>,+ );+ const link = screen.getByRole('link');+ expect(link).toHaveAttribute('target', '_blank');+ expect(link).toHaveAttribute('rel', 'noopener noreferrer');+ // Check for the icon (SVG element)+ expect(link.querySelector('svg')).toBeInTheDocument();+ });++ it('renders external link with existing rel merged', () => {+ render(+ <XDSLink+ label="External"+ href="https://example.com"+ isExternalLink+ rel="sponsored">+ External Link+ </XDSLink>,+ );+ const link = screen.getByRole('link');+ expect(link).toHaveAttribute('rel', 'sponsored noopener noreferrer');+ });++ it('renders with custom target without isExternalLink', () => {+ render(+ <XDSLink label="Target" href="/test" target="_parent">+ Parent Link+ </XDSLink>,+ );+ const link = screen.getByRole('link');+ expect(link).toHaveAttribute('target', '_parent');+ });++ it('handles click events', async () => {+ const user = userEvent.setup();+ const handleClick = vi.fn(e => e.preventDefault());+ render(+ <XDSLink label="Click me" href="/test" onClick={handleClick}>+ Click me+ </XDSLink>,+ );++ await user.click(screen.getByRole('link'));+ expect(handleClick).toHaveBeenCalledTimes(1);+ });++ it('forwards ref correctly', () => {+ const ref = vi.fn();+ render(+ <XDSLink label="Test" href="/test" ref={ref}>+ Test+ </XDSLink>,+ );+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLAnchorElement));+ });++ it('renders standalone link', () => {+ render(+ <XDSLink label="Standalone Link" href="/standalone" standalone>+ Standalone Link+ </XDSLink>,+ );+ expect(screen.getByRole('link')).toBeInTheDocument();+ });++ it('renders link with tooltip', () => {+ render(+ <XDSLink label="Settings" href="/settings" tooltip="Configure settings">+ Settings+ </XDSLink>,+ );+ const link = screen.getByRole('link', {name: 'Settings'});+ expect(link).toBeInTheDocument();+ });+});diff --git a/packages/core/src/Link/XDSLink.tsx b/packages/core/src/Link/XDSLink.tsxnew file mode 100644index 0000000000..e70e518987--- /dev/null+++ b/packages/core/src/Link/XDSLink.tsx@@ -0,0 +1,267 @@+/**+ * @file XDSLink.tsx+ * @input Uses React forwardRef, AnchorHTMLAttributes, ReactNode+ * @output Exports XDSLink component, XDSLinkProps+ * @position Core implementation; consumed by index.ts, tested by XDSLink.test.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Link/README.md (props table, features, implementation notes)+ * - /packages/core/src/Link/XDSLink.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/Link/index.ts (exports if types change)+ * - /apps/storybook/stories/Link.stories.tsx (storybook stories)+ */++import {+ forwardRef,+ type AnchorHTMLAttributes,+ type MouseEventHandler,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {ArrowTopRightOnSquareIcon} from '@heroicons/react/16/solid';+import {+ colorVars,+ transitionVars,+ textSizeVars,+ lineHeightVars,+ spacingVars,+} from '../theme/tokens.stylex';+import {XDSIcon} from '../Icon';+import {XDSTooltip} from '../Layer';+import {XDSText} from '../Text';+import type {+ XDSTextType,+ XDSTextSize,+ XDSTextColor,+ XDSTextWeight,+ XDSTextDisplay,+} from '../theme/types';++/**+ * Base link styles+ */+const styles = stylex.create({+ base: {+ display: 'inline-flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-0-5'],+ fontFamily: 'inherit',+ fontSize: 'inherit',+ lineHeight: 'inherit',+ fontWeight: 'inherit',+ textDecoration: {+ default: 'none',+ ':hover': 'underline',+ },+ cursor: 'pointer',+ transitionProperty: 'color, text-decoration',+ transitionDuration: transitionVars['--transition-fast'],+ outline: {+ default: null,+ ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: {+ default: '0',+ ':focus-visible': '2px',+ },+ },+ hasUnderline: {+ textDecoration: 'underline',+ },+ disabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ pointerEvents: 'none',+ },+ standalone: {+ fontSize: textSizeVars['--text-base'],+ lineHeight: lineHeightVars['--leading-base'],+ },+});++export interface XDSLinkProps extends Omit<+ AnchorHTMLAttributes<HTMLAnchorElement>,+ 'children'+> {+ /**+ * Accessible label for the link (required for accessibility).+ * Used as aria-label when content is not self-descriptive.+ */+ label: string;+ /**+ * Link destination URL.+ */+ href?: string;+ /**+ * Whether the link should always display an underline.+ * When false, underline only appears on hover.+ * @default false+ */+ hasUnderline?: boolean;+ /**+ * Whether the link is disabled.+ * @default false+ */+ isDisabled?: boolean;+ /**+ * Whether the link opens in a new tab with an external link icon.+ * When true, sets target="_blank" and rel="noopener noreferrer".+ * @default false+ */+ isExternalLink?: boolean;+ /**+ * Where to open the linked document.+ * Overridden to "_blank" when isExternalLink is true.+ */+ target?: string;+ /**+ * Click event handler.+ */+ onClick?: MouseEventHandler<HTMLAnchorElement>;+ /**+ * Tooltip text to display on hover.+ */+ tooltip?: string;+ /**+ * Whether the link is standalone (not inline within text).+ * Applies base font sizing when true.+ * @default false+ */+ standalone?: boolean;+ /**+ * Semantic text type for XDSText. Determines base typography.+ * @default 'body'+ */+ type?: XDSTextType;+ /**+ * Explicit font size override. Forwarded to XDSText.+ */+ size?: XDSTextSize;+ /**+ * Font weight override. Forwarded to XDSText.+ */+ weight?: XDSTextWeight;+ /**+ * Text color. Forwarded to XDSText.+ * @default 'active'+ */+ color?: XDSTextColor;+ /**+ * Display type for XDSText. Forwarded to XDSText.+ * @default 'inline'+ */+ display?: XDSTextDisplay;+ /**+ * Maximum lines before truncation. Forwarded to XDSText.+ * @default 0+ */+ maxLines?: number;+ /**+ * Link content (required).+ */+ children: ReactNode;+}++/**+ * A styled anchor link component.+ *+ * Uses XDSText internally for typography styling.+ * Wrap your app in <Theme> to apply a theme.+ *+ * @example+ * ```tsx+ * // Basic link+ * <XDSLink label="Documentation" href="/docs">Documentation</XDSLink>+ *+ * // External link (opens in new tab with icon)+ * <XDSLink label="GitHub" href="https://github.com" isExternalLink>GitHub</XDSLink>+ *+ * // Link with custom color+ * <XDSLink label="Settings" href="/settings" color="secondary">Settings</XDSLink>+ *+ * // Always underlined link+ * <XDSLink label="Privacy Policy" href="/privacy" hasUnderline>Privacy Policy</XDSLink>+ * ```+ */+export const XDSLink = forwardRef<HTMLAnchorElement, XDSLinkProps>(+ (+ {+ label,+ href,+ hasUnderline = false,+ isDisabled = false,+ isExternalLink = false,+ target,+ onClick,+ tooltip,+ standalone = false,+ type = 'body',+ size,+ weight,+ color = 'active',+ display = 'inline',+ maxLines = 0,+ children,+ rel,+ ...props+ },+ ref,+ ) => {+ // Determine target and rel based on isExternalLink+ const computedTarget = isExternalLink ? '_blank' : target;+ const computedRel = isExternalLink+ ? rel+ ? `${rel} noopener noreferrer`+ : 'noopener noreferrer'+ : rel;++ const linkElement = (+ <a+ ref={ref}+ href={href}+ target={computedTarget}+ rel={computedRel}+ onClick={onClick}+ aria-label={label}+ aria-disabled={isDisabled || undefined}+ tabIndex={isDisabled ? -1 : undefined}+ {...stylex.props(+ styles.base,+ hasUnderline && styles.hasUnderline,+ standalone && styles.standalone,+ isDisabled && styles.disabled,+ )}+ {...props}>+ <XDSText+ type={type}+ size={size}+ weight={weight}+ color={color}+ display={display}+ maxLines={maxLines}>+ {children}+ </XDSText>+ {isExternalLink && (+ <XDSIcon+ icon={ArrowTopRightOnSquareIcon}+ size="xsm"+ color="inherit"+ />+ )}+ </a>+ );++ // Wrap with tooltip if provided+ if (tooltip) {+ return (+ <XDSTooltip content={tooltip} placement="above">+ {linkElement}+ </XDSTooltip>+ );+ }++ return linkElement;+ },+);++XDSLink.displayName = 'XDSLink';diff --git a/packages/core/src/Link/index.ts b/packages/core/src/Link/index.tsnew file mode 100644index 0000000000..95f86b3516--- /dev/null+++ b/packages/core/src/Link/index.ts@@ -0,0 +1,11 @@+/**+ * @file index.ts+ * @input Imports XDSLink component and types from XDSLink.tsx+ * @output Exports XDSLink, XDSLinkProps+ * @position Component entry point; re-exported by /packages/core/src/index.ts+ *+ * SYNC: When modified, update this header and /packages/core/src/Link/README.md+ */++export {XDSLink} from './XDSLink';+export type {XDSLinkProps} from './XDSLink';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 039b89cd2e..e8c4f774e2 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -16,6 +16,7 @@ export * from './Calendar';export * from './Center';export * from './CheckboxInput';export * from './Divider';+export * from './Link';export * from './Switch';export * from './DateInput';export * from './Field';