From ede43cef1b85232e6daaad8cfee26579fb8a6d09 Mon Sep 17 00:00:00 2001 From: Alex Smith Date: Wed, 9 Sep 2026 23:43:35 -0400 Subject: [PATCH 01/35] fix(bulma-ui): make props and refs follow the polymorphic `as` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `as` accepts any `React.ElementType` (#188), but every prop type stayed pinned to one element, so the declared types were wrong in both directions: `\n

Rendered element: {tag ?? '—'}

\n \n );\n}" } ], "accessibility": "- Image avatars use `alt` (falling back to `name`) for their accessible name.\n- Initials/icon avatars expose `role=\"img\"` and `aria-label` (from `alt`/`name`) — unless\n rendered as a link or button, where the native link/button role and `aria-label` are used\n instead.\n- **Decorative avatars:** pass an explicit `alt=\"\"` when the avatar repeats information\n already visible next to it (e.g. beside the author's name in a comment row). The image\n stays decorative and an initials/icon avatar is skipped entirely (`aria-hidden`), avoiding\n double-speak. The opt-out never applies to a link/button avatar — an interactive element\n always keeps an accessible name (from `name`, or a generic `\"Avatar\"` fallback).\n- A link/button avatar with no `alt`/`name` (e.g. an API that returns only a photo URL) still\n gets an `aria-label` fallback rather than rendering a nameless control.\n- `as=\"button\"` defaults to `type=\"button\"`, so a clickable avatar inside a form doesn't\n submit it.\n- The default fallback icon is `aria-hidden`.", @@ -47,6 +51,15 @@ "summary": "The `Avatar` component represents a person or entity as a compact image.", "component": null, "props": [ + { + "name": "as", + "type": "React.ElementType", + "default": null, + "description": "Element/component to render as. Defaults to `'a'` when `href` is set, else `'figure'`.", + "required": false, + "inherited": false, + "deprecated": false + }, { "name": "className", "type": "string", @@ -128,15 +141,6 @@ "inherited": false, "deprecated": false }, - { - "name": "as", - "type": "React.ElementType", - "default": null, - "description": "Element/component to render as. Defaults to `'a'` when `href` is set, else `'figure'`.", - "required": false, - "inherited": false, - "deprecated": false - }, { "name": "href", "type": "string", @@ -172,10 +176,29 @@ "required": false, "inherited": false, "deprecated": false + }, + { + "name": "style", + "type": "React.CSSProperties", + "default": null, + "description": "Inline styles, merged after the size style.", + "required": false, + "inherited": false, + "deprecated": false + } + ], + "extraProps": [ + { + "name": "ref", + "type": "React.Ref", + "default": null, + "description": "Ref forwarded to the element `as` renders.", + "required": false, + "inherited": false, + "deprecated": false } ], - "extraProps": [], - "catchAll": "All standard HTML attributes and Bulma helper props", + "catchAll": "All props of the element or component as renders and Bulma helper props", "types": [ { "name": "AvatarColor", diff --git a/bestax-mcp/data/components/Avatars.json b/bestax-mcp/data/components/Avatars.json index c22d80be8..f1c053c7e 100644 --- a/bestax-mcp/data/components/Avatars.json +++ b/bestax-mcp/data/components/Avatars.json @@ -71,7 +71,7 @@ }, { "name": "size", - "type": "'16x16' | '24x24' | '32x32' | '48x48' | '64x64' | '96x96' | '128x128' | number", + "type": "AvatarProps['size']", "default": null, "description": "Uniform size applied to every child `Avatar` (and the surplus avatar).", "required": false, @@ -80,7 +80,7 @@ }, { "name": "shape", - "type": "'circle' | 'rounded' | 'square'", + "type": "AvatarProps['shape']", "default": null, "description": "Uniform shape applied to every child `Avatar` (and the surplus avatar); a child's own `shape` wins when this is unset.", "required": false, @@ -133,6 +133,15 @@ "summary": "The `Avatar` component represents a person or entity as a compact image.", "component": "Avatar", "props": [ + { + "name": "as", + "type": "React.ElementType", + "default": null, + "description": "Element/component to render as. Defaults to `'a'` when `href` is set, else `'figure'`.", + "required": false, + "inherited": false, + "deprecated": false + }, { "name": "className", "type": "string", @@ -214,15 +223,6 @@ "inherited": false, "deprecated": false }, - { - "name": "as", - "type": "React.ElementType", - "default": null, - "description": "Element/component to render as. Defaults to `'a'` when `href` is set, else `'figure'`.", - "required": false, - "inherited": false, - "deprecated": false - }, { "name": "href", "type": "string", @@ -258,10 +258,29 @@ "required": false, "inherited": false, "deprecated": false + }, + { + "name": "style", + "type": "React.CSSProperties", + "default": null, + "description": "Inline styles, merged after the size style.", + "required": false, + "inherited": false, + "deprecated": false } ], - "extraProps": [], - "catchAll": "All standard HTML attributes and Bulma helper props", + "extraProps": [ + { + "name": "ref", + "type": "React.Ref", + "default": null, + "description": "Ref forwarded to the element `as` renders.", + "required": false, + "inherited": false, + "deprecated": false + } + ], + "catchAll": "All props of the element or component as renders and Bulma helper props", "types": [ { "name": "AvatarColor", diff --git a/bestax-mcp/data/components/Button.json b/bestax-mcp/data/components/Button.json index e1a379c6e..95336233d 100644 --- a/bestax-mcp/data/components/Button.json +++ b/bestax-mcp/data/components/Button.json @@ -110,6 +110,15 @@ "summary": "The `Button` component provides a flexible and highly customizable button for your Bulma React UI.", "component": null, "props": [ + { + "name": "as", + "type": "React.ElementType", + "default": "'button'", + "description": "Render as a `\n

Rendered element: {tag ?? '—'}

\n \n );\n}" } ], "accessibility": "- **Descriptive Text:** Use meaningful link text that describes the destination, not generic text like \"click here\".\n- **External Links:** When opening links in new tabs, consider informing users (e.g., with an icon or text like \"opens in new tab\").\n- **Focus States:** Links inherit browser focus styles. Customize with CSS if needed.\n- **Keyboard Navigation:** Links are naturally keyboard accessible via Tab and Enter keys.\n\n:::info\nFor navigation menus, consider using the `isActive` prop to indicate the current page.\n:::\n\n:::warning Links Are for Navigation, Buttons Are for Actions\nPer [Section 508](https://www.section508.gov/) and [eslint-plugin-jsx-a11y](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y) best practices, links (`
`) should navigate to a URL — not trigger an action via `onClick` alone. If your element performs an action (opening a modal, submitting data, toggling state, etc.) without navigating, use a [`Button`](./button.md) or [`LinkButton`](./linkbutton.md) instead. A `` is an anti-pattern that confuses screen readers and fails accessibility audits.\n:::", @@ -60,6 +64,15 @@ "summary": "The `Link` component renders a styled anchor (``) element with Bulma helper class integration.", "component": null, "props": [ + { + "name": "as", + "type": "React.ElementType", + "default": "'a'", + "description": "Render as a custom component (e.g. a router `Link`) instead of ``. Defaults to `'a'`.", + "required": false, + "inherited": false, + "deprecated": false + }, { "name": "className", "type": "string", @@ -98,15 +111,6 @@ "inherited": false, "deprecated": false }, - { - "name": "as", - "type": "React.ElementType", - "default": "'a'", - "description": "Render as a custom component (e.g. a router `Link`) instead of ``. Defaults to `'a'`.", - "required": false, - "inherited": false, - "deprecated": false - }, { "name": "children", "type": "React.ReactNode", @@ -119,34 +123,16 @@ ], "extraProps": [ { - "name": "href", - "type": "string", - "default": null, - "description": "The URL the link points to.", - "required": false, - "inherited": false, - "deprecated": false - }, - { - "name": "target", - "type": "'_self' | '_blank' | '_parent' | '_top'", - "default": null, - "description": "Where to open the linked document.", - "required": false, - "inherited": false, - "deprecated": false - }, - { - "name": "rel", - "type": "string", + "name": "ref", + "type": "React.Ref", "default": null, - "description": "Relationship between current and linked document.", + "description": "Ref forwarded to the element `as` renders.", "required": false, "inherited": false, "deprecated": false } ], - "catchAll": "All standard attributes and Bulma helper props", + "catchAll": "All props of the element or component as renders (default ) and Bulma helper props", "types": [] } ], diff --git a/bestax-mcp/data/components/LinkButton.json b/bestax-mcp/data/components/LinkButton.json index 50948f956..a0c3b7687 100644 --- a/bestax-mcp/data/components/LinkButton.json +++ b/bestax-mcp/data/components/LinkButton.json @@ -59,6 +59,15 @@ "summary": "The `LinkButton` component renders a `\n \n General\n \n Dashboard\n \n Customers\n \n \n \n \n );\n}" + }, { "title": "Compound (dot-notation) usage", "code": "\n General\n \n Dashboard\n Customers\n \n" @@ -123,11 +127,20 @@ "summary": "MenuItem supports `as` prop for custom link components, e.g., react-router-dom Link.", "component": null, "props": [ + { + "name": "as", + "type": "React.ElementType", + "default": "'a'", + "description": "Custom link component (e.g. `Link` from router).", + "required": false, + "inherited": false, + "deprecated": false + }, { "name": "className", "type": "string", "default": null, - "description": "Additional CSS classes.", + "description": "Additional CSS classes for the wrapping `
  • `.", "required": false, "inherited": false, "deprecated": false @@ -151,26 +164,72 @@ "deprecated": false }, { - "name": "href", + "name": "style", + "type": "React.CSSProperties", + "default": null, + "description": "Inline styles for the wrapping `
  • `.", + "required": false, + "inherited": false, + "deprecated": false + }, + { + "name": "id", "type": "string", "default": null, - "description": "Href for link items (if rendered as ``).", + "description": "`id` for the wrapping `
  • `.", "required": false, "inherited": false, "deprecated": false }, { - "name": "as", - "type": "React.ElementType", - "default": "'a'", - "description": "Custom link component (e.g. `Link` from router).", + "name": "title", + "type": "string", + "default": null, + "description": "`title` for the wrapping `
  • `.", + "required": false, + "inherited": false, + "deprecated": false + }, + { + "name": "role", + "type": "React.AriaRole", + "default": null, + "description": "ARIA role for the wrapping `
  • `.", + "required": false, + "inherited": false, + "deprecated": false + }, + { + "name": "tabIndex", + "type": "number", + "default": null, + "description": "Tab index for the wrapping `
  • `.", + "required": false, + "inherited": false, + "deprecated": false + }, + { + "name": "data-testid", + "type": "string", + "default": null, + "description": "Test id for the wrapping `
  • `.", "required": false, "inherited": false, "deprecated": false } ], - "extraProps": [], - "catchAll": "All standard
  • attributes and Bulma helper props", + "extraProps": [ + { + "name": "ref", + "type": "React.Ref", + "default": null, + "description": "Ref forwarded to the inner element `as` renders, not the wrapping `
  • `.", + "required": false, + "inherited": false, + "deprecated": false + } + ], + "catchAll": "All props of the element or component as renders (default ) and Bulma helper props", "types": [] } ], diff --git a/bestax-mcp/data/components/Navbar.json b/bestax-mcp/data/components/Navbar.json index 643bf1a25..2fbaa242b 100644 --- a/bestax-mcp/data/components/Navbar.json +++ b/bestax-mcp/data/components/Navbar.json @@ -220,19 +220,19 @@ "component": null, "props": [ { - "name": "className", - "type": "string", - "default": null, - "description": "Additional CSS classes.", + "name": "as", + "type": "React.ElementType", + "default": "'a'", + "description": "Render as a custom component (e.g., a router link).", "required": false, "inherited": false, "deprecated": false }, { - "name": "as", - "type": "React.ElementType", - "default": "'a'", - "description": "Render as a custom component (e.g., a router link).", + "name": "className", + "type": "string", + "default": null, + "description": "Additional CSS classes.", "required": false, "inherited": false, "deprecated": false @@ -276,8 +276,18 @@ "deprecated": false } ], - "extraProps": [], - "catchAll": "All standard attributes and Bulma helper props", + "extraProps": [ + { + "name": "ref", + "type": "React.Ref", + "default": null, + "description": "Ref forwarded to the element `as` renders.", + "required": false, + "inherited": false, + "deprecated": false + } + ], + "catchAll": "All props of the element or component as renders (default ) and Bulma helper props", "types": [] }, { @@ -286,19 +296,19 @@ "component": null, "props": [ { - "name": "className", - "type": "string", - "default": null, - "description": "Additional CSS classes.", + "name": "as", + "type": "React.ElementType", + "default": "'a'", + "description": "Render as a custom component (default: 'a').", "required": false, "inherited": false, "deprecated": false }, { - "name": "as", - "type": "React.ElementType", - "default": "'a'", - "description": "Render as a custom component (default: 'a').", + "name": "className", + "type": "string", + "default": null, + "description": "Additional CSS classes.", "required": false, "inherited": false, "deprecated": false @@ -345,15 +355,15 @@ "extraProps": [ { "name": "ref", - "type": "React.Ref", + "type": "React.Ref", "default": null, - "description": "Ref forwarded to the rendered link or button element.", + "description": "Ref forwarded to the element `as` renders.", "required": false, "inherited": false, "deprecated": false } ], - "catchAll": "All standard attributes and Bulma helper props", + "catchAll": "All props of the element or component as renders (default ) and Bulma helper props", "types": [] }, { diff --git a/bestax-mcp/data/components/Reveal.json b/bestax-mcp/data/components/Reveal.json index d6305de9a..d9e13ab84 100644 --- a/bestax-mcp/data/components/Reveal.json +++ b/bestax-mcp/data/components/Reveal.json @@ -39,6 +39,15 @@ "summary": "The `Reveal` component animates its content into view as it scrolls into the viewport, backed by `IntersectionObserver`.", "component": null, "props": [ + { + "name": "as", + "type": "React.ElementType", + "default": "'div'", + "description": "Element or component to render as. Default: 'div'. When `as` is a plain intrinsic tag (e.g. `'section'`), your `className`, `style`, and Bulma helper classes plus everything in `...rest` all land on that single element. When `as` is a component (e.g. `Section`, `Card`), scroll detection needs a real DOM node with a ref, so `Reveal` wraps it in an observed `div`: `className`/`style`/helper classes go on that wrapper `div`, while `...rest` (`id`, `aria-*`, `data-*`, event handlers) is forwarded to the inner component.", + "required": false, + "inherited": false, + "deprecated": false + }, { "name": "animation", "type": "'fade' | 'fade-up' | 'fade-down' | 'slide-left' | 'slide-right' | 'zoom' | 'flip'", @@ -84,15 +93,6 @@ "inherited": false, "deprecated": false }, - { - "name": "as", - "type": "React.ElementType", - "default": "'div'", - "description": "Element or component to render as. Default: 'div'. When `as` is a plain intrinsic tag (e.g. `'section'`), your `className`, `style`, and Bulma helper classes plus everything in `...rest` all land on that single element. When `as` is a component (e.g. `Section`, `Card`), scroll detection needs a real DOM node with a ref, so `Reveal` wraps it in an observed `div`: `className`/`style`/helper classes go on that wrapper `div`, while `...rest` (`id`, `aria-*`, `data-*`, event handlers) is forwarded to the inner component.", - "required": false, - "inherited": false, - "deprecated": false - }, { "name": "cascade", "type": "boolean", @@ -119,20 +119,28 @@ "required": false, "inherited": false, "deprecated": false - } - ], - "extraProps": [ + }, { "name": "className", "type": "string", "default": null, - "description": "Additional CSS classes.", + "description": "Additional CSS classes. Applied to the observed element (the wrapper `div` when `as` is a component).", + "required": false, + "inherited": false, + "deprecated": false + }, + { + "name": "style", + "type": "React.CSSProperties", + "default": null, + "description": "Inline styles, merged after the animation's own. Applied to the observed element.", "required": false, "inherited": false, "deprecated": false } ], - "catchAll": "All standard HTML attributes and Bulma helper props", + "extraProps": [], + "catchAll": "All props of the element or component as renders (default
    ) and Bulma helper props", "types": [] } ], diff --git a/bestax-mcp/data/skills.json b/bestax-mcp/data/skills.json index 7596191de..d9cbb7f3b 100644 --- a/bestax-mcp/data/skills.json +++ b/bestax-mcp/data/skills.json @@ -64,7 +64,7 @@ { "id": "layout-components", "file": "references/layout-components.md", - "bytes": 14687 + "bytes": 14737 } ], "examples": [ diff --git a/bulma-ui/jest.config.js b/bulma-ui/jest.config.js index f47f5a7e3..45ba41475 100644 --- a/bulma-ui/jest.config.js +++ b/bulma-ui/jest.config.js @@ -14,6 +14,9 @@ export default { 'src/**/*.{ts,tsx}', '!src/**/*.{test,spec}.{ts,tsx}', '!src/**/__tests__/**', + // Type-level assertions (#641). They are checked by `tsc --noEmit`, never + // run — and the JSX in them would otherwise instrument as uncovered lines. + '!src/**/__typetests__/**', '!src/**/*.stories.{ts,tsx}', '!src/index.ts', ], diff --git a/bulma-ui/rollup.config.js b/bulma-ui/rollup.config.js index 24fed25d3..da36e29f3 100644 --- a/bulma-ui/rollup.config.js +++ b/bulma-ui/rollup.config.js @@ -57,7 +57,11 @@ export default commandLineArgs => { declaration: true, declarationDir: 'dist/types', rootDir: 'src', - exclude: ['**/__tests__/**/*', '**/*.test.tsx'], + exclude: [ + '**/__tests__/**/*', + '**/*.test.tsx', + '**/__typetests__/**/*', + ], }), isVisualizerEnabled && visualizer({ diff --git a/bulma-ui/src/__typetests__/polymorphic.tsx b/bulma-ui/src/__typetests__/polymorphic.tsx new file mode 100644 index 000000000..c98671ac3 --- /dev/null +++ b/bulma-ui/src/__typetests__/polymorphic.tsx @@ -0,0 +1,118 @@ +/** + * Type-level tests for the polymorphic `as` contract (#641). + * + * These assert types, not behaviour, so they deliberately live OUTSIDE + * `__tests__/`: `bulma-ui/tsconfig.json` excludes that directory and every + * `*.test.tsx`, and ts-jest runs transpile-only (the repo sets + * `isolatedModules`), so an `@ts-expect-error` in a test file is checked by + * nothing. Here `tsc --noEmit` reads the file — which means `pnpm typecheck` + * and the React 18/19 matrix both enforce it, and an `@ts-expect-error` that + * stops being an error fails the build as TS2578. + * + * Nothing renders these; jest's testMatch does not reach this directory and + * `collectCoverageFrom` excludes it. + */ +import React from 'react'; +import { Avatar } from '../components/Avatar'; +import { Menu } from '../components/Menu'; +import { Navbar } from '../components/Navbar'; +import { Reveal } from '../components/Reveal'; +import { Button } from '../elements/Button'; +import { Link } from '../elements/Link'; +import { LinkButton } from '../elements/LinkButton'; + +/** A router-style link, standing in for `react-router`'s `Link`. */ +const RouterLink = React.forwardRef< + HTMLAnchorElement, + { to: string; children?: React.ReactNode } +>(function RouterLink({ to, children }, ref) { + return ( + + {children} + + ); +}); + +// -------------------------------------------------------------------------- +// Correct code must compile. Every one of these was rejected before #641, or +// only compiled because an index signature turned excess-property checking off. +// -------------------------------------------------------------------------- + +export const accepted = ( + <> + {/* The ref follows `as`, including to an element the component never mentions. */} + + + {size &&

    {size}

    } + + ); +}; + +export const ForwardedRef: Story = { + render: () => , + name: 'Forwarded ref (measure the root)', +}; diff --git a/bulma-ui/src/components/Avatar.tsx b/bulma-ui/src/components/Avatar.tsx index eb0a15ce4..43bf56f7b 100644 --- a/bulma-ui/src/components/Avatar.tsx +++ b/bulma-ui/src/components/Avatar.tsx @@ -1,6 +1,7 @@ -import React, { useEffect, useRef, useState } from 'react'; +import React, { forwardRef, useEffect, useRef, useState } from 'react'; import { classNames, usePrefixedClassNames } from '../helpers/classNames'; import { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses'; +import type { PolymorphicComponent } from '../helpers/polymorphic'; const avatarColors = [ 'primary', @@ -87,12 +88,10 @@ function DefaultAvatarIcon() { } /** - * Props for the Avatar component. + * The Avatar component's own props — everything it adds on top of the + * attributes of whatever element `as` renders. */ -export interface AvatarProps - extends - Omit, 'color'>, - Omit { +export interface AvatarOwnProps extends Omit { /** Additional CSS classes to apply. */ className?: string; /** Image URL. On load error (or if absent), falls back to initials, then `icon`. */ @@ -111,8 +110,6 @@ export interface AvatarProps shape?: AvatarShape; /** Background color for initials/icon avatars (else auto-derived from `name`). */ color?: AvatarColor; - /** Element/component to render as. Defaults to `'a'` when `href` is set, else `'figure'`. */ - as?: React.ElementType; /** When set, renders the avatar as a link. */ href?: string; /** Anchor target — forwarded only when rendering a link (an `a` or a custom `as` component). */ @@ -121,13 +118,41 @@ export interface AvatarProps rel?: string; /** Extra props forwarded to the underlying `` (e.g. `loading`, `crossOrigin`); its `onError` is chained before the fallback fires. */ imageProps?: React.ImgHTMLAttributes; + /** Inline styles, merged after the size style. */ + style?: React.CSSProperties; } +/** + * Props for the Avatar component. The DOM attributes and the `ref` both follow + * `as`. + * + * `href`, `target` and `rel` stay Avatar's own props rather than being derived: + * they are what *chooses* the element when `as` is absent (an `` with an + * `href`, a `
    ` without one), so they have to be accepted before `as` is + * known. The type parameter defaults to `React.ElementType` for the same + * reason — Avatar has no single default element to name. + * + * @extraProp {React.Ref} [ref] - Ref forwarded to the element `as` renders. + */ +export type AvatarProps = + AvatarOwnProps & + Omit, keyof AvatarOwnProps | 'as'> & { + /** Element/component to render as. Defaults to `'a'` when `href` is set, else `'figure'`. */ + as?: T; + }; + +/** + * The shape the implementation destructures. The public contract is the generic + * `AvatarProps` above — the body cannot see through `T`. + */ +type AvatarImplProps = AvatarOwnProps & { as?: React.ElementType }; + /** * The `Avatar` component represents a person or entity as a compact image. * * @function * @param {AvatarProps} props - Props for the Avatar component. + * @param {React.Ref} ref - Forwarded ref to the element `as` renders. * @returns {JSX.Element} The rendered avatar element. * * @example @@ -135,24 +160,28 @@ export interface AvatarProps * @example * */ -export const Avatar: React.FC = ({ - className, - src, - alt, - name, - initials, - icon, - size, - shape = 'circle', - color, - as, - href, - target, - rel, - imageProps, - style, - ...props -}) => { +export const Avatar = forwardRef(function Avatar( + avatarProps: AvatarProps, + ref: React.Ref +) { + const { + className, + src, + alt, + name, + initials, + icon, + size, + shape = 'circle', + color, + as, + href, + target, + rel, + imageProps, + style, + ...props + } = avatarProps as AvatarImplProps; // Tracks the src that failed to load. A src change clears the latch during // render (React's "reset state when props change" pattern) so a previously // failed src is retried when switched back to. The img is additionally @@ -254,6 +283,7 @@ export const Avatar: React.FC = ({ return ( = ({ {showDefaultIcon && } ); -}; +}) as PolymorphicComponent; Avatar.displayName = 'Avatar'; diff --git a/bulma-ui/src/components/Menu.stories.tsx b/bulma-ui/src/components/Menu.stories.tsx index 1f5be06a4..cc6de34ba 100644 --- a/bulma-ui/src/components/Menu.stories.tsx +++ b/bulma-ui/src/components/Menu.stories.tsx @@ -1,5 +1,7 @@ +import React from 'react'; import { Meta, StoryObj } from '@storybook/react-vite'; import { Menu } from './Menu'; +import { Button } from '../elements/Button'; const meta: Meta = { title: 'Components/Menu', @@ -60,3 +62,31 @@ export const CompoundUsage: Story = { ), }; + +// Forwarded ref — Menu.Item's ref reaches the inner element `as` renders, +// not the wrapping
  • , because `as` is what names it. +const MenuForwardedRefDemo = () => { + const itemRef = React.useRef(null); + + return ( + <> + + + General + + Dashboard + + Customers + + + + + ); +}; + +export const ForwardedRef: Story = { + render: () => , + name: 'Forwarded ref (inner element, not the `
  • `)', +}; diff --git a/bulma-ui/src/components/Menu.tsx b/bulma-ui/src/components/Menu.tsx index b7ee48e05..fc217ac8e 100644 --- a/bulma-ui/src/components/Menu.tsx +++ b/bulma-ui/src/components/Menu.tsx @@ -1,7 +1,8 @@ -import React, { createContext, useContext } from 'react'; +import React, { createContext, forwardRef, useContext } from 'react'; import { classNames, usePrefixedClassNames } from '../helpers/classNames'; import { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses'; import { withSubComponents } from '../helpers/withSubComponents'; +import type { PolymorphicComponent } from '../helpers/polymorphic'; // Context to track MenuList nesting level const MenuListLevelContext = createContext(0); @@ -131,50 +132,85 @@ export const MenuList: React.FC = ({ }; /** - * Props for the MenuItem component. + * The MenuItem component's own props. + * + * A menu item is two elements: a wrapping `
  • ` and, inside it, the element + * `as` names. The props here are the ones the `
  • ` consumes; everything else + * follows `as` onto the inner element. */ -export interface MenuItemProps - extends - Omit, keyof BulmaClassesProps>, - BulmaClassesProps { - /** Additional CSS classes. */ +export interface MenuItemOwnProps extends BulmaClassesProps { + /** Additional CSS classes for the wrapping `
  • `. */ className?: string; /** Item content and optional nested MenuList. */ children: React.ReactNode; /** Highlight item as active. */ active?: boolean; - /** Href for link items (if rendered as ``). */ - href?: string; - /** Custom link component (e.g. `Link` from router). */ - as?: React.ElementType; - [key: string]: unknown; + /** Inline styles for the wrapping `
  • `. */ + style?: React.CSSProperties; + /** `id` for the wrapping `
  • `. */ + id?: string; + /** `title` for the wrapping `
  • `. */ + title?: string; + /** ARIA role for the wrapping `
  • `. */ + role?: React.AriaRole; + /** Tab index for the wrapping `
  • `. */ + tabIndex?: number; + /** Test id for the wrapping `
  • `. */ + 'data-testid'?: string; } +/** + * Props for the MenuItem component. Everything the `
  • ` does not consume + * follows `as` onto the inner element: with the default `'a'` that means `href` + * and the other anchor attributes, and with `as={Link}` it means that + * component's own props. + * + * @extraProp {React.Ref} [ref] - Ref forwarded to the inner element `as` renders, not the wrapping `
  • `. + */ +export type MenuItemProps = + MenuItemOwnProps & + Omit, keyof MenuItemOwnProps | 'as'> & { + /** Custom link component (e.g. `Link` from router). */ + as?: T; + }; + +/** + * The shape the implementation destructures. The public contract is the generic + * `MenuItemProps` above — the body cannot see through `T`. + */ +type MenuItemImplProps = MenuItemOwnProps & { as?: React.ElementType }; + /** * MenuItem supports `as` prop for custom link components, e.g., react-router-dom Link. * * @function * @param {MenuItemProps} props - Props for the MenuItem component. + * @param {React.Ref} ref - Forwarded ref to the inner element `as` renders. * @returns {JSX.Element} The rendered menu item. */ -export const MenuItem: React.FC = ({ - className, - children, - active, - href, - as: Component = 'a', - 'data-testid': testId, - ...rest -}) => { - const { bulmaHelperClasses, rest: bulmaRest } = useBulmaClasses(rest); +export const MenuItem = forwardRef(function MenuItem( + itemProps: MenuItemProps, + ref: React.Ref +) { + const { + className, + children, + active, + as: Component = 'a', + 'data-testid': testId, + style, + id, + title, + role, + tabIndex, + ...rest + } = itemProps as MenuItemImplProps; + const { bulmaHelperClasses, rest: linkProps } = useBulmaClasses(rest); const itemClass = classNames( { [usePrefixedClassNames('is-active')]: active }, bulmaHelperClasses ); - // Standard
  • props - const { style, id, title, role, tabIndex, ...linkProps } = bulmaRest; - // Split children into label and nested MenuList(s) const labelChildren: React.ReactNode[] = []; const nestedMenuLists: React.ReactNode[] = []; @@ -186,31 +222,25 @@ export const MenuItem: React.FC = ({ } }); - // href/to should go to the link component - if (Component === 'a' && href) { - (linkProps as Record).href = href; - } - if (Object.prototype.hasOwnProperty.call(rest, 'to')) { - (linkProps as Record).to = rest.to; - } - return (
  • - + {labelChildren} {nestedMenuLists}
  • ); -}; +}) as PolymorphicComponent; + +MenuItem.displayName = 'MenuItem'; // Attach static subcomponents export const Menu = withSubComponents( diff --git a/bulma-ui/src/components/Navbar.stories.tsx b/bulma-ui/src/components/Navbar.stories.tsx index a14c06c5e..e83620e64 100644 --- a/bulma-ui/src/components/Navbar.stories.tsx +++ b/bulma-ui/src/components/Navbar.stories.tsx @@ -348,6 +348,7 @@ const ForwardedRefNavbar = () => { const navRef = useRef(null); const burgerRef = useRef(null); const linkRef = useRef(null); + const itemRef = useRef(null); const dropdownRef = useRef(null); const [height, setHeight] = useState(null); const [burgerLabel, setBurgerLabel] = useState(null); @@ -367,7 +368,9 @@ const ForwardedRefNavbar = () => { - Home + + Home + More @@ -397,6 +400,9 @@ const ForwardedRefNavbar = () => { > Read the burger from its ref + diff --git a/bulma-ui/src/components/Navbar.tsx b/bulma-ui/src/components/Navbar.tsx index 7ea1a8221..caad00523 100644 --- a/bulma-ui/src/components/Navbar.tsx +++ b/bulma-ui/src/components/Navbar.tsx @@ -1,6 +1,7 @@ import React, { forwardRef, useContext, useEffect, useState } from 'react'; import { classNames, usePrefixedClassNames } from '../helpers/classNames'; import { withSubComponents } from '../helpers/withSubComponents'; +import type { PolymorphicComponent } from '../helpers/polymorphic'; import { useBulmaClasses, BulmaClassesProps, @@ -163,16 +164,15 @@ export const NavbarBrand: React.FC = ({ }; /** - * Props for the NavbarItem component. + * The NavbarItem component's own props — everything it adds on top of the + * attributes of whatever element `as` renders. */ -export interface NavbarItemProps - extends - Omit, 'color'>, - Omit { +export interface NavbarItemOwnProps extends Omit< + BulmaClassesProps, + 'color' | 'backgroundColor' +> { /** Additional CSS classes. */ className?: string; - /** Render as a custom component (e.g., a router link). */ - as?: React.ElementType; /** Whether the item is active. */ active?: boolean; /** Text color for the item. */ @@ -181,26 +181,49 @@ export interface NavbarItemProps bgColor?: (typeof validColors)[number] | 'inherit' | 'current'; /** Navbar item content. */ children?: React.ReactNode; - // Allow router props like `to` when rendering via `as` (matches MenuItemProps) - [key: string]: unknown; } +/** + * Props for the NavbarItem component. The DOM attributes and the `ref` both + * follow `as`: rendering as a router link accepts that component's props (`to` + * and friends) by inference, and `as="span"` rejects `href`. + * + * @extraProp {React.Ref} [ref] - Ref forwarded to the element `as` renders. + */ +export type NavbarItemProps = + NavbarItemOwnProps & + Omit, keyof NavbarItemOwnProps | 'as'> & { + /** Render as a custom component (e.g., a router link). */ + as?: T; + }; + +/** + * The shape the implementation destructures. The public contract is the generic + * `NavbarItemProps` above — the body cannot see through `T`. + */ +type NavbarItemImplProps = NavbarItemOwnProps & { as?: React.ElementType }; + /** * Navigation links, buttons, or custom content * * @function * @param {NavbarItemProps} props - Props for the NavbarItem component. + * @param {React.Ref} ref - Forwarded ref to the element `as` renders. * @returns {JSX.Element} The rendered item. */ -export const NavbarItem: React.FC = ({ - className, - as: Component = 'a', - active, - textColor, - bgColor, - children, - ...props -}) => { +export const NavbarItem = forwardRef(function NavbarItem( + itemProps: NavbarItemProps, + ref: React.Ref +) { + const { + className, + as: Component = 'a', + active, + textColor, + bgColor, + children, + ...props + } = itemProps as NavbarItemImplProps; const { bulmaHelperClasses, rest } = useBulmaClasses({ color: textColor, backgroundColor: bgColor, @@ -209,6 +232,7 @@ export const NavbarItem: React.FC = ({ return ( = ({ {children} ); -}; +}) as PolymorphicComponent; + +NavbarItem.displayName = 'NavbarItem'; /** * Props for the NavbarBurger component. @@ -417,17 +443,15 @@ export const NavbarEnd: React.FC = ({ }; /** - * Props for the NavbarLink component. - * @extraProp {React.Ref} [ref] - Ref forwarded to the rendered link or button element. + * The NavbarLink component's own props — everything it adds on top of the + * attributes of whatever element `as` renders. */ -export interface NavbarLinkProps - extends - Omit, 'color'>, - Omit { +export interface NavbarLinkOwnProps extends Omit< + BulmaClassesProps, + 'color' | 'backgroundColor' +> { /** Additional CSS classes. */ className?: string; - /** Render as a custom component (default: 'a'). */ - as?: React.ElementType; /** Remove the dropdown arrow indicator. */ arrowless?: boolean; /** Text color. */ @@ -438,19 +462,45 @@ export interface NavbarLinkProps children?: React.ReactNode; } +/** + * Props for the NavbarLink component. The DOM attributes and the `ref` both + * follow `as`: `as="button"` accepts the button attributes and a button ref, + * and `as="span"` rejects `href`, `target` and `rel`. + * + * @extraProp {React.Ref} [ref] - Ref forwarded to the element `as` renders. + */ +export type NavbarLinkProps = + NavbarLinkOwnProps & + Omit, keyof NavbarLinkOwnProps | 'as'> & { + /** Render as a custom component (default: 'a'). */ + as?: T; + }; + +/** + * The shape the implementation destructures. The public contract is the generic + * `NavbarLinkProps` above — the body cannot see through `T`, so it names the + * handful of DOM props it actually reads back off `rest`. + */ +type NavbarLinkImplProps = NavbarLinkOwnProps & { + as?: React.ElementType; + href?: string; + onKeyDown?: React.KeyboardEventHandler; + onClick?: React.MouseEventHandler; +}; + /** * Dropdown trigger with arrow indicator (use as first child of `Navbar.Dropdown`) * * @function * @param {NavbarLinkProps} props - Props for the NavbarLink component. - * @param {React.Ref} ref - Forwarded ref to the rendered link or button element. + * @param {React.Ref} ref - Forwarded ref to the element `as` renders. * @returns {JSX.Element} The rendered navbar link. */ -export const NavbarLink = forwardRef< - HTMLAnchorElement | HTMLButtonElement, - NavbarLinkProps ->(function NavbarLink( - { +export const NavbarLink = forwardRef(function NavbarLink( + linkProps: NavbarLinkProps, + ref: React.Ref +) { + const { className, as: Component = 'a', arrowless, @@ -458,9 +508,7 @@ export const NavbarLink = forwardRef< bgColor, children, ...props - }, - ref -) { + } = linkProps as NavbarLinkImplProps; const { bulmaHelperClasses, rest } = useBulmaClasses({ color: textColor, backgroundColor: bgColor, @@ -468,7 +516,7 @@ export const NavbarLink = forwardRef< }); const dropdownContext = useContext(NavbarDropdownContext); - const hasHref = (rest as { href?: string }).href !== undefined; + const hasHref = rest.href !== undefined; const isNativeInteractive = Component === 'button' || hasHref; const handleKeyDown = (e: React.KeyboardEvent) => { @@ -519,7 +567,7 @@ export const NavbarLink = forwardRef< {children} ); -}); +}) as PolymorphicComponent; NavbarLink.displayName = 'NavbarLink'; diff --git a/bulma-ui/src/components/Reveal.tsx b/bulma-ui/src/components/Reveal.tsx index ec80c03eb..809ef309e 100644 --- a/bulma-ui/src/components/Reveal.tsx +++ b/bulma-ui/src/components/Reveal.tsx @@ -11,6 +11,7 @@ import { usePrefixedClassNames, } from '../helpers/classNames'; import { useClassPrefix } from '../helpers/Config'; +import type { PolymorphicComponentWithoutRef } from '../helpers/polymorphic'; import { useBulmaClasses, BulmaClassesProps } from '../helpers/useBulmaClasses'; /** @@ -26,11 +27,10 @@ export type RevealAnimation = | 'flip'; /** - * Props for the Reveal component. - * @extraProp {string} [className] - Additional CSS classes. + * The Reveal component's own props — everything it adds on top of the + * attributes of whatever element `as` renders. */ -export interface RevealProps - extends Omit, 'color'>, BulmaClassesProps { +export interface RevealOwnProps extends BulmaClassesProps { /** Animation style applied when the element enters the viewport. */ animation?: RevealAnimation; /** Delay in milliseconds before the animation starts. Default: 0. */ @@ -41,16 +41,38 @@ export interface RevealProps threshold?: number; /** Animate only the first time the element enters the viewport. If `false`, it re-animates on every entry/exit. */ once?: boolean; - /** Element or component to render as. Default: 'div'. When `as` is a plain intrinsic tag (e.g. `'section'`), your `className`, `style`, and Bulma helper classes plus everything in `...rest` all land on that single element. When `as` is a component (e.g. `Section`, `Card`), scroll detection needs a real DOM node with a ref, so `Reveal` wraps it in an observed `div`: `className`/`style`/helper classes go on that wrapper `div`, while `...rest` (`id`, `aria-*`, `data-*`, event handlers) is forwarded to the inner component. */ - as?: React.ElementType; /** Stagger direct children with an incrementing delay instead of animating this element as a single block. */ cascade?: boolean; /** Milliseconds added to each successive child's delay when `cascade` is set. Default: 80. */ cascadeInterval?: number; /** Content to reveal. */ children?: React.ReactNode; + /** Additional CSS classes. Applied to the observed element (the wrapper `div` when `as` is a component). */ + className?: string; + /** Inline styles, merged after the animation's own. Applied to the observed element. */ + style?: React.CSSProperties; } +/** + * Props for the Reveal component. The DOM attributes follow `as`. + * + * Reveal forwards no `ref`: it owns the node it observes for scroll + * intersection, and when `as` is a component that node is a wrapper `div` + * rather than the element `as` names — so a ref derived from `as` would point + * at the wrong thing. + */ +export type RevealProps = RevealOwnProps & + Omit, keyof RevealOwnProps | 'as'> & { + /** Element or component to render as. Default: 'div'. When `as` is a plain intrinsic tag (e.g. `'section'`), your `className`, `style`, and Bulma helper classes plus everything in `...rest` all land on that single element. When `as` is a component (e.g. `Section`, `Card`), scroll detection needs a real DOM node with a ref, so `Reveal` wraps it in an observed `div`: `className`/`style`/helper classes go on that wrapper `div`, while `...rest` (`id`, `aria-*`, `data-*`, event handlers) is forwarded to the inner component. */ + as?: T; + }; + +/** + * The shape the implementation destructures. The public contract is the generic + * `RevealProps` above — the body cannot see through `T`. + */ +type RevealImplProps = RevealOwnProps & { as?: React.ElementType }; + /** * Detects the user's `prefers-reduced-motion` preference. Always `false` on * the server and on the very first client render, so SSR output and the @@ -101,20 +123,21 @@ function usePrefersReducedMotion(): boolean { * ))} * */ -export const Reveal: React.FC = ({ - animation = 'fade-up', - delay = 0, - duration = 600, - threshold = 0.15, - once = true, - as: Component = 'div', - cascade = false, - cascadeInterval = 80, - className, - style, - children, - ...props -}) => { +export const Reveal = function Reveal(revealProps: RevealProps) { + const { + animation = 'fade-up', + delay = 0, + duration = 600, + threshold = 0.15, + once = true, + as: Component = 'div', + cascade = false, + cascadeInterval = 80, + className, + style, + children, + ...props + } = revealProps as RevealImplProps; const { bulmaHelperClasses, rest } = useBulmaClasses(props); const classPrefix = useClassPrefix(); const prefersReducedMotion = usePrefersReducedMotion(); @@ -245,6 +268,8 @@ export const Reveal: React.FC = ({ {content}
    ); -}; +} as PolymorphicComponentWithoutRef; + +Reveal.displayName = 'Reveal'; export default Reveal; diff --git a/bulma-ui/src/components/__tests__/Avatar.test.tsx b/bulma-ui/src/components/__tests__/Avatar.test.tsx index ea5e60365..6c34f8b74 100644 --- a/bulma-ui/src/components/__tests__/Avatar.test.tsx +++ b/bulma-ui/src/components/__tests__/Avatar.test.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { createRef } from 'react'; import { render, screen, fireEvent } from '@testing-library/react'; import { Avatar } from '../Avatar'; import { ConfigProvider } from '../../helpers/Config'; @@ -341,3 +341,20 @@ describe('Avatar', () => { expect(avatar).not.toHaveClass('avatar'); }); }); + +describe('Ref forwarding', () => { + // Avatar gained ref forwarding with #641. The ref lands on the root element, + // which `as` names — not on the inner . + it('forwards ref to the root
    by default', () => { + const ref = createRef(); + render(); + expect(ref.current).toBe(screen.getByTestId('avatar')); + expect(ref.current?.tagName).toBe('FIGURE'); + }); + + it('forwards ref to the an href selects', () => { + const ref = createRef(); + render(); + expect(ref.current).toBeInstanceOf(HTMLAnchorElement); + }); +}); diff --git a/bulma-ui/src/components/__tests__/Menu.test.tsx b/bulma-ui/src/components/__tests__/Menu.test.tsx index 3fac257dd..fe30eef4c 100644 --- a/bulma-ui/src/components/__tests__/Menu.test.tsx +++ b/bulma-ui/src/components/__tests__/Menu.test.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { createRef } from 'react'; import { render, screen } from '@testing-library/react'; import { Menu, MenuLabel, MenuList, MenuItem } from '../Menu'; import { ConfigProvider } from '../../helpers/Config'; @@ -264,3 +264,36 @@ describe('Compound components', () => { expect(container.querySelectorAll('.menu-list li')).toHaveLength(2); }); }); + +describe('Ref forwarding', () => { + // Menu.Item gained ref forwarding with #641. The ref goes to the INNER + // element `as` renders, not the wrapping
  • : `as` names the inner one. + it('forwards ref to the inner , not the wrapping
  • ', () => { + const ref = createRef(); + render( + + + + Foo + + + + ); + expect(ref.current).toBeInstanceOf(HTMLAnchorElement); + expect(ref.current).toBe(screen.getByTestId('item-li').querySelector('a')); + }); + + it('forwards ref to whatever as renders', () => { + const ref = createRef(); + render( + + + + Static + + + + ); + expect(ref.current).toBeInstanceOf(HTMLSpanElement); + }); +}); diff --git a/bulma-ui/src/components/__tests__/Navbar.test.tsx b/bulma-ui/src/components/__tests__/Navbar.test.tsx index 3d309b342..a9849c17e 100644 --- a/bulma-ui/src/components/__tests__/Navbar.test.tsx +++ b/bulma-ui/src/components/__tests__/Navbar.test.tsx @@ -753,6 +753,25 @@ describe('Navbar.Link', () => { ); expect(ref.current).toBeInstanceOf(HTMLButtonElement); }); + + // Navbar.Item gained ref forwarding with #641: the polymorphic contract is + // props AND ref following `as`, and it had neither. + it('forwards Navbar.Item ref to the rendered element by default', () => { + const ref = createRef(); + render(Home); + expect(ref.current).toBeInstanceOf(HTMLAnchorElement); + expect(ref.current).toBe(screen.getByText('Home')); + }); + + it('forwards Navbar.Item ref to whatever as renders', () => { + const ref = createRef(); + render( + + Static + + ); + expect(ref.current).toBeInstanceOf(HTMLSpanElement); + }); }); describe('Compound components', () => { diff --git a/bulma-ui/src/elements/Button.tsx b/bulma-ui/src/elements/Button.tsx index e4f12e8b7..18b9aaabe 100644 --- a/bulma-ui/src/elements/Button.tsx +++ b/bulma-ui/src/elements/Button.tsx @@ -1,5 +1,6 @@ import React, { forwardRef } from 'react'; import { classNames, usePrefixedClassNames } from '../helpers/classNames'; +import type { PolymorphicComponent } from '../helpers/polymorphic'; import { useBulmaClasses, BulmaClassesProps, @@ -7,13 +8,13 @@ import { } from '../helpers/useBulmaClasses'; /** - * Props for the Button component. - * @extraProp {React.Ref} [ref] - Ref forwarded to the rendered button or anchor element. + * The Button component's own props — everything it adds on top of the + * attributes of whatever element `as` renders. */ -export interface ButtonProps - extends - Omit, 'color' | 'onClick'>, - Omit { +export interface ButtonOwnProps extends Omit< + BulmaClassesProps, + 'color' | 'backgroundColor' | 'size' +> { /** Bulma color variant for the button. `ghost` renders a link-like button; `text` renders a minimal text-only button. */ color?: | 'primary' @@ -60,21 +61,38 @@ export interface ButtonProps textColor?: (typeof validColors)[number] | 'inherit' | 'current'; /** Background color helper. */ bgColor?: (typeof validColors)[number] | 'inherit' | 'current'; - /** Render as a ` ); -}); +}) as PolymorphicComponent; Button.displayName = 'Button'; diff --git a/bulma-ui/src/elements/Link.stories.tsx b/bulma-ui/src/elements/Link.stories.tsx index 0c6928eba..e96c06c20 100644 --- a/bulma-ui/src/elements/Link.stories.tsx +++ b/bulma-ui/src/elements/Link.stories.tsx @@ -1,6 +1,7 @@ import React from 'react'; import { Meta, StoryObj } from '@storybook/react-vite'; import { Link } from './Link'; +import { Button } from './Button'; const meta: Meta = { title: 'Elements/Link', @@ -207,3 +208,24 @@ export const PolymorphicAs: Story = { ), name: 'Polymorphic `as` (Router Link)', }; + +// Forwarded ref — reach the DOM node the `as` prop selected +const LinkForwardedRefDemo = () => { + const linkRef = React.useRef(null); + + return ( + <> + + + I receive focus + + + ); +}; + +export const ForwardedRef: Story = { + render: () => , + name: 'Forwarded ref (programmatic focus)', +}; diff --git a/bulma-ui/src/elements/Link.tsx b/bulma-ui/src/elements/Link.tsx index 018e471cf..dd3ddd67d 100644 --- a/bulma-ui/src/elements/Link.tsx +++ b/bulma-ui/src/elements/Link.tsx @@ -1,5 +1,6 @@ -import React from 'react'; +import React, { forwardRef } from 'react'; import { classNames, usePrefixedClassNames } from '../helpers/classNames'; +import type { PolymorphicComponent } from '../helpers/polymorphic'; import { useBulmaClasses, BulmaClassesProps, @@ -7,15 +8,13 @@ import { } from '../helpers/useBulmaClasses'; /** - * Props for the Link component. - * @extraProp {string} [href] - The URL the link points to. - * @extraProp {'_self' | '_blank' | '_parent' | '_top'} [target] - Where to open the linked document. - * @extraProp {string} [rel] - Relationship between current and linked document. + * The Link component's own props — everything it adds on top of the attributes + * of whatever element `as` renders. */ -export interface LinkProps - extends - React.AnchorHTMLAttributes, - Omit { +export interface LinkOwnProps extends Omit< + BulmaClassesProps, + 'color' | 'backgroundColor' +> { /** Additional CSS classes to apply. */ className?: string; /** Text color helper. */ @@ -24,29 +23,52 @@ export interface LinkProps bgColor?: (typeof validColors)[number] | 'inherit' | 'current'; /** Whether the link appears active. */ isActive?: boolean; - /** Render as a custom component (e.g. a router `Link`) instead of ``. Defaults to `'a'`. */ - as?: React.ElementType; /** Content to render inside the link. */ children?: React.ReactNode; } +/** + * Props for the Link component. The DOM attributes and the `ref` both follow + * `as`: with the default `'a'` the anchor attributes (`href`, `target`, `rel`) + * are accepted, with `as="span"` they are not. + * + * @extraProp {React.Ref} [ref] - Ref forwarded to the element `as` renders. + */ +export type LinkProps = LinkOwnProps & + Omit, keyof LinkOwnProps | 'as'> & { + /** Render as a custom component (e.g. a router `Link`) instead of ``. Defaults to `'a'`. */ + as?: T; + }; + +/** + * The shape the implementation destructures. The public contract is the generic + * `LinkProps` above — the body cannot see through `T`, so it reads the widest + * form of the props it actually touches. + */ +type LinkImplProps = LinkOwnProps & { as?: React.ElementType }; + /** * The `Link` component renders a styled anchor (``) element with Bulma helper class integration. * * @function * @param {LinkProps} props - Props for the Link component. - * @returns {JSX.Element} The rendered anchor element. + * @param {React.Ref} ref - Forwarded ref to the element `as` renders. + * @returns {JSX.Element} The rendered anchor, or whatever `as` names. * @see {@link https://bulma.io/documentation/elements/content/ | Bulma Content documentation} */ -export const Link: React.FC = ({ - className, - textColor, - bgColor, - isActive, - as: Component = 'a', - children, - ...props -}) => { +export const Link = forwardRef(function Link( + linkProps: LinkProps, + ref: React.Ref +) { + const { + className, + textColor, + bgColor, + isActive, + as: Component = 'a', + children, + ...props + } = linkProps as LinkImplProps; /** * Generates Bulma helper classes and separates out remaining props. */ @@ -62,8 +84,10 @@ export const Link: React.FC = ({ const linkClasses = classNames(bulmaClasses, bulmaHelperClasses, className); return ( - + {children} ); -}; +}) as PolymorphicComponent; + +Link.displayName = 'Link'; diff --git a/bulma-ui/src/elements/LinkButton.tsx b/bulma-ui/src/elements/LinkButton.tsx index f75cfefd9..375241609 100644 --- a/bulma-ui/src/elements/LinkButton.tsx +++ b/bulma-ui/src/elements/LinkButton.tsx @@ -1,12 +1,14 @@ -import { forwardRef } from 'react'; -import { Button, ButtonProps } from './Button'; +import React, { forwardRef } from 'react'; +import { Button, ButtonOwnProps } from './Button'; import { classNames, usePrefixedClassNames } from '../helpers/classNames'; +import type { PolymorphicComponent } from '../helpers/polymorphic'; /** - * Props for the LinkButton component. + * The LinkButton component's own props — everything it adds on top of the + * attributes of whatever element `as` renders. */ -export interface LinkButtonProps extends Omit< - ButtonProps, +export interface LinkButtonOwnProps extends Omit< + ButtonOwnProps, 'color' | 'isOutlined' | 'isInverted' | 'isLight' > { /** Display mode. `text` has no underline and highlights its background on hover; `ghost` uses the default text color and underlines on hover; `underline` drops the button chrome entirely (transparent background and border) and underlines on hover or focus. */ @@ -25,12 +27,28 @@ export interface LinkButtonProps extends Omit< | 'black'; } +/** + * Props for the LinkButton component. The DOM attributes and the `ref` both + * follow `as`, exactly as they do on `Button`. + * + * @extraProp {React.Ref} [ref] - Ref forwarded to the element `as` renders. + */ +export type LinkButtonProps = + LinkButtonOwnProps & + Omit, keyof LinkButtonOwnProps | 'as'> & { + /** + * Render as a ` diff --git a/bulma-ui/src/elements/__tests__/Link.test.tsx b/bulma-ui/src/elements/__tests__/Link.test.tsx index 9a8e269aa..05798696b 100644 --- a/bulma-ui/src/elements/__tests__/Link.test.tsx +++ b/bulma-ui/src/elements/__tests__/Link.test.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { createRef } from 'react'; import { render, screen } from '@testing-library/react'; import { Link } from '../Link'; import { ConfigProvider } from '../../helpers/Config'; @@ -210,3 +210,27 @@ describe('Link Component', () => { }); }); }); + +describe('Ref forwarding', () => { + // Link gained ref forwarding with #641, alongside props that follow `as`. + it('forwards ref to the rendered by default', () => { + const ref = createRef(); + render( + + Home + + ); + expect(ref.current).toBeInstanceOf(HTMLAnchorElement); + expect(ref.current).toBe(screen.getByRole('link')); + }); + + it('forwards ref to whatever as renders', () => { + const ref = createRef(); + render( + + Static + + ); + expect(ref.current).toBeInstanceOf(HTMLSpanElement); + }); +}); diff --git a/bulma-ui/src/helpers/polymorphic.ts b/bulma-ui/src/helpers/polymorphic.ts new file mode 100644 index 000000000..2950a46ef --- /dev/null +++ b/bulma-ui/src/helpers/polymorphic.ts @@ -0,0 +1,63 @@ +import type React from 'react'; + +/** + * The ref type of whatever element `as` renders. + * + * Derived from `ComponentPropsWithRef` rather than `React.ComponentRef` so it + * resolves on every `@types/react` a consumer may be on: this package supports + * React 18 and 19, and the CI matrix pins only `react`/`react-dom`, never the + * types, so a types-only regression here would not be caught. + */ +export type PolymorphicRef = + React.ComponentPropsWithRef['ref']; + +/** + * A component's own props, plus the attributes of the element `as` names. + * + * `Own` wins every collision — a component that declares `color` as a Bulma + * variant keeps it, rather than inheriting the DOM attribute of the same name. + * + * Each component writes this intersection out in its own `*Props` alias rather + * than referring to this type: the API-docs extractor + * (`scripts/lib/props-extract.mjs`) walks heritage syntactically, and a generic + * alias leaves it resolving a type parameter it cannot see through. + * This type is here for the component's cast target and for consumers writing + * wrappers. + */ +export type PolymorphicProps = Own & + Omit, keyof Own | 'as'> & { + /** The element or component to render. */ + as?: T; + }; + +/** + * A component whose props and forwarded ref both follow `as`. + * + * `forwardRef` cannot express a generic component, so the implementation is + * cast to this. `displayName` is part of the type because the library sets it + * on every `forwardRef` component, and `withSubComponents` constrains its base + * to `{ displayName?: string }`. + */ +export interface PolymorphicComponent { + ( + props: PolymorphicProps & { ref?: PolymorphicRef } + ): React.ReactElement | null; + displayName?: string; +} + +/** + * A component whose props follow `as` but which forwards no ref. + * + * For components that own the node they observe — `Reveal` keeps its own ref on + * the element it watches for scroll intersection, which is not always the + * element `as` names. + */ +export interface PolymorphicComponentWithoutRef< + Own, + Default extends React.ElementType, +> { + ( + props: PolymorphicProps + ): React.ReactElement | null; + displayName?: string; +} diff --git a/bulma-ui/src/index.ts b/bulma-ui/src/index.ts index a4d4d7da7..1bb4949ba 100644 --- a/bulma-ui/src/index.ts +++ b/bulma-ui/src/index.ts @@ -113,6 +113,7 @@ export * from './grid/Cell'; export * from './grid/Grid'; export * from './helpers/classNames'; +export * from './helpers/polymorphic'; export * from './helpers/mergeBulmaStyles'; export * from './helpers/useBulmaClasses'; export * from './helpers/Theme'; diff --git a/docs/docs/api/components/avatar.md b/docs/docs/api/components/avatar.md index a7a540eda..715bdbf76 100644 --- a/docs/docs/api/components/avatar.md +++ b/docs/docs/api/components/avatar.md @@ -122,6 +122,29 @@ automatic initials/icon fallback runs. --- +### Forwarded ref + +`Avatar` forwards a ref to its root element — the `
    `, or the `` that an `href` selects — not to the inner ``. + +```tsx live +function example() { + const avatarRef = React.useRef(null); + const [tag, setTag] = React.useState(null); + + return ( + <> + + +

    Rendered element: {tag ?? '—'}

    + + ); +} +``` + +--- + ## Accessibility - Image avatars use `alt` (falling back to `name`) for their accessible name. @@ -162,6 +185,7 @@ automatic initials/icon fallback runs. | Prop | Type | Default | Description | | ------------ | ----------------------------------------------------------------------------------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | +| `as` | `React.ElementType` | — | Element/component to render as. Defaults to `'a'` when `href` is set, else `'figure'`. | | `className` | `string` | — | Additional CSS classes to apply. | | `src` | `string` | — | Image URL. On load error (or if absent), falls back to initials, then `icon`. | | `alt` | `string` | — | Alternate text for the image (used for the accessible name in every render mode). An explicit `alt=""` marks a non-interactive avatar as decorative. | @@ -171,12 +195,13 @@ automatic initials/icon fallback runs. | `size` | `'16x16'` \| `'24x24'` \| `'32x32'` \| `'48x48'` \| `'64x64'` \| `'96x96'` \| `'128x128'` \| `number` | — | Preset size, or a pixel size when a number. | | `shape` | `'circle'` \| `'rounded'` \| `'square'` | `'circle'` | Avatar shape. Default `'circle'`. | | `color` | `AvatarColor` | — | Background color for initials/icon avatars (else auto-derived from `name`). | -| `as` | `React.ElementType` | — | Element/component to render as. Defaults to `'a'` when `href` is set, else `'figure'`. | | `href` | `string` | — | When set, renders the avatar as a link. | | `target` | `string` | — | Anchor target — forwarded only when rendering a link (an `a` or a custom `as` component). | | `rel` | `string` | — | Anchor rel — forwarded only when rendering a link (an `a` or a custom `as` component). | | `imageProps` | `React.ImgHTMLAttributes` | — | Extra props forwarded to the underlying `` (e.g. `loading`, `crossOrigin`); its `onError` is chained before the fallback fires. | -| `...` | All standard HTML attributes and Bulma helper props | — | See [Helper Props](../helpers/usebulmaclasses.md) | +| `style` | `React.CSSProperties` | — | Inline styles, merged after the size style. | +| `ref` | `React.Ref` | — | Ref forwarded to the element `as` renders. | +| `...` | All props of the element or component `as` renders and Bulma helper props | — | See [Helper Props](../helpers/usebulmaclasses.md) | **Types:** diff --git a/docs/docs/api/components/avatars.md b/docs/docs/api/components/avatars.md index 717b8c39f..25dd6a4e1 100644 --- a/docs/docs/api/components/avatars.md +++ b/docs/docs/api/components/avatars.md @@ -178,17 +178,17 @@ A `number` sets a pixel overlap directly: -| Prop | Type | Default | Description | -| -------------- | ----------------------------------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `className` | `string` | — | Additional CSS classes to apply. | -| `max` | `number` | — | Show only the first `max` children, replacing the overflow with a "+N" surplus avatar. A single overflow avatar is shown directly rather than as a pointless "+1". | -| `size` | `'16x16'` \| `'24x24'` \| `'32x32'` \| `'48x48'` \| `'64x64'` \| `'96x96'` \| `'128x128'` \| `number` | — | Uniform size applied to every child `Avatar` (and the surplus avatar). | -| `shape` | `'circle'` \| `'rounded'` \| `'square'` | — | Uniform shape applied to every child `Avatar` (and the surplus avatar); a child's own `shape` wins when this is unset. | -| `spacing` | `'sm'` \| `'md'` \| `'lg'` \| `number` | `'md'` | Space between avatars: a preset or a pixel `number`. The overlap distance, or the gap when `spaced`. | -| `spaced` | `boolean` | `false` | Lay the avatars out side by side (non-overlapping), using `spacing` as the gap. | -| `surplusLabel` | `(count: number) => string` | — | Builds the surplus avatar's accessible name from the hidden count, for localization. Default: `` `${count} more` ``. | -| `children` | `React.ReactNode` | — | `Avatar` elements to render inside the group. | -| `...` | All standard `
    ` attributes and Bulma helper props | — | See [Helper Props](../helpers/usebulmaclasses.md) | +| Prop | Type | Default | Description | +| -------------- | ------------------------------------------------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `className` | `string` | — | Additional CSS classes to apply. | +| `max` | `number` | — | Show only the first `max` children, replacing the overflow with a "+N" surplus avatar. A single overflow avatar is shown directly rather than as a pointless "+1". | +| `size` | `AvatarProps['size']` | — | Uniform size applied to every child `Avatar` (and the surplus avatar). | +| `shape` | `AvatarProps['shape']` | — | Uniform shape applied to every child `Avatar` (and the surplus avatar); a child's own `shape` wins when this is unset. | +| `spacing` | `'sm'` \| `'md'` \| `'lg'` \| `number` | `'md'` | Space between avatars: a preset or a pixel `number`. The overlap distance, or the gap when `spaced`. | +| `spaced` | `boolean` | `false` | Lay the avatars out side by side (non-overlapping), using `spacing` as the gap. | +| `surplusLabel` | `(count: number) => string` | — | Builds the surplus avatar's accessible name from the hidden count, for localization. Default: `` `${count} more` ``. | +| `children` | `React.ReactNode` | — | `Avatar` elements to render inside the group. | +| `...` | All standard `
    ` attributes and Bulma helper props | — | See [Helper Props](../helpers/usebulmaclasses.md) | **Subcomponents:** diff --git a/docs/docs/api/components/menu.md b/docs/docs/api/components/menu.md index 9fbe42b7d..fcd371c78 100644 --- a/docs/docs/api/components/menu.md +++ b/docs/docs/api/components/menu.md @@ -75,7 +75,7 @@ To create a sidebar or section menu with multiple levels, use the `Menu` compone ### Custom Link Component -Use the `as` prop on `Menu.Item` to render a custom link component, such as a router link. This enables seamless integration with client-side routing libraries, allowing you to pass additional props like `to` or `href` as needed for navigation. +Use the `as` prop on `Menu.Item` to render a custom link component, such as a router link. Its props follow `as`, so props like `to` or `href` are checked against whatever you render and are forwarded to it. ```tsx live // import { Link } from 'react-router-dom'; @@ -141,6 +141,35 @@ Create multi-level navigation by nesting `Menu.List` components inside `Menu.Ite --- +### Forwarded ref + +`Menu.Item` forwards a ref to the **inner** element — the one `as` names — not to the wrapping `
  • `. That is the element you want for programmatic focus. + +```tsx live +function example() { + const itemRef = React.useRef(null); + + return ( + <> + + + General + + Dashboard + + Customers + + + + + ); +} +``` + +--- + ### Compound (dot-notation) usage `MenuLabel`, `MenuList`, and `MenuItem` are also available as `Menu.Label`, `Menu.List`, and `Menu.Item`, so the whole menu can be composed from the single `Menu` import. @@ -224,14 +253,20 @@ You can use all [Bulma helper props](../helpers/usebulmaclasses.md) with ``). | -| `as` | `React.ElementType` | `'a'` | Custom link component (e.g. `Link` from router). | -| `...` | All standard `
  • ` attributes and Bulma helper props | — | See [Helper Props](../helpers/usebulmaclasses.md) | +| Prop | Type | Default | Description | +| ------------- | ----------------------------------------------------------------------------------------- | ------- | ------------------------------------------------------------------------- | +| `as` | `React.ElementType` | `'a'` | Custom link component (e.g. `Link` from router). | +| `className` | `string` | — | Additional CSS classes for the wrapping `
  • `. | +| `children` | `React.ReactNode` | — | Item content and optional nested MenuList. | +| `active` | `boolean` | `false` | Highlight item as active. | +| `style` | `React.CSSProperties` | — | Inline styles for the wrapping `
  • `. | +| `id` | `string` | — | `id` for the wrapping `
  • `. | +| `title` | `string` | — | `title` for the wrapping `
  • `. | +| `role` | `React.AriaRole` | — | ARIA role for the wrapping `
  • `. | +| `tabIndex` | `number` | — | Tab index for the wrapping `
  • `. | +| `data-testid` | `string` | — | Test id for the wrapping `
  • `. | +| `ref` | `React.Ref` | — | Ref forwarded to the inner element `as` renders, not the wrapping `
  • `. | +| `...` | All props of the element or component `as` renders (default ``) and Bulma helper props | — | See [Helper Props](../helpers/usebulmaclasses.md) | diff --git a/docs/docs/api/components/navbar.md b/docs/docs/api/components/navbar.md index 3944c392d..455f99d72 100644 --- a/docs/docs/api/components/navbar.md +++ b/docs/docs/api/components/navbar.md @@ -181,7 +181,7 @@ A more complex example with navigation links and a dropdown menu. The dropdown i ### Custom Link Component -Use the `as` prop on `Navbar.Item` to render a custom link component, such as a router link. Extra props like `to` are forwarded to the link component and type-check without casts, so client-side routing libraries integrate directly. See the [Routing guide](../../guides/features/routing.md) for the full patterns. +Use the `as` prop on `Navbar.Item` to render a custom link component, such as a router link. Its props follow `as`, so props like `to` are forwarded to the link component and are checked against that component's own types, no cast needed. See the [Routing guide](../../guides/features/routing.md) for the full patterns. ```tsx live // import { Link } from 'react-router-dom'; @@ -391,7 +391,7 @@ function example() { ### Forwarded ref -`Navbar` forwards a ref to the root `