Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/components/Button/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ import { BBButton } from 'bbb-ui-components-react';
</form>
```

### Disabled Button with Tooltip

Useful to explain why a button is disabled. The tooltip shows on hover and keyboard focus, and its text is also exposed to screen readers as the button's description.

A disabled button with a `tooltipLabel` stays in the tab order so keyboard users can reach the tooltip: it gets `aria-disabled="true"` instead of the native `disabled` attribute, keeps the disabled look, and ignores clicks, Enter and Space, without submitting its form when `type="submit"`. Without a `tooltipLabel`, a disabled button is natively disabled.

```jsx
import { BBButton } from 'bbb-ui-components-react';

<BBButton label="Start" disabled tooltipLabel="Pick a response type first" onClick={() => (console.log('clicked'))}/>
```

### Full-width Button

```jsx
Expand Down Expand Up @@ -111,7 +123,7 @@ const FooterButton = styled(BBButton)`
| `id` | `string` | `''` | The unique identifier for the button. |
| `dataTest` | `string` | | The 'data-test' attribute for testing purposes. |
| `label` | `string` | | The text to be displayed on the button. |
| `tooltipLabel` | `string` | | The text to be displayed in a tooltip on hover. |
| `tooltipLabel` | `string` | | Text shown in a tooltip on hover and keyboard focus. When set, a disabled button stays focusable (`aria-disabled`) so the tooltip can be reached. |
| `tooltipPlacement` | `keyof typeof TOOLTIP_PLACEMENTS` | `'top'` | The placement of the tooltip. |
| `onClick` | `() => void` | | The function to be called when the button is clicked. |
| `onKeyDown` | `(event: React.KeyboardEvent<HTMLButtonElement>) => void` | | The function to be called when a key is pressed. |
Expand All @@ -123,7 +135,7 @@ const FooterButton = styled(BBButton)`
| `size` | `keyof typeof SIZES` | `'medium'` | The size of the button. |
| `layout` | `keyof typeof LAYOUTS` | `'default'` | The layout of the button. |
| `type` | `'button' \| 'submit' \| 'reset'` | `'button'` | The native `type` attribute of the `<button>`. Defaults to `'button'` so it never submits an enclosing form unless `'submit'` is passed explicitly. |
| `disabled` | `boolean` | `false` | If `true`, the button will be disabled. |
| `disabled` | `boolean` | `false` | If `true`, the button will be disabled. With a `tooltipLabel`, it uses `aria-disabled` instead of the native `disabled` attribute, so it stays focusable. |
| `fullWidth` | `boolean` | `false` | If `true`, the button fills the width of its container, keeping its content centered. Used for 'default' layout. |
| `labelOverflow` | `'nowrap' \| 'wrap' \| 'ellipsis'` | `'nowrap'` | What happens when the label doesn't fit the button's available width: `nowrap` keeps it on one line, widening the button or overflowing it, `wrap` breaks it onto more lines, `ellipsis` truncates it and shows the full label as a tooltip unless `tooltipLabel` is set. Used for 'default' layout. |
| `className` | `string` | | Class name forwarded to the root element (the `<button>`, or the wrapper `<div>` in the 'stacked' layout), so `styled(BBButton)` works. Escape hatch while BBButton is being adopted; prefer native props and open an issue for recurring needs. |
Expand Down
14 changes: 12 additions & 2 deletions src/components/Button/component.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const meta = {
},
tooltipLabel: {
control: 'text',
description: 'Text shown inside a tooltip. Tooltip appears only when this prop is provided.',
description: 'Text shown in a tooltip on hover and keyboard focus; when set, a disabled button stays focusable (`aria-disabled`) so the tooltip can be reached.',
table: { defaultValue: { summary: "''" } },
},
tooltipPlacement: {
Expand Down Expand Up @@ -77,7 +77,7 @@ const meta = {
},
disabled: {
control: 'boolean',
description: 'Disables interaction and applies disabled visuals. Works across all layouts.',
description: 'Disables interaction and applies disabled visuals. Works across all layouts. With `tooltipLabel`, the button stays focusable and is announced through `aria-disabled` instead of the native `disabled` attribute.',
table: { defaultValue: { summary: 'false' } },
},
fullWidth: {
Expand Down Expand Up @@ -403,6 +403,16 @@ export const Disabled: Story = {
},
};

/** Disabled button that stays keyboard-focusable so its tooltip can explain why it is unavailable. */
export const DisabledWithTooltip: Story = {
args: {
label: 'Start',
variant: 'primary',
disabled: true,
tooltipLabel: 'Pick a response type first',
},
};

/** Shows a `fullWidth` button filling its container, with the label centered. */
export const FullWidth: Story = {
args: {
Expand Down
49 changes: 39 additions & 10 deletions src/components/Button/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,15 +63,26 @@ function Button(props: ButtonProps): JSX.Element {
if (feedbackTimeoutRef.current) clearTimeout(feedbackTimeoutRef.current);
}, []);

// A natively disabled button leaves the tab order, so keyboard users could never reach the
// tooltip that explains why it is disabled. With a tooltip, the button stays focusable and is
// announced through aria-disabled instead, and its clicks (including Enter, Space and form
// submission) are cancelled here.
const focusableWhileDisabled = Boolean(disabled && tooltipLabel);

const handleClick: React.MouseEventHandler<HTMLButtonElement> = useCallback((event) => {
if (focusableWhileDisabled) {
event.preventDefault();
return;
}

onClick(event);

if (showFeedback) {
setFeedbackVisible(true);
if (feedbackTimeoutRef.current) clearTimeout(feedbackTimeoutRef.current);
feedbackTimeoutRef.current = setTimeout(() => setFeedbackVisible(false), feedbackDuration);
}
}, [onClick, showFeedback, feedbackDuration]);
}, [focusableWhileDisabled, onClick, showFeedback, feedbackDuration]);

const labelRef = useRef<HTMLSpanElement>(null);
const [isLabelTruncated, setLabelTruncated] = useState(false);
Expand All @@ -97,6 +108,7 @@ function Button(props: ButtonProps): JSX.Element {
} = {};
const generatedId = useId();
const defaultLabelId = `${id || generatedId}-label`;
const tooltipDescriptionId = `${id || generatedId}-tooltip`;
// Only default aria-labelledby to defaultLabelId when an element with that id is
// actually rendered (stacked always renders ButtonText; default when labeled, or
// when the feedback content is taking the label's place). circle never renders a
Expand All @@ -110,7 +122,18 @@ function Button(props: ButtonProps): JSX.Element {
} else if (hasRenderedLabelElement) {
accessibilityProps['aria-labelledby'] = defaultLabelId;
}
if (ariaDescribedBy) accessibilityProps['aria-describedby'] = ariaDescribedBy;
const describedBy = [ariaDescribedBy, tooltipLabel && tooltipDescriptionId].filter(Boolean).join(' ');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

An icon-only button with only a tooltipLabel (no label or ariaLabel) ends up with no name and the tooltip as its description. Same rule as BBBCheckbox/BBBToggle: when nothing else names it, point aria-labelledby at the tooltip span instead.

if (describedBy) accessibilityProps['aria-describedby'] = describedBy;

const disabledProps = {
disabled: disabled && !focusableWhileDisabled,
'aria-disabled': focusableWhileDisabled || undefined,
};

// aria-describedby needs the text at all times; Tippy mounts it only while shown.
const tooltipDescription = tooltipLabel && (
<span id={tooltipDescriptionId} hidden>{tooltipLabel}</span>
);

const buttonElement = (() => {
if (props.layout === LAYOUTS.CIRCLE || props.layout === LAYOUTS.SQUARED) {
Expand All @@ -130,13 +153,14 @@ function Button(props: ButtonProps): JSX.Element {
$variant={variant}
$size={size}
$layout={layout}
disabled={disabled}
{...disabledProps}
>
{isFeedbackVisible ? (
<Styled.FeedbackContent role="status" aria-live="polite">
{feedbackContent}
</Styled.FeedbackContent>
) : icon}
{tooltipDescription}
</Styled.Button>
);
}
Expand Down Expand Up @@ -166,7 +190,7 @@ function Button(props: ButtonProps): JSX.Element {
$variant={variant}
$size={size}
$layout={layout}
disabled={disabled}
{...disabledProps}
>
{!hideHelperIcon && (
<Styled.HelperIconContainer
Expand All @@ -175,11 +199,11 @@ function Button(props: ButtonProps): JSX.Element {
{...(helperOnClick && { 'data-is-aux-icon': true })}
{...(helperOnClick && { 'aria-label': accessibilityProps['aria-label'] + ' helper' })}
{...(helperOnClick && { role: "button" })}
$hover={helperOnClick !== null}
$hover={helperOnClick !== null && !disabled}
$color={color}
$variant={variant}
onClick={(event) => {
if (helperOnClick) {
if (helperOnClick && !disabled) {
helperOnClick(event);
event.preventDefault();
event.stopPropagation();
Expand All @@ -196,6 +220,7 @@ function Button(props: ButtonProps): JSX.Element {
</Styled.FeedbackContent>
</Styled.IconWrapper>
) : (icon && <Styled.IconWrapper>{icon}</Styled.IconWrapper>)}
{tooltipDescription}
</Styled.Button>
<Styled.ButtonText id={defaultLabelId}>{label}</Styled.ButtonText>
</Styled.ButtonWrapper>
Expand All @@ -220,7 +245,7 @@ function Button(props: ButtonProps): JSX.Element {
$layout={layout}
$fullWidth={fullWidth}
$labelOverflow={labelOverflow}
disabled={disabled}
{...disabledProps}
>
{isFeedbackVisible ? (
<Styled.FeedbackContent id={defaultLabelId} role="status" aria-live="polite">
Expand All @@ -238,12 +263,11 @@ function Button(props: ButtonProps): JSX.Element {
{iconEnd && iconEnd}
</>
)}
{tooltipDescription}
</Styled.Button>
);
})();

// The truncated-label tooltip repeats text that is already the accessible name
// (via aria-labelledby), so it must not also be announced as a description.
const showsTruncatedLabelTooltip = !tooltipLabel && truncatesLabel && Boolean(label);

if (tooltipLabel || showsTruncatedLabelTooltip) {
Expand All @@ -253,7 +277,12 @@ function Button(props: ButtonProps): JSX.Element {
placement={tooltipPlacement}
plugins={TOOLTIP_PLUGINS}
disabled={showsTruncatedLabelTooltip && !isLabelTruncated}
aria={{ content: showsTruncatedLabelTooltip ? null : 'auto' }}
// In the 'stacked' layout the reference is the wrapper, which focus never lands on;
// `focusin` bubbles up from the button, Tippy's `focus` would not.
trigger="mouseenter focusin"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Adding or removing tooltipLabel swaps the root between <button> and <Tippy>, so React remounts the button. With the issue's pattern (tooltipLabel only while disabled), a Start button that disables itself after Enter, or a disabled one that becomes enabled while focused, drops focus to <body>. Same fix as in #117/#118: render Tippy beside the button and point it at the root.

const buttonRef = useRef<HTMLButtonElement>(null); // ref={buttonRef} on both Styled.Button roots
const wrapperRef = useRef<HTMLDivElement>(null);   // ref={wrapperRef} on Styled.ButtonWrapper
// …
return (
  <>
    {buttonElement}
    {(tooltipLabel || showsTruncatedLabelTooltip) && (
      <Tippy
        reference={layout === LAYOUTS.STACKED ? wrapperRef : buttonRef}
        content={tooltipLabel || label}
        /* …same props as now */
      />
    )}
  </>
);

Focus stays put in all three browsers, and nothing else in my checks changes.

// The button is already described by `tooltipDescription`, and the truncated-label
// tooltip repeats its accessible name, so Tippy must not add aria-describedby.
aria={{ content: null }}
>
{buttonElement}
</Tippy>
Expand Down
64 changes: 33 additions & 31 deletions src/components/Button/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ import {
import { colorBorderDefault, colorTextDefault } from '../../stylesheets/palette';
import { fontSizeSmall } from '../../stylesheets/typography';

const {
color: disabledColor,
background: disabledBackground,
border: disabledBorder,
outline: disabledOutline,
} = CSS_COLOR_PROPERTIES_DISABLED;

// A disabled button with a tooltip is `aria-disabled` instead of natively disabled. It gets the
// same disabled look, but keeps pointer events so the tooltip opens on hover and the
// not-allowed cursor shows.
const commonButtonStyles = css<StyledButtonProps>`
cursor: pointer;
user-select: none;
Expand Down Expand Up @@ -61,11 +71,13 @@ const commonButtonStyles = css<StyledButtonProps>`
${background && `background-color: ${background};`}
${border ? `border: 1px solid ${border};` : 'border: 1px solid transparent;'}

&&:hover:not(:has(> [data-is-aux-icon]:hover)),
&&:active {
color: ${hoverColor};
${hoverBackground && `background-color: ${hoverBackground};`}
${hoverBorder ? `border: 1px solid ${hoverBorder};` : 'border: 1px solid transparent;'}
&&:not(:disabled):not([aria-disabled='true']) {
&:hover:not(:has(> [data-is-aux-icon]:hover)),
&:active {
color: ${hoverColor};
${hoverBackground && `background-color: ${hoverBackground};`}
${hoverBorder ? `border: 1px solid ${hoverBorder};` : 'border: 1px solid transparent;'}
}
}
&&:focus {
border: 1px solid transparent;
Expand All @@ -80,32 +92,22 @@ const commonButtonStyles = css<StyledButtonProps>`
text-decoration: underline;
`}

${({ disabled }) => {
if (!disabled) return null;
const { color, background, border, outline } = CSS_COLOR_PROPERTIES_DISABLED;

return css`
pointer-events: none;
cursor: not-allowed;
& span {
color: ${color};
}
color: ${color};
${background ? `background-color: ${background}` : `background-color: transparent`};
border: ${border ? `1px solid ${border}` : '1px solid transparent'};

&&:hover,
&&:active {
color: ${color};
${background ? `background-color: ${background}` : `background-color: transparent`};
border: ${border ? `1px solid ${border}` : '1px solid transparent'};
}

&&:focus {
outline: 2px solid ${outline};
}
`;
}}
&:disabled,
&[aria-disabled='true'] {
cursor: not-allowed;
& span {
color: ${disabledColor};
}
color: ${disabledColor};
${disabledBackground ? `background-color: ${disabledBackground}` : 'background-color: transparent'};
border: ${disabledBorder ? `1px solid ${disabledBorder}` : '1px solid transparent'};
}
&:disabled {
pointer-events: none;
}
&&[aria-disabled='true']:focus {
outline: 2px solid ${disabledOutline};
}
`;

const stackedLayoutStyles = css`
Expand Down
3 changes: 1 addition & 2 deletions src/components/Button/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ export interface StyledButtonProps {
$layout?: LayoutType;
$fullWidth?: boolean;
$labelOverflow?: LabelOverflowType;
disabled: boolean;
}

export interface StyledLabelProps {
Expand All @@ -81,7 +80,7 @@ type BaseButtonProps = {
/** Text label for the button; rendered in layouts that display a label (e.g. `default`, `stacked`). */
label?: string;

/** Text shown in a tooltip; the tooltip only renders when this is provided. */
/** Text shown in a tooltip on hover and keyboard focus; when set, a disabled button stays focusable (`aria-disabled`) so the tooltip can be reached. */
tooltipLabel?: string;

/** Placement of the tooltip relative to the button; only used when `tooltipLabel` is set. @default 'top' */
Expand Down
Loading