From 005114e87970ad027a93973658f5733e34a5eadb Mon Sep 17 00:00:00 2001 From: "lablup-quill[bot]" <353096427+lablup-quill[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:43:10 +0000 Subject: [PATCH] feat(Selector): show a truncated value's whole label in a tooltip Add showSelectedOptionTooltip, an opt-in prop that reads the selected option's full label on hover or focus when the trigger ellipsizes it. It shows only while the label is actually clipped, and stays off while nothing is selected, while the control is disabled, or while the listbox is open. The trigger tooltip is now shared with MultiSelector so both follow the trigger's own state the same way. --- CHANGELOG.md | 13 + .../MultiSelector/MultiSelector.tsx | 62 +--- .../Selector/Selector.stories.tsx | 21 ++ .../Selector/Selector.tooltip.test.tsx | 286 ++++++++++++++++++ src/formControls/Selector/Selector.tsx | 49 ++- src/formControls/triggerTooltip.tsx | 104 +++++++ 6 files changed, 475 insertions(+), 60 deletions(-) create mode 100644 src/formControls/Selector/Selector.tooltip.test.tsx create mode 100644 src/formControls/triggerTooltip.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index ed18d58cc..aee176f07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,19 @@ Versioning follows the policy in [CONTRIBUTING.md](CONTRIBUTING.md#versioning). sections) can read apart in the tooltip as they do on the trigger. `content` is never called while nothing is selected or the trigger is disabled. +- **`Selector`: `showSelectedOptionTooltip` reads a truncated value on the + trigger (#174).** The single-select trigger cuts a long label off with an + ellipsis, with no way to read it whole. With `showSelectedOptionTooltip`, + hovering or focusing the trigger shows the selected option's whole label in + a `Tooltip`, from `options` (sections included), and only while the trigger + actually clips it: a label that fits adds no tooltip. There is none while + nothing is selected, while the control is disabled (its `disabledMessage` + keeps the trigger), or while the listbox is open, and `onOpenChange` is + still called. The tooltip's id joins the trigger's `aria-describedby` beside + the caller's. Off by default, so existing call sites render as before. The + tooltip follows the trigger's own disabled and open state exactly as + `MultiSelector`'s `showSelectedOptionsTooltip` does, through one shared + implementation. ### Fixed diff --git a/src/formControls/MultiSelector/MultiSelector.tsx b/src/formControls/MultiSelector/MultiSelector.tsx index 1a31682c9..51a07b4f9 100644 --- a/src/formControls/MultiSelector/MultiSelector.tsx +++ b/src/formControls/MultiSelector/MultiSelector.tsx @@ -9,7 +9,7 @@ * `showSelectedOptionsTooltip` lists the selected labels in a tooltip on the trigger, or * renders the caller's `content` for the selection. */ -import { useLayoutEffect, useState, type ReactNode } from "react"; +import { useState, type ReactNode } from "react"; import { MultiSelector as AstryxMultiSelector, type MultiSelectorDivider, @@ -22,8 +22,8 @@ import { import { useMergedRefs } from "@astryxdesign/core/hooks"; import type { SelectorOptionType } from "@astryxdesign/core/Selector"; import { getSelectableOptions } from "@astryxdesign/core/Selector/utils"; -import { useTooltip } from "@astryxdesign/core/Tooltip"; +import { TriggerTooltip } from "../triggerTooltip"; import { EMPTY_ARRAY, FormControlScope, @@ -171,7 +171,7 @@ export function MultiSelector< {hasTooltip && showSelectedOptionsTooltip && trigger ? ( - tooltipContent( @@ -194,59 +194,3 @@ function tooltipContent( return items.map((item) => item.label).join(", "); return showSelectedOptionsTooltip.content(items); } - -/** What the tooltip needs from the trigger: disabled, and the listbox open. */ -const readTrigger = (trigger: HTMLElement) => ({ - // A disabled InputGroup disables the trigger through context Astryx does not - // export; the trigger's aria-disabled is where it shows. - isDisabled: trigger.getAttribute("aria-disabled") === "true", - isExpanded: trigger.getAttribute("aria-expanded") === "true", -}); - -/** - * The selection tooltip, mounted only with `showSelectedOptionsTooltip`. It follows the - * trigger's own attributes, so it is held shut while the listbox is open and - * absent while the trigger is disabled, from the first commit on. - */ -function SelectionTooltip({ - trigger, - renderContent, - onDescribedBy, -}: { - trigger: HTMLElement; - /** Called only while the tooltip is enabled, so a disabled trigger never runs it. */ - renderContent: () => ReactNode; - onDescribedBy: (id: string | undefined) => void; -}) { - const [state, setState] = useState(() => readTrigger(trigger)); - useLayoutEffect(() => { - const sync = () => - setState((prev) => { - const next = readTrigger(trigger); - return prev.isDisabled === next.isDisabled && - prev.isExpanded === next.isExpanded - ? prev - : next; - }); - sync(); - const observer = new MutationObserver(sync); - observer.observe(trigger, { attributeFilter: ["aria-disabled", "aria-expanded"] }); - return () => observer.disconnect(); - }, [trigger]); - const isEnabled = !state.isDisabled; - const tooltip = useTooltip({ - isEnabled, - isOpen: state.isExpanded ? false : undefined, - }); - const attach = tooltip.ref; - useLayoutEffect( - () => (isEnabled ? attach(trigger) : undefined), - [attach, trigger, isEnabled], - ); - const { describedBy } = tooltip; - useLayoutEffect(() => { - onDescribedBy(isEnabled ? describedBy : undefined); - return () => onDescribedBy(undefined); - }, [onDescribedBy, describedBy, isEnabled]); - return isEnabled ? tooltip.renderTooltip(renderContent()) : null; -} diff --git a/src/formControls/Selector/Selector.stories.tsx b/src/formControls/Selector/Selector.stories.tsx index b049eb558..73464aa04 100644 --- a/src/formControls/Selector/Selector.stories.tsx +++ b/src/formControls/Selector/Selector.stories.tsx @@ -88,6 +88,27 @@ export const DisabledOptionReason: Story = { }, }; +/** + * `showSelectedOptionTooltip`: hover or focus the trigger to read the selected + * option's whole label when the trigger cuts it short with an ellipsis. A label + * that fits shows no tooltip, and neither does an empty or disabled control. + */ +export const ShowTruncatedValueTooltip: Story = { + decorators: [withMaxWidth(200)], + args: { + showSelectedOptionTooltip: true, + options: [ + { value: "north", label: "North" }, + { value: "south", label: "South" }, + { + value: "ap-northeast-2", + label: "ap-northeast-2 (Seoul, South Korea)", + }, + ], + defaultValue: "ap-northeast-2", + }, +}; + /** On its own, disabled. */ export const Disabled: Story = { args: { disabled: true }, diff --git a/src/formControls/Selector/Selector.tooltip.test.tsx b/src/formControls/Selector/Selector.tooltip.test.tsx new file mode 100644 index 000000000..c52bf7c01 --- /dev/null +++ b/src/formControls/Selector/Selector.tooltip.test.tsx @@ -0,0 +1,286 @@ +/** + * `showSelectedOptionTooltip`: the selected option's full label on the trigger, + * shown on hover or focus only while the trigger clips it with an ellipsis, + * held shut while the listbox is open, and absent when it has nothing to say. + */ +import { act, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { Selector } from "./Selector"; + +const originalMatches = HTMLElement.prototype.matches; +const originalScrollWidth = Object.getOwnPropertyDescriptor( + HTMLElement.prototype, + "scrollWidth", +); +const originalClientWidth = Object.getOwnPropertyDescriptor( + HTMLElement.prototype, + "clientWidth", +); + +/** The trigger label's sizes, or `null` while it fits. jsdom reports 0 for both. */ +let clipped: { scrollWidth: number; clientWidth: number } | null = null; + +const isTriggerLabel = (element: HTMLElement) => + element.tagName === "SPAN" && element.closest('[role="combobox"]') != null; + +beforeEach(() => { + // jsdom has no Popover API: Astryx's own mock, which marks an open popover. + HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) { + this.setAttribute("popover-open", ""); + const event = new Event("toggle"); + Object.defineProperty(event, "newState", { value: "open" }); + this.dispatchEvent(event); + }); + HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) { + this.removeAttribute("popover-open"); + const event = new Event("toggle"); + Object.defineProperty(event, "newState", { value: "closed" }); + this.dispatchEvent(event); + }); + vi.spyOn(HTMLElement.prototype, "matches").mockImplementation(function ( + this: HTMLElement, + selector: string, + ) { + if (selector === ":popover-open") return this.hasAttribute("popover-open"); + // jsdom does not match :focus-visible; the tooltip opens on focused triggers. + if (selector === ":focus-visible") return document.activeElement === this; + return originalMatches.call(this, selector); + }); + Element.prototype.scrollIntoView = vi.fn(); + + clipped = null; + Object.defineProperty(HTMLElement.prototype, "scrollWidth", { + configurable: true, + get(this: HTMLElement) { + return clipped && isTriggerLabel(this) ? clipped.scrollWidth : 0; + }, + }); + Object.defineProperty(HTMLElement.prototype, "clientWidth", { + configurable: true, + get(this: HTMLElement) { + return clipped && isTriggerLabel(this) ? clipped.clientWidth : 0; + }, + }); +}); + +afterEach(() => { + vi.restoreAllMocks(); + restoreSize("scrollWidth", originalScrollWidth); + restoreSize("clientWidth", originalClientWidth); +}); + +/** Put back the size getter this file shadowed on `HTMLElement.prototype`. */ +function restoreSize( + name: "scrollWidth" | "clientWidth", + original: PropertyDescriptor | undefined, +) { + if (original) { + Object.defineProperty(HTMLElement.prototype, name, original); + } else { + delete (HTMLElement.prototype as Partial)[name]; + } +} + +const OPTIONS = [ + { value: "north", label: "North" }, + { value: "south", label: "A long southern region name" }, +]; + +const trigger = () => screen.getByRole("combobox", { name: "Region" }); +const tooltip = () => screen.queryByRole("tooltip", { hidden: true }); + +describe("Selector showSelectedOptionTooltip", () => { + it("shows the selected label on hover when the trigger clips it", async () => { + const user = userEvent.setup(); + clipped = { scrollWidth: 200, clientWidth: 100 }; + render( + , + ); + await waitFor(() => + expect(tooltip()).toHaveTextContent("A long southern region name"), + ); + + await user.hover(trigger()); + await waitFor(() => expect(tooltip()).toHaveAttribute("popover-open")); + }); + + it("shows it on keyboard focus too", async () => { + clipped = { scrollWidth: 200, clientWidth: 100 }; + render( + , + ); + await waitFor(() => expect(tooltip()).not.toBeNull()); + + act(() => trigger().focus()); + await waitFor(() => expect(tooltip()).toHaveAttribute("popover-open")); + }); + + it("is absent while the label fits", () => { + render( + , + ); + expect(tooltip()).toBeNull(); + expect(trigger()).not.toHaveAttribute("aria-describedby"); + }); + + it("follows the value: it appears when a longer one clips, and goes when it fits", async () => { + const { rerender } = render( + , + ); + expect(tooltip()).toBeNull(); + + clipped = { scrollWidth: 200, clientWidth: 100 }; + rerender( + , + ); + await waitFor(() => + expect(tooltip()).toHaveTextContent("A long southern region name"), + ); + + clipped = null; + rerender( + , + ); + await waitFor(() => expect(tooltip()).toBeNull()); + expect(trigger()).not.toHaveAttribute("aria-describedby"); + }); + + it("joins the caller's aria-describedby with the tooltip's id", async () => { + clipped = { scrollWidth: 200, clientWidth: 100 }; + render( + , + ); + await waitFor(() => expect(tooltip()).not.toBeNull()); + expect(trigger().getAttribute("aria-describedby")?.split(" ")).toEqual( + expect.arrayContaining(["hint", tooltip()!.id]), + ); + }); + + it("shows nothing with no selection, when disabled, or when off", async () => { + clipped = { scrollWidth: 200, clientWidth: 100 }; + const { rerender } = render( + , + ); + expect(tooltip()).toBeNull(); + + rerender( + , + ); + expect(tooltip()).toBeNull(); + expect(trigger()).not.toHaveAttribute("aria-describedby"); + + rerender(); + expect(tooltip()).toBeNull(); + expect(trigger()).not.toHaveAttribute("aria-describedby"); + }); + + it("stays shut while the listbox is open", async () => { + const user = userEvent.setup(); + clipped = { scrollWidth: 200, clientWidth: 100 }; + render( + , + ); + await waitFor(() => expect(tooltip()).not.toBeNull()); + + await user.click(trigger()); + await waitFor(() => expect(trigger()).toHaveAttribute("aria-expanded", "true")); + await waitFor(() => expect(tooltip()).not.toHaveAttribute("popover-open")); + + await user.unhover(trigger()); + await user.hover(trigger()); + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(tooltip()).not.toHaveAttribute("popover-open"); + }); + + it("falls back to the value for an option with no label, and resolves sections", async () => { + clipped = { scrollWidth: 200, clientWidth: 100 }; + render( + , + ); + await waitFor(() => expect(tooltip()).toHaveTextContent("bare")); + }); + + it("does not re-attach the caller's callback ref on re-render", async () => { + clipped = { scrollWidth: 200, clientWidth: 100 }; + const ref = vi.fn(); + const { rerender } = render( + , + ); + rerender( + , + ); + expect(ref).toHaveBeenCalledTimes(1); + expect(ref).toHaveBeenCalledWith(trigger()); + }); +}); diff --git a/src/formControls/Selector/Selector.tsx b/src/formControls/Selector/Selector.tsx index a25d41ec4..bbcd71d90 100644 --- a/src/formControls/Selector/Selector.tsx +++ b/src/formControls/Selector/Selector.tsx @@ -9,8 +9,11 @@ * `onOpenChange` is MultiSelector's, which Astryx's Selector lacks: the * wrapper watches the trigger's `aria-expanded`, which follows the panel * however it opens or closes, and calls it on each change. + * + * `showSelectedOptionTooltip` reads the selected option's full label on the + * trigger when the trigger cuts it off with an ellipsis (../triggerTooltip). */ -import { useEffect, useRef, type Ref } from "react"; +import { useEffect, useMemo, useRef, useState, type Ref } from "react"; import { useMergedRefs } from "@astryxdesign/core/hooks"; import { @@ -22,6 +25,7 @@ import { type SelectorProps as AstryxSelectorProps, type SelectorSection as AstryxSelectorSection, } from "@astryxdesign/core/Selector"; +import { getSelectableOptions } from "@astryxdesign/core/Selector/utils"; import { FormControlScope, @@ -31,6 +35,7 @@ import { type FormControlValueProps, } from "../formControl"; import { withOptionDisabledReason, type OptionDisabled } from "../optionDisabledReason"; +import { TriggerTooltip, useClippedContent } from "../triggerTooltip"; /** Astryx's option, with `disabled` also taking `{ reason }`. */ export type SelectorOptionData = Omit & { @@ -55,6 +60,14 @@ export type SelectorProps = * trigger, the keyboard, a light dismiss or Escape. As MultiSelector's. */ onOpenChange?: (isOpen: boolean) => void; + /** + * A tooltip on the trigger with the selected option's full label, shown on + * hover or on focus (the keyboard's included) while the trigger cuts the + * label off with an ellipsis. None while nothing is selected, while the + * control is disabled, or while the listbox is open. + * @default false + */ + showSelectedOptionTooltip?: boolean; }; /** Calls `onOpenChange` when the trigger's `aria-expanded` changes. */ @@ -92,13 +105,20 @@ export function Selector({ status, disabled, options, + showSelectedOptionTooltip = false, onOpenChange, ...rest }: SelectorProps) { const openChangeRef = useOpenChange(onOpenChange); + // Only with showSelectedOptionTooltip: the trigger element (state, so the + // tooltip follows a replaced element) and the tooltip's id, which + // TriggerTooltip reports. + const [trigger, setTrigger] = useState(null); + const [tooltipId, setTooltipId] = useState(); const triggerRef = useMergedRefs( rest.ref as Ref | undefined, openChangeRef, + showSelectedOptionTooltip ? setTrigger : undefined, ); const { required, field, width } = useFormControl({ component: "Selector", @@ -116,6 +136,20 @@ export function Selector({ onChange, undefined, ); + // Astryx resolves the trigger's label from the same option list; a value + // with no option has no trigger label and so no tooltip to show. + const selectedOption = useMemo( + () => + mergedValue == null + ? undefined + : getSelectableOptions(options as AstryxSelectorOptionType[]).find( + (option) => option.value === mergedValue, + ), + [options, mergedValue], + ); + const hasTooltip = + !!showSelectedOptionTooltip && !!selectedOption && !field.isDisabled; + const isClipped = useClippedContent(trigger, hasTooltip); const reasoned = withOptionDisabledReason({ options, renderOption: rest.renderOption, @@ -140,10 +174,23 @@ export function Selector({ onChange: handleChange, renderOption: reasoned.renderOption, ref: triggerRef, + // React owns the attribute: the tooltip's id joins the caller's here. + ...(tooltipId && { + "aria-describedby": [rest["aria-describedby"], tooltipId] + .filter(Boolean) + .join(" "), + }), } as unknown as AstryxSelectorProps; return ( + {hasTooltip && trigger && isClipped ? ( + selectedOption?.label ?? selectedOption?.value ?? ""} + onDescribedBy={setTooltipId} + /> + ) : null} ); } diff --git a/src/formControls/triggerTooltip.tsx b/src/formControls/triggerTooltip.tsx new file mode 100644 index 000000000..4902e4a8e --- /dev/null +++ b/src/formControls/triggerTooltip.tsx @@ -0,0 +1,104 @@ +/** + * The tooltip on a select control's trigger, shared by `Selector` and + * `MultiSelector`. It follows the trigger's own attributes, so it is held shut + * while the listbox is open and absent while the trigger is disabled, from the + * first commit on. + */ +import { useLayoutEffect, useState, type ReactNode } from "react"; +import { useTooltip } from "@astryxdesign/core/Tooltip"; + +/** What the tooltip needs from the trigger: disabled, and the listbox open. */ +const readTrigger = (trigger: HTMLElement) => ({ + // A disabled InputGroup disables the trigger through context Astryx does not + // export; the trigger's aria-disabled is where it shows. + isDisabled: trigger.getAttribute("aria-disabled") === "true", + isExpanded: trigger.getAttribute("aria-expanded") === "true", +}); + +export function TriggerTooltip({ + trigger, + renderContent, + onDescribedBy, +}: { + trigger: HTMLElement; + /** Called only while the tooltip is enabled, so a disabled trigger never runs it. */ + renderContent: () => ReactNode; + onDescribedBy: (id: string | undefined) => void; +}) { + const [state, setState] = useState(() => readTrigger(trigger)); + useLayoutEffect(() => { + const sync = () => + setState((prev) => { + const next = readTrigger(trigger); + return prev.isDisabled === next.isDisabled && + prev.isExpanded === next.isExpanded + ? prev + : next; + }); + sync(); + const observer = new MutationObserver(sync); + observer.observe(trigger, { attributeFilter: ["aria-disabled", "aria-expanded"] }); + return () => observer.disconnect(); + }, [trigger]); + const isEnabled = !state.isDisabled; + const tooltip = useTooltip({ + isEnabled, + isOpen: state.isExpanded ? false : undefined, + }); + const attach = tooltip.ref; + useLayoutEffect( + () => (isEnabled ? attach(trigger) : undefined), + [attach, trigger, isEnabled], + ); + const { describedBy } = tooltip; + useLayoutEffect(() => { + onDescribedBy(isEnabled ? describedBy : undefined); + return () => onDescribedBy(undefined); + }, [onDescribedBy, describedBy, isEnabled]); + return isEnabled ? tooltip.renderTooltip(renderContent()) : null; +} + +/** + * Whether anything inside `trigger` is clipped: an element whose content is + * wider than the box it shows. The trigger's label ellipsizes and + * `renderValue`'s wrapper clips, so a wider scroll box than client box is the + * sign a value is cut off. + */ +export function hasClippedContent(trigger: HTMLElement): boolean { + return Array.from(trigger.querySelectorAll("*")).some( + (element) => element.clientWidth > 0 && element.scrollWidth > element.clientWidth, + ); +} + +/** + * `hasClippedContent` for a trigger, kept current: a resize of the trigger or + * a change to what it shows remeasures, so the answer follows the layout and + * the value without the caller tracking either. + */ +export function useClippedContent( + trigger: HTMLElement | null, + isEnabled: boolean, +): boolean { + const [isClipped, setIsClipped] = useState(false); + useLayoutEffect(() => { + if (!trigger || !isEnabled) { + setIsClipped(false); + return; + } + const measure = () => setIsClipped(hasClippedContent(trigger)); + measure(); + const resizeObserver = new ResizeObserver(measure); + resizeObserver.observe(trigger); + const mutationObserver = new MutationObserver(measure); + mutationObserver.observe(trigger, { + childList: true, + characterData: true, + subtree: true, + }); + return () => { + resizeObserver.disconnect(); + mutationObserver.disconnect(); + }; + }, [trigger, isEnabled]); + return isClipped; +}