diff --git a/bestax-mcp/data/catalog.json b/bestax-mcp/data/catalog.json index a8eeebf77..a09719c6f 100644 --- a/bestax-mcp/data/catalog.json +++ b/bestax-mcp/data/catalog.json @@ -139,8 +139,8 @@ "slug": "components/avatar", "import": "import { Avatar } from '@allxsmith/bestax-bulma';", "compound": false, - "propCount": 14, - "exampleCount": 7 + "propCount": 15, + "exampleCount": 8 }, { "name": "Avatars", @@ -150,7 +150,7 @@ "slug": "components/avatars", "import": "import { Avatars, Avatar } from '@allxsmith/bestax-bulma';", "compound": true, - "propCount": 22, + "propCount": 23, "exampleCount": 8 }, { @@ -205,7 +205,7 @@ "slug": "elements/button", "import": "import { Button } from '@allxsmith/bestax-bulma';", "compound": false, - "propCount": 23, + "propCount": 19, "exampleCount": 25 }, { @@ -216,7 +216,7 @@ "slug": "elements/buttons", "import": "import { Buttons } from '@allxsmith/bestax-bulma';", "compound": true, - "propCount": 53, + "propCount": 45, "exampleCount": 8 }, { @@ -569,7 +569,7 @@ "import": "import { Link } from '@allxsmith/bestax-bulma';", "compound": false, "propCount": 6, - "exampleCount": 11 + "exampleCount": 12 }, { "name": "LinkButton", @@ -579,7 +579,7 @@ "slug": "elements/linkbutton", "import": "import { LinkButton } from '@allxsmith/bestax-bulma';", "compound": false, - "propCount": 21, + "propCount": 17, "exampleCount": 10 }, { @@ -623,8 +623,8 @@ "slug": "components/menu", "import": "import { Menu } from '@allxsmith/bestax-bulma';", "compound": true, - "propCount": 11, - "exampleCount": 5 + "propCount": 16, + "exampleCount": 6 }, { "name": "Message", @@ -788,7 +788,7 @@ "slug": "components/reveal", "import": "import { Reveal } from '@allxsmith/bestax-bulma';", "compound": false, - "propCount": 9, + "propCount": 11, "exampleCount": 5 }, { diff --git a/bestax-mcp/data/components/Avatar.json b/bestax-mcp/data/components/Avatar.json index 610c7aabf..96db68ec4 100644 --- a/bestax-mcp/data/components/Avatar.json +++ b/bestax-mcp/data/components/Avatar.json @@ -32,6 +32,10 @@ { "title": "Forwarding Props to the Image", "code": "" + }, + { + "title": "Forwarded ref", + "code": "function example() {\n const avatarRef = React.useRef(null);\n const [tag, setTag] = React.useState(null);\n\n return (\n <>\n \n \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": "PolymorphicRef", + "default": null, + "description": "Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes.", + "required": false, + "inherited": false, + "deprecated": false } ], - "extraProps": [], - "catchAll": "All standard HTML attributes and Bulma helper props", + "catchAll": "Remaining props of the element or component selected by as (default
) 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..4438d329b 100644 --- a/bestax-mcp/data/components/Avatars.json +++ b/bestax-mcp/data/components/Avatars.json @@ -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": "PolymorphicRef", + "default": null, + "description": "Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes.", + "required": false, + "inherited": false, + "deprecated": false + } + ], + "catchAll": "Remaining props of the element or component selected by as (default
) 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..c1d7f780e 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 another intrinsic element (`'span'`, `'button'`) or 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": "PolymorphicRef", "default": null, - "description": "Relationship between current and linked document.", + "description": "Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes.", "required": false, "inherited": false, "deprecated": false } ], - "catchAll": "All standard attributes and Bulma helper props", + "catchAll": "Remaining props of the element or component selected by as (default ) and Bulma helper props", "types": [] } ], diff --git a/bestax-mcp/data/components/LinkButton.json b/bestax-mcp/data/components/LinkButton.json index 50948f956..e59c67224 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": "PolymorphicRef", + "default": null, + "description": "Ref forwarded to the inner element `as` renders, not the wrapping `
  • `, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes.", + "required": false, + "inherited": false, + "deprecated": false + } + ], + "catchAll": "Remaining props of the element or component selected by as (default ) and Bulma helper props", "types": [] } ], diff --git a/bestax-mcp/data/components/Navbar.json b/bestax-mcp/data/components/Navbar.json index 643bf1a25..0515515a5 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 another intrinsic element (`'span'`, `'div'`) or a custom component (e.g. a router link). Defaults to `'a'`.", "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": "PolymorphicRef", + "default": null, + "description": "Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes.", + "required": false, + "inherited": false, + "deprecated": false + } + ], + "catchAll": "Remaining props of the element or component selected by as (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 another intrinsic element (`'button'`, `'span'`) or a custom component. Defaults to `'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": "PolymorphicRef", "default": null, - "description": "Ref forwarded to the rendered link or button element.", + "description": "Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes.", "required": false, "inherited": false, "deprecated": false } ], - "catchAll": "All standard attributes and Bulma helper props", + "catchAll": "Remaining props of the element or component selected by as (default ) and Bulma helper props", "types": [] }, { diff --git a/bestax-mcp/data/components/Reveal.json b/bestax-mcp/data/components/Reveal.json index d6305de9a..120bdfede 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": "Remaining props of the element or component selected by as (default
    ) and Bulma helper props", "types": [] } ], diff --git a/bestax-mcp/data/skills.json b/bestax-mcp/data/skills.json index 7596191de..196fa9c20 100644 --- a/bestax-mcp/data/skills.json +++ b/bestax-mcp/data/skills.json @@ -15,7 +15,7 @@ { "id": "library-contributor", "file": "references/library-contributor.md", - "bytes": 15257 + "bytes": 17474 }, { "id": "patterns", "file": "references/patterns.md", "bytes": 4601 } ], @@ -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__/helper-props.tsx b/bulma-ui/src/__typetests__/helper-props.tsx new file mode 100644 index 000000000..585401e4d --- /dev/null +++ b/bulma-ui/src/__typetests__/helper-props.tsx @@ -0,0 +1,37 @@ +import type { BulmaClassesProps } from '../helpers/useBulmaClasses'; +import type { ButtonOwnProps } from '../elements/Button'; +import type { LinkButtonOwnProps } from '../elements/LinkButton'; +import type { LinkOwnProps } from '../elements/Link'; +import type { AvatarOwnProps } from '../components/Avatar'; +import type { RevealOwnProps } from '../components/Reveal'; +import type { + NavbarItemOwnProps, + NavbarLinkOwnProps, +} from '../components/Navbar'; +import type { MenuItemOwnProps } from '../components/Menu'; + +/** + * Every Bulma helper key must be DECLARED on a polymorphic component's own + * props, never merely `Omit`ted from `BulmaClassesProps`. + * + * Omitting a key takes it out of `keyof Own`, which is what subtracts the + * element's side — so the key comes back from whatever `as` renders, while + * `useBulmaClasses` still consumes it before `rest` is spread. A custom target + * declaring one then type-checks and never receives it. + * + * This caught `color` on three components and `backgroundColor` on five, in + * two separate review rounds. The check exists so the next helper prop, or the + * next polymorphic component, cannot reopen the class quietly: a failure names + * the component and the missing key. + */ +type Missing = Exclude; +type None = [T] extends [never] ? true : { MISSING: T }; + +export const button: None> = true; +export const linkButton: None> = true; +export const link: None> = true; +export const avatar: None> = true; +export const reveal: None> = true; +export const navbarItem: None> = true; +export const navbarLink: None> = true; +export const menuItem: None> = true; diff --git a/bulma-ui/src/__typetests__/polymorphic.tsx b/bulma-ui/src/__typetests__/polymorphic.tsx new file mode 100644 index 000000000..323b8e5aa --- /dev/null +++ b/bulma-ui/src/__typetests__/polymorphic.tsx @@ -0,0 +1,257 @@ +/** + * 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, type ButtonProps } from '../elements/Button'; +import { Link } from '../elements/Link'; +import { LinkButton } from '../elements/LinkButton'; + +/** A component that forwards no ref, the way most hand-written ones do. */ +const PlainFC = (props: { children?: React.ReactNode }) => ( + {props.children} +); + +/** 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..c1c85f1fa 100644 --- a/bulma-ui/src/components/Avatar.tsx +++ b/bulma-ui/src/components/Avatar.tsx @@ -1,6 +1,10 @@ -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 { + isCustomElement, + type PolymorphicComponent, +} from '../helpers/polymorphic'; const avatarColors = [ 'primary', @@ -87,12 +91,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 +113,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 +121,56 @@ 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; + /** + * Not accepted. Avatar always renders its own content — the image, the + * initials, or the icon — so anything a caller passed would be replaced. It + * is declared unavailable rather than derived from `as`, which would let a + * target requiring `children` compel a value it then never receives. + * @internal + */ + children?: never; } +/** + * 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 `'figure'`, not to `React.ElementType`. + * Defaulting to the constraint sounds truer to a runtime default that is + * conditional, but `ComponentPropsWithoutRef` spreads across + * every element at once and accepts anything — which is the false-positive this + * whole change exists to remove. `'figure'` is the element a no-`href` avatar + * actually renders, and the anchor props it can additionally take are declared + * above. + * + * @extraProp {PolymorphicRef} [ref] - Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes. + */ +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 +178,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 @@ -221,11 +268,12 @@ export const Avatar: React.FC = ({ const isInteractive = Tag === 'a' || Tag === 'button' || - (typeof Tag !== 'string' && href != null); + ((typeof Tag !== 'string' || isCustomElement(Tag)) && href != null); // Only forward link attributes when rendering an anchor or a custom (non-DOM) // component; a plain `as="div"` must not receive a stray `href`/`target`/`rel`. - const isLinkLike = Tag === 'a' || typeof Tag !== 'string'; + const isLinkLike = + Tag === 'a' || typeof Tag !== 'string' || isCustomElement(Tag); const linkProps = isLinkLike ? { href, target, rel } : {}; // alt coalesces with ?? (not ||) so an explicit alt="" survives as the @@ -254,6 +302,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..4f10a83c7 100644 --- a/bulma-ui/src/components/Menu.tsx +++ b/bulma-ui/src/components/Menu.tsx @@ -1,7 +1,11 @@ -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 { + isCustomElement, + type PolymorphicComponent, +} from '../helpers/polymorphic'; // Context to track MenuList nesting level const MenuListLevelContext = createContext(0); @@ -131,50 +135,96 @@ 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 {PolymorphicRef} [ref] - Ref forwarded to the inner element `as` renders, not the wrapping `
  • `, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes. + */ +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: forwarded } = useBulmaClasses(rest); + // `href` reaches an anchor or a custom component (which owns its own prop + // contract), but not another intrinsic tag — `` is invalid HTML. + // The same rule Avatar applies through `isLinkLike` and Button through its + // intrinsic-only strip. Before #641 `href` was an own prop re-applied only + // for `as="a"`; deriving it from `as` must not quietly widen that. + const isLinkLike = + Component === 'a' || + typeof Component !== 'string' || + isCustomElement(Component); + const { href: _href, ...withoutHref } = forwarded as { href?: string }; + const linkProps = isLinkLike ? forwarded : withoutHref; 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 +236,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..b778fe3bf 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,30 @@ 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' +> { + /** + * Not accepted. `color` here would be the deprecated presentational HTML + * attribute, and `useBulmaClasses` consumes any `color` key as a Bulma helper + * before the target could see it — so it is declared unavailable rather than + * silently eaten. Use `textColor` / `bgColor`. + * @internal + */ + color?: never; + /** + * Not accepted under this name. `useBulmaClasses` consumes any + * `backgroundColor` key before `rest` is spread, so a custom `as` target + * declaring one would never receive it. Use `bgColor`. + * @internal + */ + backgroundColor?: never; /** 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 +196,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 {PolymorphicRef} [ref] - Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes. + */ +export type NavbarItemProps = + NavbarItemOwnProps & + Omit, keyof NavbarItemOwnProps | 'as'> & { + /** Render as another intrinsic element (`'span'`, `'div'`) or a custom component (e.g. a router link). Defaults to `'a'`. */ + 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 +247,7 @@ export const NavbarItem: React.FC = ({ return ( = ({ {children} ); -}; +}) as PolymorphicComponent; + +NavbarItem.displayName = 'NavbarItem'; /** * Props for the NavbarBurger component. @@ -417,17 +458,30 @@ 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' +> { + /** + * Not accepted. `color` here would be the deprecated presentational HTML + * attribute, and `useBulmaClasses` consumes any `color` key as a Bulma helper + * before the target could see it — so it is declared unavailable rather than + * silently eaten. Use `textColor` / `bgColor`. + * @internal + */ + color?: never; + /** + * Not accepted under this name. `useBulmaClasses` consumes any + * `backgroundColor` key before `rest` is spread, so a custom `as` target + * declaring one would never receive it. Use `bgColor`. + * @internal + */ + backgroundColor?: never; /** 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 +492,47 @@ 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` and `target`. Not `rel` — React declares it on + * `HTMLAttributes`, so it is valid on every element, and rejecting it would + * mean diverging from React's own typing. + * + * @extraProp {PolymorphicRef} [ref] - Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes. + */ +export type NavbarLinkProps = + NavbarLinkOwnProps & + Omit, keyof NavbarLinkOwnProps | 'as'> & { + /** Render as another intrinsic element (`'button'`, `'span'`) or a custom component. Defaults to `'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 +540,7 @@ export const NavbarLink = forwardRef< bgColor, children, ...props - }, - ref -) { + } = linkProps as NavbarLinkImplProps; const { bulmaHelperClasses, rest } = useBulmaClasses({ color: textColor, backgroundColor: bgColor, @@ -468,11 +548,20 @@ 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; + // Guarded like Button's disabled blocker: these run on whatever `as` renders, + // and a custom target's callback need not take a DOM event. One declaring + // `onKeyDown: (k: {key: string}) => void` reaches `e.preventDefault()` and + // throws. Composing the caller's handler is unconditional; acting on the + // event is not ours to do when the payload is foreign. + const isDomEvent = (e: unknown): e is { preventDefault: () => void } => + typeof (e as { preventDefault?: unknown })?.preventDefault === 'function'; + const handleKeyDown = (e: React.KeyboardEvent) => { rest.onKeyDown?.(e); + if (!isDomEvent(e)) return; if (!dropdownContext || e.defaultPrevented) return; if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); @@ -490,6 +579,7 @@ export const NavbarLink = forwardRef< // click semantics (navigation / the caller's handler). const handleClick = (e: React.MouseEvent) => { rest.onClick?.(e); + if (!isDomEvent(e)) return; if (!dropdownContext || isNativeInteractive || e.defaultPrevented) return; dropdownContext.toggle(); }; @@ -519,7 +609,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..22fc962fd 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 -}) => { +function RevealImpl(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(); @@ -219,12 +242,16 @@ export const Reveal: React.FC = ({ }) : children; - // Scroll observation needs a real DOM node. Intrinsic tags ('div', - // 'section', ...) always accept a ref directly. A custom component passed - // via `as` (Section, Card, ...) is rendered by this library as a plain - // React.FC with no ref forwarding, so the ref (and the animation classes - // that depend on it) go on a plain wrapper `div` instead, with `Component` - // rendered inside it. + // Scroll observation needs a DOM node this component OWNS — the observer and + // the animation classes both key off it. An intrinsic tag is that node, so + // the ref goes straight on it. A component passed via `as` is not: whatever + // it renders is its own business, and it may render several elements or + // none. So it gets wrapped in an observed `div`. + // + // Not a statement about ref forwarding. Several components in this library + // forward refs (#641 added four more), and that changes nothing here — a + // forwarded ref would still point at the target's node rather than at one + // this component controls. if (typeof Component === 'string') { // A plain createElement call sidesteps the combinatorial JSX prop types // for `ref` across every possible intrinsic tag `as` could be. @@ -245,6 +272,13 @@ export const Reveal: React.FC = ({ {content}
    ); -}; +} + +export const Reveal = RevealImpl as PolymorphicComponentWithoutRef< + RevealOwnProps, + 'div' +>; + +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..119b6ad84 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,38 @@ describe('Avatar', () => { expect(avatar).not.toHaveClass('avatar'); }); }); + +describe('Custom element targets', () => { + it('keeps role="img" on a custom element with no href', () => { + // A custom element is not inherently interactive — it is a string tag with + // consumer-declared props, and without an href it is still a picture. + render(); + expect(screen.getByTestId('a')).toHaveAttribute('role', 'img'); + }); + + it('drops role="img" once the custom element has an href', () => { + render( + + ); + const el = screen.getByTestId('a'); + expect(el).not.toHaveAttribute('role', 'img'); + expect(el).toHaveAttribute('href', '/p'); + }); +}); + +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..b837661ae 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,98 @@ describe('Compound components', () => { expect(container.querySelectorAll('.menu-list li')).toHaveLength(2); }); }); + +describe('href routing', () => { + it('withholds href from a non-anchor intrinsic tag', () => { + render( + + + {/* @ts-expect-error a span takes no href; a JS consumer can still + deliver one, and it must not reach the DOM */} + + Static + + + + ); + const span = screen.getByTestId('li').querySelector('span'); + expect(span).not.toHaveAttribute('href'); + }); + + it('forwards href to a custom element, which declares its own props', () => { + render( + + + )} + data-testid="li" + > + i + + + + ); + expect(screen.getByTestId('li').querySelector('x-link')).toHaveAttribute( + 'href', + '/x' + ); + }); + + it('forwards href to a custom component, which owns its prop contract', () => { + const Custom = ({ + href, + children, + }: { + href?: string; + children?: React.ReactNode; + }) => ( + + {children} + + ); + render( + + + + Go + + + + ); + expect(screen.getByTestId('custom')).toHaveAttribute('href', '/x'); + }); +}); + +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..d35f47bc0 100644 --- a/bulma-ui/src/components/__tests__/Navbar.test.tsx +++ b/bulma-ui/src/components/__tests__/Navbar.test.tsx @@ -252,6 +252,24 @@ describe('Navbar.Item', () => { const item = screen.getByTestId('navitem'); expect(item).toHaveAttribute('href', '/test'); }); + // 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('Navbar.Burger', () => { diff --git a/bulma-ui/src/elements/Button.tsx b/bulma-ui/src/elements/Button.tsx index e4f12e8b7..e93ef9f2a 100644 --- a/bulma-ui/src/elements/Button.tsx +++ b/bulma-ui/src/elements/Button.tsx @@ -1,5 +1,9 @@ import React, { forwardRef } from 'react'; import { classNames, usePrefixedClassNames } from '../helpers/classNames'; +import { + isCustomElement, + type PolymorphicComponent, +} from '../helpers/polymorphic'; import { useBulmaClasses, BulmaClassesProps, @@ -7,13 +11,20 @@ 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' +> { + /** + * Not accepted under this name. `useBulmaClasses` consumes any + * `backgroundColor` key before `rest` is spread, so a custom `as` target + * declaring one would never receive it. Use `bgColor`. + * @internal + */ + backgroundColor?: never; /** Bulma color variant for the button. `ghost` renders a link-like button; `text` renders a minimal text-only button. */ color?: | 'primary' @@ -60,21 +71,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..be3ac2521 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,28 @@ 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' +> { + /** + * Not accepted. `color` on this component would be the deprecated + * presentational HTML attribute, and `useBulmaClasses` consumes any `color` + * key as a Bulma helper before the target could see it — so it is declared + * unavailable rather than silently eaten. Use `textColor` / `bgColor`. + * @internal + */ + color?: never; + /** + * Not accepted under this name. `useBulmaClasses` consumes any + * `backgroundColor` key before `rest` is spread, so a custom `as` target + * declaring one would never receive it. Use `bgColor`. + * @internal + */ + backgroundColor?: never; /** Additional CSS classes to apply. */ className?: string; /** Text color helper. */ @@ -24,29 +38,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 {PolymorphicRef} [ref] - Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes. + */ +export type LinkProps = LinkOwnProps & + Omit, keyof LinkOwnProps | 'as'> & { + /** Render as another intrinsic element (`'span'`, `'button'`) or 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 +99,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..5bf7b60eb 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. */ @@ -23,14 +25,43 @@ export interface LinkButtonProps extends Omit< | 'light' | 'dark' | 'black'; + /** + * Not available on `LinkButton`, and declared so that a custom `as` target + * cannot reintroduce it. `Button` consumes these three for styling variants + * `LinkButton` does not offer, and strips them before rendering the target — + * so without this a component requiring one would type-check and silently + * never receive it. + * @internal + */ + isOutlined?: never; + /** @internal Not available on `LinkButton` — see `isOutlined`. */ + isInverted?: never; + /** @internal Not available on `LinkButton` — see `isOutlined`. */ + isLight?: never; } +/** + * Props for the LinkButton component. The DOM attributes and the `ref` both + * follow `as`, exactly as they do on `Button`. + * + * @extraProp {PolymorphicRef} [ref] - Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes. + */ +export type LinkButtonProps = + LinkButtonOwnProps & + Omit, keyof LinkButtonOwnProps | 'as'> & { + /** + * Render as a ` + ); + const link = screen.getByTestId('a'); + expect(link).not.toHaveAttribute('formaction'); + // An anchor owns neither filter's props, so it takes both. Scoping the + // submit-overrides to `as="a"` in an if/else let `disabled` back onto it. + expect(link).not.toHaveAttribute('disabled'); + }); + + it('keeps the form attributes an input owns', () => { + // The strip list used to remove `name` and `value` from every non-button + // tag, so this rendered an input the form submitted nothing for. + render( + + ); + expect(screen.getByTestId('s')).not.toHaveAttribute('disabled'); + }); + + it('does not throw when a disabled custom target has a non-DOM onClick', () => { + // The isDisabled blocker is installed into whatever `as` renders. A + // component declaring `onClick: (v: string) => void` calls it with a + // string, and an unguarded `e.preventDefault()` threw. + const Custom = (p: { + onClick?: (v: string) => void; + children?: React.ReactNode; + }) => ( + p.onClick?.('a string')}> + {p.children} + + ); + const { container } = render( + + ); + expect(() => + (container.querySelector('a') as HTMLElement).click() + ).not.toThrow(); + }); + + it('leaves a custom element alone, props and all', () => { + // A custom element is an intrinsic STRING, so the built-in backstop + // caught it — but its props are whatever a consumer declared through + // `React.JSX.IntrinsicElements`, the way this package declares + // ``. A hyphen is exact: HTML requires one in a custom element + // name and no built-in has one. + render( + + ); + const fieldset = screen.getByTestId('f'); + expect(fieldset).toHaveAttribute('form', 'signup'); + expect(fieldset).toBeDisabled(); + }); + + it('keeps an attribute the anchor itself accepts', () => { + // `type` is the anchor's MIME hint and `ButtonProps<'a'>` types it as + // such, but the strip list removed it by spelling because a + ); + expect(screen.getByTestId('a')).toHaveAttribute( + 'type', + 'application/pdf' + ); + }); }); describe('as={Component} custom component rendering', () => { @@ -138,18 +285,31 @@ describe('Button Component', () => { expect(link).toHaveAttribute('data-to', '/visit'); }); - it('does not forward button-only attributes to a custom component', () => { - const CustomLink = ( - props: React.AnchorHTMLAttributes - ) => ; + it('forwards a prop a custom component declares, even a stripped name', () => { + // The strip list matches on spelling, so `name` used to be removed from + // every non-button `as` — including a component that requires it. The + // props type promises the component's own props reach it; only intrinsic + // tags, where an unknown attribute would be invalid HTML, are filtered. + const Custom = ({ + name, + children, + }: { + name: string; + children?: React.ReactNode; + }) => ( + + {children} + + ); render( - ); - const link = screen.getByRole('link'); - expect(link).not.toHaveAttribute('type'); - expect(link).not.toHaveAttribute('name'); + expect(screen.getByTestId('custom')).toHaveAttribute( + 'data-name', + 'required' + ); }); }); 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..8c61384a9 --- /dev/null +++ b/bulma-ui/src/helpers/polymorphic.ts @@ -0,0 +1,129 @@ +import type React from 'react'; + +/** + * Whether an `as` target is a custom element rather than a built-in tag. + * + * HTML requires a custom element's name to contain a hyphen, and no built-in + * element name has one, so this is exact rather than a heuristic. It matters + * because a custom element is an intrinsic STRING — `typeof as === 'string'` is + * true — while its props are whatever a consumer declared through + * `React.JSX.IntrinsicElements`, the way this package declares ``. + * A runtime backstop that filters built-in attributes must leave those alone, + * or it strips props the derived type just promised to forward. + */ +export function isCustomElement(as: unknown): as is string { + return typeof as === 'string' && as.includes('-'); +} + +/** + * 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. + * + * `never` when the target takes no ref. A plain function component has no `ref` + * key at all, and React's own types reject ``; without the + * guard the indexed access degraded to `unknown` and we accepted a ref that + * silently does nothing — `ref.current` stays null and a later `.focus()` + * throws. Matching React's strictness is the point. + */ +export type PolymorphicRef = + 'ref' extends keyof React.ComponentPropsWithRef + ? React.ComponentPropsWithRef['ref'] + : never; + +/** + * 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. + * That subtraction is the ONLY one. `color` used to be dropped here as well, to + * stop the deprecated presentational HTML attribute reaching the three + * components whose own props do not declare one — but doing it in the shared + * type also stripped `color` from a CUSTOM target that legitimately has one. + * Those three declare `color?: never` themselves instead, which lands in + * `keyof Own` and reaches the same result without a special case here. + * + * Distributive over `T` on purpose. `Omit` keys off `keyof (A | B)`, + * which is only what A and B share — so a union-typed `as` (a ternary, or a + * variable typed `'a' | 'button'`) silently lost every prop that belongs to + * just one member, `href` among them. Distributing produces a union of prop + * shapes instead, and each member keeps its own. + * + * 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< + T extends React.ElementType, + Own, +> = T extends unknown + ? Own & + Omit, keyof Own | 'as'> & { + /** The element or component to render. */ + as?: T; + } + : never; + +/** + * 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 }`. + * + * The second, non-generic signature exists for type DERIVATION rather than for + * calls. `React.ComponentProps` infers from the last overload; + * with only the generic one it instantiated at the constraint and collapsed to + * `any`, so a consumer building their own prop type on ours lost every check. + * Calls still resolve against the generic signature first, so ordering here is + * load-bearing — swapping the two puts the collapse back. + * + * **A wrapping HOC erases the genericity.** `React.memo(Button)`, + * `React.lazy`, a `styled()` wrapper — anything that infers its props through + * `ComponentProps` — instantiates the type parameter once and hands back a + * component with a single widened prop type. Calls still work, but the checks + * stop: `` compiles where ` +

    Rendered element: {tag ?? '—'}

    + + ); +} +``` + +--- + ## Accessibility - Image avatars use `alt` (falling back to `name`) for their accessible name. @@ -160,23 +183,25 @@ automatic initials/icon fallback runs. -| Prop | Type | Default | Description | -| ------------ | ----------------------------------------------------------------------------------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -| `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. | -| `name` | `string` | — | Derives initials and a deterministic background color when no `src` is shown. | -| `initials` | `string` | — | Explicit initials override (else derived from `name`). | -| `icon` | `React.ReactNode` | — | Final fallback, rendered when there is no `src`, `name`, or `initials`. | -| `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) | +| 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. | +| `name` | `string` | — | Derives initials and a deterministic background color when no `src` is shown. | +| `initials` | `string` | — | Explicit initials override (else derived from `name`). | +| `icon` | `React.ReactNode` | — | Final fallback, rendered when there is no `src`, `name`, or `initials`. | +| `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`). | +| `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. | +| `style` | `React.CSSProperties` | — | Inline styles, merged after the size style. | +| `ref` | `PolymorphicRef` | — | Ref forwarded to the element `as` renders, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes. | +| `...` | Remaining props of the element or component selected by `as` (default `
    `) and Bulma helper props | — | See [Helper Props](../helpers/usebulmaclasses.md) | **Types:** diff --git a/docs/docs/api/components/menu.md b/docs/docs/api/components/menu.md index 9fbe42b7d..ca65c635b 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` | `PolymorphicRef` | — | Ref forwarded to the inner element `as` renders, not the wrapping `
  • `, typed from `as`: the DOM node for an intrinsic tag, or whatever handle a custom component exposes. | +| `...` | Remaining props of the element or component selected by `as` (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..52d78929e 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 `