A platform for community discussion. Free, open, simple.
DEV: Add a `DTabs` ui-kit primitive on a shared scroll strip (#43108)
Sérgio Saquetimed65dfa58f65
diff --git a/app/assets/stylesheets/common/base/review.scss b/app/assets/stylesheets/common/base/review.scssindex beffe5b43b9..9b46e23205f 100644--- a/app/assets/stylesheets/common/base/review.scss+++ b/app/assets/stylesheets/common/base/review.scss@@ -329,9 +329,14 @@&__insights {padding-inline: var(--review-item-padding);+ // The border goes on the nav, not the ul: the ul is the strip's scroller+ // and its edge fade would mask a border painted there.+ .horizontal-overflow-nav {+ border-bottom: 1px solid var(--content-border-color);+ }+.nav-pills.action-list {margin-bottom: 0;- border-bottom: 1px solid var(--content-border-color);}}diff --git a/app/assets/stylesheets/common/components/d-overflow-controls.scss b/app/assets/stylesheets/common/components/d-overflow-controls.scssindex d050f48641d..79f71131ef5 100644--- a/app/assets/stylesheets/common/components/d-overflow-controls.scss+++ b/app/assets/stylesheets/common/components/d-overflow-controls.scss@@ -1,20 +1,23 @@.d-overflow-controls {--fade-width: 2rem;--fade-color: var(--secondary);++ // rem, because the button and the scroller resolve the value separately+ // and their font sizes can differ.+ --d-overflow-controls-btn-size: 1.5rem;position: relative;min-width: 0;min-height: 0;- &__content {- scrollbar-width: none;- -ms-overflow-style: none;-- // keep scroll-into-view targets clear of the edge fade/chevron buttons- scroll-padding: var(--fade-width);+ // The chevron is positioned against this wrapper, so it sits over the+ // strip's edge and the fade starts beyond it. Pad this wrapper on a+ // scrolling edge and that stops being true; pad the scroller instead.+ > [data-d-scroll-axis] {+ --fade-inset: var(--d-overflow-controls-btn-size);+ }- &::-webkit-scrollbar {- display: none;- }+ &__content {+ @include scroll-strip;}&__btn {@@ -25,8 +28,11 @@display: flex;align-items: center;justify-content: center;+ padding: 0;cursor: pointer;color: var(--primary-high);+ user-select: none;+ -webkit-touch-callout: none;&:hover {color: var(--primary);@@ -36,36 +42,22 @@&.--right {top: 0;bottom: 0;+ width: var(--d-overflow-controls-btn-size);margin-block: 1px;- padding: 0 var(--space-1);}&.--up,&.--down {left: 0;right: 0;+ height: var(--d-overflow-controls-btn-size);margin-inline: 1px;- padding: var(--space-1) 0;}&.--left {/*! rtl:ignore */left: 0;- &::after {- content: "";- position: absolute;-- /*! rtl:ignore */- left: 100%;- height: 100%;- width: var(--fade-width);-- /*! rtl:ignore */- background: linear-gradient(to right, var(--fade-color), transparent);- pointer-events: none;- }-// Undo automatic icon flip since button stays in physical position.rtl & .d-icon {transform: scaleX(1);@@ -76,20 +68,6 @@/*! rtl:ignore */right: 0;- &::before {- content: "";- position: absolute;-- /*! rtl:ignore */- right: 100%;- height: 100%;- width: var(--fade-width);-- /*! rtl:ignore */- background: linear-gradient(to left, var(--fade-color), transparent);- pointer-events: none;- }-// Undo automatic icon flip since button stays in physical position.rtl & .d-icon {transform: scaleX(1);@@ -98,30 +76,10 @@&.--up {top: 0;-- &::after {- content: "";- position: absolute;- top: 100%;- width: 100%;- height: var(--fade-width);- background: linear-gradient(to bottom, var(--fade-color), transparent);- pointer-events: none;- }}&.--down {bottom: 0;-- &::before {- content: "";- position: absolute;- bottom: 100%;- width: 100%;- height: var(--fade-width);- background: linear-gradient(to top, var(--fade-color), transparent);- pointer-events: none;- }}}}diff --git a/app/assets/stylesheets/common/components/emoji-picker.scss b/app/assets/stylesheets/common/components/emoji-picker.scssindex 5ebdf9534e1..cca10ea4c52 100644--- a/app/assets/stylesheets/common/components/emoji-picker.scss+++ b/app/assets/stylesheets/common/components/emoji-picker.scss@@ -127,6 +127,7 @@&__sections-nav-wrap {--fade-color: var(--primary-low);+ background: var(--primary-low);flex: 0 0 auto;@include viewport.until(sm) {@@ -142,9 +143,6 @@overflow-y: auto;overflow-x: hidden;height: 250px;- background: var(--primary-low);- -ms-overflow-style: none; /* IE and Edge */- scrollbar-width: none; /* Firefox */overscroll-behavior: contain;@include viewport.until(sm) {@@ -158,10 +156,6 @@}}- &__sections-nav::-webkit-scrollbar {- display: none;- }-&__section-btn {padding: 0.25rem;diff --git a/app/assets/stylesheets/common/components/horizontal-overflow-nav.scss b/app/assets/stylesheets/common/components/horizontal-overflow-nav.scssindex a2a1d79bcc1..f7e010f6e8b 100644--- a/app/assets/stylesheets/common/components/horizontal-overflow-nav.scss+++ b/app/assets/stylesheets/common/components/horizontal-overflow-nav.scss@@ -1,100 +1,22 @@.horizontal-overflow-nav {- position: relative;min-width: 0;width: 100%;.nav-pills {- overflow: auto;- min-width: 0;+ @include horizontal-scroll-strip;margin: 0;height: 100%;position: relative;-- // avoids auto-scroll on initial load if active nav item is overflowed- scroll-behavior: auto;-- // hides scrollbars, but allows mouse scrolling- scrollbar-width: none;-- &::-webkit-scrollbar {- height: 0;- }- }-- &.has-scroll {- .nav-pills {- scroll-behavior: smooth; // smooth scrolling on user interaction- }}}-.horizontal-overflow-nav__scroll-right,-.horizontal-overflow-nav__scroll-left {+// Chained to outrank the primitive's own declaration on the same element.+.d-overflow-controls.horizontal-overflow-nav__controls {--fade-width: 1.5em;- --fade-color: var(--secondary);- opacity: 1;- position: absolute;- z-index: 2;- background-color: var(--secondary);- top: 0;- bottom: 0;- display: flex;- align-items: center;- transition: opacity 0.25s;+ height: 100%;- .d-icon {- pointer-events: none;- margin-bottom: 0.2em;+ .d-overflow-controls__btn .d-icon {color: var(--d-nav-color--active);- }-- &.disabled {- // hiding with opacity so we can transition visibility- opacity: 0;- pointer-events: none;- }-}--.horizontal-overflow-nav__scroll-right {- /*! rtl:ignore */- right: 0;-- &::before {- content: "";-- /*! rtl:ignore */- margin-left: calc(var(--fade-width) * -1);- height: 100%;- width: var(--fade-width);-- /*! rtl:ignore */- background: linear-gradient(to left, var(--fade-color), transparent);- }-- // Undo automatic icon flip since button stays in physical position- .rtl & .d-icon {- transform: scaleX(1);- }-}--.horizontal-overflow-nav__scroll-left {- /*! rtl:ignore */- left: 0;-- &::after {- content: "";-- /*! rtl:ignore */- margin-right: calc(var(--fade-width) * -1);- height: 100%;- width: var(--fade-width);-- /*! rtl:ignore */- background: linear-gradient(to right, var(--fade-color), transparent);- }-- // Undo automatic icon flip since button stays in physical position- .rtl & .d-icon {- transform: scaleX(1);+ margin-bottom: 0.2em;}}diff --git a/app/assets/stylesheets/common/d-editor.scss b/app/assets/stylesheets/common/d-editor.scssindex b3e50faa24a..e9c8a256d7f 100644--- a/app/assets/stylesheets/common/d-editor.scss+++ b/app/assets/stylesheets/common/d-editor.scss@@ -334,8 +334,6 @@padding-block: var(--space-1);overflow-x: auto;overflow-y: hidden;- scrollbar-width: none;- -ms-overflow-style: none;max-width: 100%;// the toolbar can be rendered outside .d-editor-textarea-wrapper, so the@@ -345,10 +343,6 @@pointer-events: none;}- &::-webkit-scrollbar {- display: none;- }-.btn:focus-visible {@include default-focus;}diff --git a/app/assets/stylesheets/common/foundation/mixins.scss b/app/assets/stylesheets/common/foundation/mixins.scssindex 99aac6bd18c..e8678d95b8f 100644--- a/app/assets/stylesheets/common/foundation/mixins.scss+++ b/app/assets/stylesheets/common/foundation/mixins.scss@@ -284,6 +284,13 @@ $hpad: 0.65em;right: 0;height: var(--d-nav-underline-height);background: var(--d-nav-color--active);++ // Forced colors drop backgrounds, which is the only thing that marks+ // the active item.+ @media (forced-colors: active) {+ background: Highlight;+ forced-color-adjust: none;+ }}}@@ -296,6 +303,121 @@ $hpad: 0.65em;}}+// A strip that hides its scrollbar and fades the edge beyond which more+// content lies. The fade reads the data-d-scroll-* attributes stamped by+// the scroll-edges watcher, which DOverflowControls and the dScrollEdges+// modifier both run. The band starts fully transparent across --fade-inset+// so strip content never shows through a chevron parked on the edge, which+// assumes the chevron covers that band: a wrapper that pads the scroller's+// scrolling edge moves the chevron off it and hides content under nothing.+// #000 is deliberate: a mask reads only alpha, so a colour token would be+// wrong here.+@mixin scroll-strip() {+ // The bands are capped so the two ends cannot cross on a narrow strip.+ // Crossed bands leave no opaque middle.+ --scroll-strip-fade-start: min(var(--fade-inset, 0px), 15%);+ --scroll-strip-fade-end: min(+ calc(var(--fade-inset, 0px) + var(--fade-width, 2em)),+ 40%+ );+ min-width: 0;+ min-height: 0;+ scrollbar-width: none;+ scroll-padding: calc(var(--fade-inset, 0px) + var(--fade-width, 2em));++ &::-webkit-scrollbar {+ display: none;+ }++ // Forced colors drop the mask, which would otherwise lower text contrast+ // for exactly the users who opted out of decoration.+ @media (forced-colors: none) {+ &[data-d-scroll-axis="horizontal"][data-d-scroll-overflow] {+ mask-image: linear-gradient(+ to right,+ transparent var(--scroll-strip-fade-start),+ #000 var(--scroll-strip-fade-end),+ #000 calc(100% - var(--scroll-strip-fade-end)),+ transparent calc(100% - var(--scroll-strip-fade-start))+ );++ // The edges are logical, the gradients physical, so RTL swaps them.+ &[data-d-scroll-at-start] {+ mask-image: linear-gradient(+ to right,+ #000 calc(100% - var(--scroll-strip-fade-end)),+ transparent calc(100% - var(--scroll-strip-fade-start))+ );++ .rtl & {+ mask-image: linear-gradient(+ to left,+ #000 calc(100% - var(--scroll-strip-fade-end)),+ transparent calc(100% - var(--scroll-strip-fade-start))+ );+ }+ }++ &[data-d-scroll-at-end] {+ mask-image: linear-gradient(+ to right,+ transparent var(--scroll-strip-fade-start),+ #000 var(--scroll-strip-fade-end)+ );++ .rtl & {+ mask-image: linear-gradient(+ to left,+ transparent var(--scroll-strip-fade-start),+ #000 var(--scroll-strip-fade-end)+ );+ }+ }+ }++ &[data-d-scroll-axis="vertical"][data-d-scroll-overflow] {+ mask-image: linear-gradient(+ to bottom,+ transparent var(--scroll-strip-fade-start),+ #000 var(--scroll-strip-fade-end),+ #000 calc(100% - var(--scroll-strip-fade-end)),+ transparent calc(100% - var(--scroll-strip-fade-start))+ );++ &[data-d-scroll-at-start] {+ mask-image: linear-gradient(+ to bottom,+ #000 calc(100% - var(--scroll-strip-fade-end)),+ transparent calc(100% - var(--scroll-strip-fade-start))+ );+ }++ &[data-d-scroll-at-end] {+ mask-image: linear-gradient(+ to bottom,+ transparent var(--scroll-strip-fade-start),+ #000 var(--scroll-strip-fade-end)+ );+ }+ }++ // The .rtl copy only exists to outrank the .rtl at-start/at-end rules+ // above, which score a class higher than the bare selector.+ &[data-d-scroll-overflow][data-d-scroll-at-start][data-d-scroll-at-end],+ .rtl+ &[data-d-scroll-overflow][data-d-scroll-at-start][data-d-scroll-at-end] {+ mask-image: none;+ }+ }+}++// The scroll strip on the horizontal axis. The caller keeps its own items+// on one row; the mixin does not.+@mixin horizontal-scroll-strip() {+ @include scroll-strip;+ overflow-x: auto;+}+@mixin click-counter-badge {content: attr(data-clicks);font-weight: normal;diff --git a/app/assets/stylesheets/common/ui-kit/_index.scss b/app/assets/stylesheets/common/ui-kit/_index.scssindex fcc37145fb3..fb3847388fd 100644--- a/app/assets/stylesheets/common/ui-kit/_index.scss+++ b/app/assets/stylesheets/common/ui-kit/_index.scss@@ -7,3 +7,4 @@@import "d-resize-separator";@import "d-drag-and-drop";@import "d-shortcut";+@import "d-tabs";diff --git a/app/assets/stylesheets/common/ui-kit/d-tabs.scss b/app/assets/stylesheets/common/ui-kit/d-tabs.scssnew file mode 100644index 00000000000..59ab03fd46d--- /dev/null+++ b/app/assets/stylesheets/common/ui-kit/d-tabs.scss@@ -0,0 +1,102 @@+@use "lib/viewport";++.d-tabs {+ display: flex;+ flex-direction: column;+ min-width: 0;++ &__strip {+ display: flex;+ align-items: center;+ min-width: 0;+ }++ &__strip-controls {+ flex: 1 1 auto;+ min-width: 0;+ }++ &__tablist {+ @include horizontal-scroll-strip;+ display: flex;+ gap: 0.5em;++ &[aria-orientation="vertical"] {+ flex-direction: column;+ align-items: stretch;++ // The strip watches only the vertical axis, so a long label wraps+ // instead of scrolling sideways with no affordance.+ overflow: hidden auto;++ .d-tabs__tab {+ white-space: normal;+ overflow-wrap: anywhere;++ // The explicit min-height below replaces the flex automatic minimum,+ // so a bounded strip would otherwise crush a wrapped label out of its+ // own button rather than scroll.+ flex-shrink: 0;+ }+ }+ }++ &__tab {+ position: relative;+ display: flex;+ align-items: center;+ min-height: 30px;+ padding: 0.65em 0.75em;+ color: var(--d-nav-color);+ background: var(--d-nav-bg-color);+ border: 0;+ border-radius: var(--d-nav-pill-border-radius);+ line-height: var(--line-height-small);+ white-space: nowrap;+ cursor: pointer;+ transition: var(--d-button-transition);++ @include viewport.between(sm, lg) {+ font-size: var(--font-0);+ padding: var(--space-2) var(--space-3);+ }++ .d-icon {+ margin-right: 5px;+ color: var(--primary-high);+ transition: color 0.2s;+ }++ &:hover {+ @include nav-hover;+ }++ &[aria-selected="true"] {+ @include nav-active;+ }++ &[aria-disabled="true"] {+ color: var(--primary-low-mid);+ background: var(--d-nav-bg-color);+ cursor: not-allowed;++ .d-icon {+ color: var(--primary-low-mid);+ }++ // aria-disabled gets no system colour of its own.+ @media (forced-colors: active) {+ color: GrayText;+ }+ }++ &:focus-visible {+ @include default-focus;+ outline-offset: -2px;+ }+ }++ &__panel {+ min-width: 0;+ }+}diff --git a/docs/developer-guides/docs/03-code-internals/02-ui-kit.md b/docs/developer-guides/docs/03-code-internals/02-ui-kit.mdindex 0f13f53325a..a0fc164786b 100644--- a/docs/developer-guides/docs/03-code-internals/02-ui-kit.md+++ b/docs/developer-guides/docs/03-code-internals/02-ui-kit.md@@ -91,18 +91,20 @@ Form-level composition belongs to [FormKit](22-form-kit.md). These are the under## Page chrome and layout-| Primitive | Use it for | Styleguide |-| ------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |-| `DPageHeader`, `DPageSubheader` | Titles, breadcrumbs, tabs, and actions of an admin or settings page. | |-| `DBreadcrumbsContainer`, `DBreadcrumbsItem` | Breadcrumb trails registered from routes. | [Breadcrumbs](https://meta.discourse.org/styleguide/molecules/bread-crumbs) |-| `DNavItem`, `DNavigationItem`, `DHorizontalOverflowNav` | Navigation bars, including ones that scroll horizontally when they overflow. | [Navigation bar](https://meta.discourse.org/styleguide/molecules/navigation-bar) |-| `DResponsiveTable`, `DTableHeaderToggle` | Tables that stay usable on narrow viewports, with sortable column headers. | |-| `DVirtualList` | Long lists that render only the rows in view. | [Virtual list](https://meta.discourse.org/styleguide/molecules/virtual-list) |-| `DStatTiles` | Rows of headline numbers. | |-| `DTapTileGrid`, `DTapTile` | Grids of tappable choices. | |-| `DPostAccordion`, `DPostAccordionItem` | Collapsible sections. | |-| `DResizeHandles`, `DResizeSeparator` | User-resizable regions. | [Drag and drop](https://meta.discourse.org/styleguide/molecules/drag-and-drop) |-| `DSaveControls` | The save button and "saved" feedback of a settings form. | |+| Primitive | Use it for | Styleguide |+| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- |+| `DPageHeader`, `DPageSubheader` | Titles, breadcrumbs, tabs, and actions of an admin or settings page. | |+| `DBreadcrumbsContainer`, `DBreadcrumbsItem` | Breadcrumb trails registered from routes. | [Breadcrumbs](https://meta.discourse.org/styleguide/molecules/bread-crumbs) |+| `DNavItem`, `DNavigationItem`, `DHorizontalOverflowNav` | Navigation bars; the overflow nav is built on `DOverflowControls`. | [Navigation bar](https://meta.discourse.org/styleguide/molecules/navigation-bar) |+| `DOverflowControls` | Scrollable strips with edge fades, chevrons on whichever edges can still scroll, press-and-hold, and a way to reveal one item. | [Overflow controls](https://meta.discourse.org/styleguide/molecules/overflow-controls) |+| `DTabs` | Tab panels switched in place, with the strip, keyboard cursor, and ARIA pairing built in. | [Tabs](https://meta.discourse.org/styleguide/molecules/tabs) |+| `DResponsiveTable`, `DTableHeaderToggle` | Tables that stay usable on narrow viewports, with sortable column headers. | |+| `DVirtualList` | Long lists that render only the rows in view. | [Virtual list](https://meta.discourse.org/styleguide/molecules/virtual-list) |+| `DStatTiles` | Rows of headline numbers. | |+| `DTapTileGrid`, `DTapTile` | Grids of tappable choices. | |+| `DPostAccordion`, `DPostAccordionItem` | Collapsible sections. | |+| `DResizeHandles`, `DResizeSeparator` | User-resizable regions. | [Drag and drop](https://meta.discourse.org/styleguide/molecules/drag-and-drop) |+| `DSaveControls` | The save button and "saved" feedback of a settings form. | |## Loading, empty, and feedback states@@ -149,6 +151,7 @@ Form-level composition belongs to [FormKit](22-form-kit.md). These are the under| `d-roving-focus` | Arrow-key navigation over a group of items (a toolbar, listbox, menu, or tree) with a single tab stop, via roving tabindex or `aria-activedescendant`. See [Roving focus](https://meta.discourse.org/styleguide/molecules/roving-focus). || `d-close-on-click-outside` | Dismiss an overlay when the user clicks elsewhere. || `d-on-resize`, `d-observe-intersection`, `d-scroll-into-view` | React to layout and visibility. |+| `d-scroll-edges` | Stamp a scroll container's overflow and edge state as data attributes, for a strip that brings its own chrome. Pair it with the `scroll-strip` stylesheet mixin, which paints the edge fades from those attributes. || `d-autocomplete` | Attach an autocomplete popup to a text input. || `d-swipe`, `d-pointer-drag`, `d-resize-edge`, `d-drag-dwell`, `d-drag-and-drop-*` | Gestures. See [Drag, resize, and gesture primitives](30-drag-and-gesture-primitives.md). |@@ -161,7 +164,7 @@ When you add one:- **Name it `d-<name>`** and put it at `frontend/discourse/app/ui-kit/d-<name>.gts` (or `helpers/d-<name>.js`, `modifiers/d-<name>.ts`). See [Splitting a large primitive](#splitting-a-large-primitive) when one file is not enough.- **Write it in TypeScript with a `Signature`** (`Args`, `Blocks`, `Element`) and TSDoc on the class and every public argument. The kit is platform-level code, so accurate types matter more here than elsewhere; `d-shortcut.gts`, `d-skeleton.gts`, `d-resize-separator.gts`, and `modifiers/d-drag-dwell.ts` are good models. See [Types](27-types.md).- **Forward `...attributes`** to the element consumers will want to target, and declare that element in the `Element` type so the type checker allows attributes and modifiers on it.-- **Use BEM class names rooted at the component name** (older primitives predate this rule; new ones must follow it), `d-<name>`, `d-<name>__part`, `d-<name>--modifier`, and put the stylesheet at `app/assets/stylesheets/common/components/d-<name>.scss`, registered in `_index.scss`. Use colour and spacing tokens only; no hard-coded colours. See [CSS guidelines](26-css-guidelines-bem.md).+- **Use BEM class names rooted at the component name** (older primitives predate this rule; new ones must follow it), `d-<name>`, `d-<name>__part`, and a standalone `.--modifier`, and put the stylesheet at `app/assets/stylesheets/common/ui-kit/d-<name>.scss`, registered in `_index.scss`. Use colour and spacing tokens only; no hard-coded colours. See [CSS guidelines](26-css-guidelines-bem.md).- **Prefer named blocks over boolean arguments** when the consumer supplies content, and yield a small API object when the consumer needs to call back into the component.- **Take strings already translated.** A primitive receives display text as a plain `string` argument (`@label`, `@title`) that the consumer has already passed through `i18n()`; it never resolves translation keys itself. The kit does not know which locale file a consumer's key lives in, and a key-taking argument forces a parallel `@translatedX` argument for every string. `d-resize-separator.gts` documents its `label` this way. `DButton`'s `@label`-as-key plus `@translatedLabel` pair predates this rule; do not copy it.- **Gate development-only warnings and assertions on `DEBUG`** from `@glimmer/env`. It is a build-time constant, so the gated code and its messages are stripped from production bundles; `d-resize-handles.gts` and `modifiers/d-roving-focus/diagnostics.ts` do this.@@ -181,7 +184,7 @@ ui-kit/constants.ts # values shared by more than one collaboratorengine/ # the headless logic: state, algebra, resolutioncoordinators/ # non-rendering classes the component constructs once- parts/ # rendering subcomponents that add no wrapper DOM+ parts/ # rendering subcomponents that own part of the public DOMmodifiers/ # element-attached behaviour private to this primitivemodifiers/d-gesture.ts # a modifier entry follows the same shape@@ -195,11 +198,11 @@ Use the buckets that apply; a two-file split needs only `types.ts`. What goes wh- **`types.ts`** holds every interface, including the ones the entry re-exports as public API. It is the documentation home for the argument reference, so the entry's `Args` block can point at it.- **`-internals/engine/`** is the headless layer: state, filtering, the move or selection algebra, value resolution. It has no DOM and no component reference, which is what makes it unit-testable on its own.- **`-internals/coordinators/`** are plain classes the component constructs once and configures downward with thunks (`() => this.args.x`); they never hold a reference back to the component. Announcers, menu coordinators, and load-feedback timers live here.-- **`-internals/parts/`** are the rendering subcomponents. They receive the stable helper objects (the engine, a presenter) plus per-slot inputs, and add no wrapper DOM of their own.+- **`-internals/parts/`** are the rendering subcomponents. They receive the stable helper objects (the engine, a presenter) plus per-slot inputs, and render the elements of the primitive's public DOM, the ones its stylesheet and tests target. They add no wrapper beyond that contract.- **`-internals/constants.ts`** exists so two collaborators that must agree on a value (a menu identifier, a selector) import it rather than restating it.- **`README.md`** explains the split: what each collaborator owns, the invariants that cross files, and the design decisions a future reader would otherwise undo.-Something shared by several primitives, rather than private to one, goes in `ui-kit/-internals/<topic>/` (cursor navigation, for example), still off-limits to consumers.+Something shared by several primitives, rather than private to one, goes in `ui-kit/-internals/<topic>/` (`scroll-strip`, for example, which the overflow controls and the tab strip share), still off-limits to consumers.# Blast radius and backward compatibilitydiff --git a/frontend/discourse/app/ui-kit/-internals/scroll-strip/edges.ts b/frontend/discourse/app/ui-kit/-internals/scroll-strip/edges.tsnew file mode 100644index 00000000000..8d0cf2f9ed5--- /dev/null+++ b/frontend/discourse/app/ui-kit/-internals/scroll-strip/edges.ts@@ -0,0 +1,219 @@+/** The axes a strip can scroll on. A strip is measured one axis at a time. */+export type ScrollAxis = "horizontal" | "vertical";++/** Which axes a container can scroll on, as read from its computed overflow. */+export type ScrollableAxes = Record<ScrollAxis, boolean>;++/** Where a scroll container's content sits relative to its viewport on one axis. */+export interface ScrollEdgeState {+ /** The content is larger than the container on this axis. */+ overflowing: boolean;+ /** The container rests on its start edge. */+ atStart: boolean;+ /** The container rests on its end edge. */+ atEnd: boolean;+}++/**+ * One measurement of both axes. An axis is `null` when the container's+ * computed overflow does not let it scroll there, so geometric overflow+ * behind `overflow: hidden` never counts as scrollable.+ */+export interface ScrollEdgesSnapshot {+ /** The horizontal axis, or `null` when the container cannot scroll on it. */+ horizontal: ScrollEdgeState | null;+ /** The vertical axis, or `null` when the container cannot scroll on it. */+ vertical: ScrollEdgeState | null;+ /**+ * The axis whose state is stamped on the element. In `"auto"` it is `null`+ * when no axis can scroll; an explicit axis is always reported, even when+ * the container cannot scroll on it and its state is `null`.+ */+ primary: ScrollAxis | null;+}++/**+ * Slack in pixels: an offset this close to an edge counts as resting on it,+ * and content that outgrows the viewport by no more than this does not+ * count as overflowing.+ */+const EDGE_TOLERANCE = 2;++function isScrollable(overflow: string) {+ return overflow === "auto" || overflow === "scroll";+}++/** Reads which axes the container's computed overflow lets it scroll on. */+function scrollableAxes(element: HTMLElement): ScrollableAxes {+ const { overflowX, overflowY } = getComputedStyle(element);+ return {+ horizontal: isScrollable(overflowX),+ vertical: isScrollable(overflowY),+ };+}++/**+ * Measures one axis. Offsets are read as magnitudes, so a right-to-left+ * container reports the same logical edges as a left-to-right one.+ */+function measureScrollEdges(+ element: HTMLElement,+ axis: ScrollAxis+): ScrollEdgeState {+ const horizontal = axis === "horizontal";+ const viewport = horizontal ? element.clientWidth : element.clientHeight;+ const content = horizontal ? element.scrollWidth : element.scrollHeight;+ const offset = Math.abs(horizontal ? element.scrollLeft : element.scrollTop);+ const overflowing = content - viewport > EDGE_TOLERANCE;++ return {+ overflowing,+ atStart: overflowing && offset <= EDGE_TOLERANCE,+ atEnd: overflowing && content - offset - viewport <= EDGE_TOLERANCE,+ };+}++/**+ * Writes the primary axis's state onto the element as data attributes, so+ * a stylesheet can react to it: `data-d-scroll-axis` names the axis, and+ * `data-d-scroll-overflow`, `data-d-scroll-at-start`, `data-d-scroll-at-end`+ * are present while true.+ */+function stampScrollEdges(element: HTMLElement, snapshot: ScrollEdgesSnapshot) {+ const { primary } = snapshot;+ const state = primary ? snapshot[primary] : null;++ if (primary) {+ element.setAttribute("data-d-scroll-axis", primary);+ } else {+ element.removeAttribute("data-d-scroll-axis");+ }+ element.toggleAttribute("data-d-scroll-overflow", !!state?.overflowing);+ element.toggleAttribute("data-d-scroll-at-start", !!state?.atStart);+ element.toggleAttribute("data-d-scroll-at-end", !!state?.atEnd);+}++/**+ * Measures every scrollable axis. An explicit axis reports only itself. In+ * `"auto"`, the primary axis is the first scrollable axis that overflows,+ * horizontal before vertical, else the first scrollable axis.+ */+function snapshotScrollEdges(+ element: HTMLElement,+ axis: ScrollAxis | "auto",+ scrollable: ScrollableAxes = scrollableAxes(element)+): ScrollEdgesSnapshot {+ const measure = (candidate: ScrollAxis) =>+ scrollable[candidate] ? measureScrollEdges(element, candidate) : null;++ if (axis !== "auto") {+ const state = measure(axis);+ return {+ horizontal: axis === "horizontal" ? state : null,+ vertical: axis === "vertical" ? state : null,+ primary: axis,+ };+ }++ const horizontal = measure("horizontal");+ const vertical = measure("vertical");+ let primary: ScrollAxis | null = null;+ if (horizontal?.overflowing) {+ primary = "horizontal";+ } else if (vertical?.overflowing) {+ primary = "vertical";+ } else if (horizontal) {+ primary = "horizontal";+ } else if (vertical) {+ primary = "vertical";+ }++ return { horizontal, vertical, primary };+}++function sameState(a: ScrollEdgeState | null, b: ScrollEdgeState | null) {+ if (a === null || b === null) {+ return a === b;+ }+ return (+ a.overflowing === b.overflowing &&+ a.atStart === b.atStart &&+ a.atEnd === b.atEnd+ );+}++function sameSnapshot(a: ScrollEdgesSnapshot, b: ScrollEdgesSnapshot) {+ return (+ a.primary === b.primary &&+ sameState(a.horizontal, b.horizontal) &&+ sameState(a.vertical, b.vertical)+ );+}++/**+ * Keeps a scroll container's edge state current and stamped on it.+ *+ * Scrolling only re-measures against cached scrollability. Resizes and+ * child changes also re-read it, which lets an axis flip at a breakpoint.+ * Child sizes are observed directly, which catches a late web font swap.+ *+ * `onChange` fires only when the snapshot differs.+ */+export class ScrollEdgesWatcher {+ /** Re-reads scrollability and re-measures. */+ refresh = () => {+ this.#scrollable = scrollableAxes(this.#element);+ this.#measure();+ };+ #element: HTMLElement;+ #axis: ScrollAxis | "auto";+ #onChange: ((snapshot: ScrollEdgesSnapshot) => void) | undefined;+ #resizeObserver: ResizeObserver;+ #mutationObserver: MutationObserver;+ #scrollable: ScrollableAxes | null = null;+ #last: ScrollEdgesSnapshot | null = null;++ #measure = () => {+ const scrollable = this.#scrollable ?? scrollableAxes(this.#element);+ const snapshot = snapshotScrollEdges(this.#element, this.#axis, scrollable);+ if (this.#last && sameSnapshot(this.#last, snapshot)) {+ return;+ }+ this.#last = snapshot;+ stampScrollEdges(this.#element, snapshot);+ this.#onChange?.(snapshot);+ };++ #observeSizes = () => {+ this.#resizeObserver.disconnect();+ this.#resizeObserver.observe(this.#element);+ for (const child of this.#element.children) {+ this.#resizeObserver.observe(child);+ }+ this.refresh();+ };++ constructor(+ element: HTMLElement,+ options: {+ axis: ScrollAxis | "auto";+ onChange?: (snapshot: ScrollEdgesSnapshot) => void;+ }+ ) {+ this.#element = element;+ this.#axis = options.axis;+ this.#onChange = options.onChange;+ this.#resizeObserver = new ResizeObserver(this.refresh);+ this.#mutationObserver = new MutationObserver(this.#observeSizes);++ element.addEventListener("scroll", this.#measure, { passive: true });+ this.#mutationObserver.observe(element, { childList: true });+ this.#observeSizes();+ }++ disconnect() {+ this.#resizeObserver.disconnect();+ this.#mutationObserver.disconnect();+ this.#element.removeEventListener("scroll", this.#measure);+ }+}diff --git a/frontend/discourse/app/ui-kit/-internals/scroll-strip/reveal.ts b/frontend/discourse/app/ui-kit/-internals/scroll-strip/reveal.tsnew file mode 100644index 00000000000..808827371bf--- /dev/null+++ b/frontend/discourse/app/ui-kit/-internals/scroll-strip/reveal.ts@@ -0,0 +1,120 @@+/** How a revealed element is placed inside the scroll container. */+export interface RevealOptions {+ /**+ * `"nearest"` moves the container the least distance that brings the+ * element fully inside, clear of any scroll padding. `"center"` centres+ * it. Defaults to `"nearest"`.+ */+ align?: "nearest" | "center";+}++/**+ * An element's layout position, summed up its offsetParent chain. Bounding+ * rects include CSS transforms. Scroll positions are layout quantities, so+ * layout offsets are used instead.+ */+function layoutOffset(element: HTMLElement) {+ let x = 0;+ let y = 0;+ let node: HTMLElement | null = element;+ while (node) {+ x += node.offsetLeft;+ y += node.offsetTop;+ node = node.offsetParent instanceof HTMLElement ? node.offsetParent : null;+ }+ return { x, y };+}++/**+ * A computed scroll-padding side in pixels. A percentage stays a percentage+ * in the computed style, so it is resolved here against the scrollport. A+ * `calc()` that mixes units cannot be parsed and counts as zero.+ */+function padding(value: string, scrollport: number) {+ const parsed = Number.parseFloat(value);+ if (!Number.isFinite(parsed)) {+ return 0;+ }+ return value.trim().endsWith("%") ? (parsed / 100) * scrollport : parsed;+}++function nearest(+ start: number,+ end: number,+ padStart: number,+ padEnd: number,+ offset: number,+ viewport: number+) {+ if (start - padStart < offset) {+ return start - padStart;+ }+ if (end + padEnd > offset + viewport) {+ return end + padEnd - viewport;+ }+ return offset;+}++function clamp(value: number, min: number, max: number) {+ return Math.min(Math.max(value, min), max);+}++/**+ * Scrolls `scroller`, never the page, until `target` lies inside it. A+ * `scrollTo` with explicit offsets is what keeps ancestors still, and it+ * bypasses `scroll-padding`, so the padding is applied by hand.+ *+ * The write is not clamped; the browser clamps it, RTL's negative range+ * included. The no-op check compares the clamped target, so an item already+ * in place issues no scroll at all.+ */+export function revealInScroller(+ scroller: HTMLElement,+ target: HTMLElement,+ { align = "nearest" }: RevealOptions = {}+) {+ const origin = layoutOffset(scroller);+ const position = layoutOffset(target);+ const start = { x: position.x - origin.x, y: position.y - origin.y };+ const end = {+ x: start.x + target.offsetWidth,+ y: start.y + target.offsetHeight,+ };+ const style = getComputedStyle(scroller);++ let left: number;+ let top: number;+ if (align === "center") {+ left = start.x + target.offsetWidth / 2 - scroller.clientWidth / 2;+ top = start.y + target.offsetHeight / 2 - scroller.clientHeight / 2;+ } else {+ left = nearest(+ start.x,+ end.x,+ padding(style.scrollPaddingLeft, scroller.clientWidth),+ padding(style.scrollPaddingRight, scroller.clientWidth),+ scroller.scrollLeft,+ scroller.clientWidth+ );+ top = nearest(+ start.y,+ end.y,+ padding(style.scrollPaddingTop, scroller.clientHeight),+ padding(style.scrollPaddingBottom, scroller.clientHeight),+ scroller.scrollTop,+ scroller.clientHeight+ );+ }++ const maxX = scroller.scrollWidth - scroller.clientWidth;+ const maxY = scroller.scrollHeight - scroller.clientHeight;+ const rtl = style.direction === "rtl";+ if (+ clamp(left, rtl ? -maxX : 0, rtl ? 0 : maxX) === scroller.scrollLeft &&+ clamp(top, 0, maxY) === scroller.scrollTop+ ) {+ return;+ }++ scroller.scrollTo({ left, top, behavior: "instant" });+}diff --git a/frontend/discourse/app/ui-kit/d-horizontal-overflow-nav.gjs b/frontend/discourse/app/ui-kit/d-horizontal-overflow-nav.gjsdeleted file mode 100644index 45d85f49f3e..00000000000--- a/frontend/discourse/app/ui-kit/d-horizontal-overflow-nav.gjs+++ /dev/null@@ -1,195 +0,0 @@-import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";-import { registerDestructor } from "@ember/destroyable";-import { on } from "@ember/modifier";-import { action } from "@ember/object";-import didInsert from "@ember/render-modifiers/modifiers/did-insert";-import { bind } from "discourse/lib/decorators";-import { isDocumentRTL } from "discourse/lib/text-direction";-import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";-import dIcon from "discourse/ui-kit/helpers/d-icon";-import dOnResize from "discourse/ui-kit/modifiers/d-on-resize";--export default class DHorizontalOverflowNav extends Component {- @tracked hasScroll;- @tracked hideRightScroll = false;- @tracked hideLeftScroll = true;- scrollInterval;-- @bind- setup(element) {- this.scrollToActive(element);-- const observer = new MutationObserver(() => this.watchScroll(element));- observer.observe(element, { childList: true });- registerDestructor(this, () => observer.disconnect());- }-- @bind- scrollToActive(element) {- const activeElement = element.querySelector("a.active, button.active");-- activeElement?.scrollIntoView({- block: "nearest",- inline: "center",- container: "nearest",- });- }-- @bind- onResize(entries) {- const element = entries[0].target;- this.watchScroll(element);- this.hasScroll = element.scrollWidth > element.offsetWidth;- }-- @bind- stopScroll() {- clearInterval(this.scrollInterval);- }-- @bind- onScroll(event) {- this.watchScroll(event.target);- }-- watchScroll(element) {- const { scrollWidth, scrollLeft, offsetWidth } = element;-- // Check if the content overflows- this.hasScroll = scrollWidth > offsetWidth;-- if (!this.hasScroll) {- this.hideLeftScroll = true;- this.hideRightScroll = true;- clearInterval(this.scrollInterval);- return;- }-- const atStart = Math.abs(scrollLeft) <= 2;- const atEnd = scrollWidth - Math.abs(scrollLeft) - offsetWidth <= 2;-- // Buttons stay in physical positions (rtl:ignore in CSS), but in RTL- // the scroll direction is reversed, so swap which button hides- if (isDocumentRTL()) {- this.hideLeftScroll = atEnd;- this.hideRightScroll = atStart;- } else {- this.hideLeftScroll = atStart;- this.hideRightScroll = atEnd;- }-- if (atStart || atEnd) {- clearInterval(this.scrollInterval);- }- }-- @bind- scrollDrag(event) {- if (!this.hasScroll) {- return;- }-- event.preventDefault();-- const navPills = event.target.closest(".nav-pills");-- const position = {- left: navPills.scrollLeft, // current scroll- x: event.clientX, // mouse position- };-- const mouseDragScroll = function (e) {- let mouseChange = e.clientX - position.x;- navPills.scrollLeft = position.left - mouseChange;- };-- navPills.querySelectorAll("a").forEach((a) => {- a.style.cursor = "grabbing";- });-- const removeDragScroll = function () {- document.removeEventListener("mousemove", mouseDragScroll);- navPills.querySelectorAll("a").forEach((a) => {- a.style.cursor = "pointer";- });- };-- document.addEventListener("mousemove", mouseDragScroll);- document.addEventListener("mouseup", removeDragScroll, { once: true });- }-- @action- horizontalScroll(event) {- // Do nothing if it is not left mousedown- if (event.which !== 1) {- return;- }-- let scrollSpeed = 175;- let siblingTarget = event.target.previousElementSibling;-- if (event.target.dataset.direction === "left") {- scrollSpeed = scrollSpeed * -1;- siblingTarget = event.target.nextElementSibling;- }-- siblingTarget.scrollLeft += scrollSpeed;-- this.scrollInterval = setInterval(function () {- siblingTarget.scrollLeft += scrollSpeed;- }, 50);- }-- <template>- {{! eslint-disable ember/template-no-pointer-down-event-binding }}- {{! eslint-disable ember/template-no-invalid-interactive }}-- <nav- aria-label={{@ariaLabel}}- class="horizontal-overflow-nav {{if this.hasScroll 'has-scroll'}}"- >- {{#if this.hasScroll}}- <a- class={{dConcatClass- "horizontal-overflow-nav__scroll-left"- (if this.hideLeftScroll "disabled")- }}- data-direction="left"- role="button"- {{on "mousedown" this.horizontalScroll}}- {{on "mouseup" this.stopScroll}}- {{on "mouseleave" this.stopScroll}}- >- {{dIcon "chevron-left"}}- </a>- {{/if}}-- <ul- class="nav-pills action-list {{@className}}"- ...attributes- {{dOnResize this.onResize}}- {{on "scroll" this.onScroll}}- {{didInsert this.setup}}- {{on "mousedown" this.scrollDrag}}- >- {{yield}}- </ul>-- {{#if this.hasScroll}}- <a- class={{dConcatClass- "horizontal-overflow-nav__scroll-right"- (if this.hideRightScroll "disabled")- }}- role="button"- {{on "mousedown" this.horizontalScroll}}- {{on "mouseup" this.stopScroll}}- {{on "mouseleave" this.stopScroll}}- >- {{dIcon "chevron-right"}}- </a>- {{/if}}- </nav>- </template>-}diff --git a/frontend/discourse/app/ui-kit/d-horizontal-overflow-nav.gts b/frontend/discourse/app/ui-kit/d-horizontal-overflow-nav.gtsnew file mode 100644index 00000000000..74300d2b2f9--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-horizontal-overflow-nav.gts@@ -0,0 +1,93 @@+import Component from "@glimmer/component";+import { modifier } from "ember-modifier";+import DOverflowControls, {+ type DOverflowControlsBag,+} from "discourse/ui-kit/d-overflow-controls";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";++const ACTIVE_ITEM = "a.active, button.active";++const EDGE_CLASSES = {+ left: "horizontal-overflow-nav__scroll-left",+ right: "horizontal-overflow-nav__scroll-right",+};++interface DHorizontalOverflowNavSignature {+ Args: {+ /** The accessible name of the navigation landmark, already translated. */+ ariaLabel?: string;++ /** Extra class(es) added to the list element. */+ className?: string;+ };++ /** The list element. Consumers yield its `li` children. */+ Element: HTMLUListElement;++ Blocks: {+ /** The `li` items of the list. */+ default: [];+ };+}++/**+ * A navigation bar whose pills scroll sideways when they outgrow it, built+ * on `DOverflowControls`: edge fades, chevrons, press-and-hold, and the+ * active item revealed on mount.+ *+ * Consumers yield bare `li` elements. The list keeps the `nav-pills`+ * styling contract and receives every attribute.+ */+export default class DHorizontalOverflowNav extends Component<DHorizontalOverflowNavSignature> {+ /**+ * Reveals the active item once, centered in the strip. When no active+ * item exists on mount, as in a portal-filled list, it watches the list+ * and reveals the first one that appears.+ */+ revealActive = modifier(+ (list: HTMLElement, [strip]: [strip: DOverflowControlsBag]) => {+ const reveal = () => {+ const active = list.querySelector<HTMLElement>(ACTIVE_ITEM);+ if (!active) {+ return false;+ }+ strip.reveal(active, { align: "center" });+ return true;+ };++ if (reveal()) {+ return;+ }++ const observer = new MutationObserver(() => {+ if (reveal()) {+ observer.disconnect();+ }+ });+ observer.observe(list, { childList: true, subtree: true });++ return () => observer.disconnect();+ }+ );++ <template>+ <nav aria-label={{@ariaLabel}} class="horizontal-overflow-nav">+ <DOverflowControls+ @axis="horizontal"+ @edgeButtonClasses={{EDGE_CLASSES}}+ @ownedScroller={{true}}+ @wrapperClass="horizontal-overflow-nav__controls"+ as |strip|+ >+ <ul+ class={{dConcatClass "nav-pills action-list" @className}}+ ...attributes+ {{strip.scroller}}+ {{this.revealActive strip}}+ >+ {{yield}}+ </ul>+ </DOverflowControls>+ </nav>+ </template>+}diff --git a/frontend/discourse/app/ui-kit/d-overflow-controls.gts b/frontend/discourse/app/ui-kit/d-overflow-controls.gtsindex 436f7ad0bbc..1ede3fe2510 100644--- a/frontend/discourse/app/ui-kit/d-overflow-controls.gts+++ b/frontend/discourse/app/ui-kit/d-overflow-controls.gts@@ -1,42 +1,189 @@import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";-import { registerDestructor } from "@ember/destroyable";+import { DEBUG } from "@glimmer/env";+import { cached, tracked } from "@glimmer/tracking";+import type { TOC } from "@ember/component/template-only";+import { assert } from "@ember/debug";+import { isDestroying } from "@ember/destroyable";+import { get } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";-import didInsert from "@ember/render-modifiers/modifiers/did-insert";-import { bind } from "discourse/lib/decorators";+import { cancel, schedule } from "@ember/runloop";+import type { ModifierLike } from "@glint/template";+import { modifier } from "ember-modifier";+import discourseLater from "discourse/lib/later";import { isDocumentRTL } from "discourse/lib/text-direction";+import {+ type ScrollAxis,+ type ScrollEdgesSnapshot,+ ScrollEdgesWatcher,+} from "discourse/ui-kit/-internals/scroll-strip/edges";+import {+ revealInScroller,+ type RevealOptions,+} from "discourse/ui-kit/-internals/scroll-strip/reveal";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";-import dOnResize from "discourse/ui-kit/modifiers/d-on-resize";++/** The axis a strip scrolls on. */+export type DOverflowControlsAxis = ScrollAxis;++/** The options `reveal` accepts. */+export type DOverflowControlsRevealOptions = RevealOptions;++/** The physical edges a chevron can sit on. */+export type DOverflowControlsEdge = "left" | "right" | "up" | "down";++/** What the default block receives. Consumers of the default mode may ignore it. */+export interface DOverflowControlsBag {+ /**+ * Marks the consumer's own element as the scroller. Owned mode only; apply+ * it to exactly one element, which may mount later inside a conditional.+ */+ scroller: ModifierLike<{ Element: HTMLElement; Args: { Positional: [] } }>;++ /**+ * Scrolls the strip, never the page, until `element` is fully inside it.+ * `"nearest"` also clears the fade band. Instant. Needs a mounted+ * scroller: in owned mode, apply `scroller` before any modifier that+ * reveals on install.+ */+ reveal: (element: HTMLElement, options?: RevealOptions) => void;+}interface DOverflowControlsSignature {Args: {/** Extra class(es) added to the outer wrapper element. */wrapperClass?: string;- /** Extra class(es) added to the scrollable content element. */++ /** Default mode only: extra class(es) added to the generated scroller. */class?: string;- /** Extra class(es) added to each edge scroll button. */++ /** Extra class(es) added to every chevron button. */buttonClass?: string;++ /**+ * Extra class(es) per physical edge, for stylesheets and specs that+ * address one chevron.+ */+ edgeButtonClasses?: Partial<Record<DOverflowControlsEdge, string>>;++ /**+ * The consumer renders the scrolling element itself and applies the+ * yielded `scroller` modifier to it. No content element is generated,+ * and `...attributes` land on the wrapper instead. The element must be+ * a direct child of the wrapper and its stylesheet must include the+ * `scroll-strip` mixin: the mixin paints the fade, hides the scrollbar,+ * and sets the `scroll-padding` that `reveal` keeps items clear of.+ */+ ownedScroller?: boolean;++ /**+ * The axis the chevrons and the fade follow.+ *+ * When omitted, both axes are measured from the scroller's computed+ * overflow and may show chevrons at once; the fade follows the first+ * one that overflows. An axis whose computed overflow is not scrollable+ * never shows a chevron.+ */+ axis?: DOverflowControlsAxis;};+ /**+ * The generated scroller in the default mode; the wrapper in owned mode,+ * where the consumer's own element is the scroller.+ */Element: HTMLDivElement;Blocks: {- default: [];+ /** The scrolled content, with the strip's controls as the block param. */+ default: [strip: DOverflowControlsBag];+ };+}++/** How long a press must last before it starts scrolling continuously. */+const HOLD_DELAY_MS = 300;++/** Viewports scrolled per second while a chevron stays pressed. */+const HOLD_VELOCITY = 3;++const NO_EDGES: ScrollEdgesSnapshot = {+ horizontal: null,+ vertical: null,+ primary: null,+};++const EDGE_ICONS: Record<DOverflowControlsEdge, string> = {+ left: "chevron-left",+ right: "chevron-right",+ up: "chevron-up",+ down: "chevron-down",+};++function prefersReducedMotion() {+ return (+ typeof window.matchMedia === "function" &&+ window.matchMedia("(prefers-reduced-motion: reduce)").matches+ );+}++function preventFocusGrab(event: MouseEvent) {+ event.preventDefault();+}++interface EdgeButtonSignature {+ Args: {+ edge: DOverflowControlsEdge;+ class: string | undefined;+ onClick: () => void;+ hold: ModifierLike<{+ Element: HTMLElement;+ Args: { Positional: [edge: DOverflowControlsEdge] };+ }>;};}/**- * Wraps scrollable content and shows chevron + gradient-fade buttons on whichever- * edges can still be scrolled. Works on both axes: a horizontally-overflowing- * child gets left/right buttons, a vertically-overflowing one gets up/down. State- * is recomputed on insert, resize, and scroll.+ * One chevron, hidden from assistive technology and out of the tab order.+ * Keyboard users already reach every item, so the button is a pointer+ * shortcut only. The mousedown handler keeps a click from stealing focus.+ */+const EdgeButton: TOC<EdgeButtonSignature> = <template>+ {{! eslint-disable ember/template-no-pointer-down-event-binding }}+ <button+ aria-hidden="true"+ class={{dConcatClass "d-overflow-controls__btn" (concat "--" @edge) @class}}+ tabindex="-1"+ type="button"+ {{on "mousedown" preventFocusGrab}}+ {{on "click" @onClick}}+ {{@hold @edge}}+ >+ {{dIcon (get EDGE_ICONS @edge)}}+ </button>+</template>;++function concat(prefix: string, edge: string) {+ return `${prefix}${edge}`;+}++/**+ * Wraps scrollable content and shows a chevron on each edge that can still+ * scroll, over an edge fade painted by the scroller's stylesheet. A click+ * scrolls one viewport; holding scrolls continuously.*- * Consumers can theme the buttons with the `--fade-color` and `--fade-width` CSS- * custom properties, and augment the generated classes via `@wrapperClass`,- * `@class` (scrollable content) and `@buttonClass`. Any `...attributes` land on- * the scrollable content element.+ * In the default mode the component renders the scroller itself and any+ * `...attributes` land on it. With `@ownedScroller` the consumer's own+ * element is the scroller (the consumer applies the yielded `scroller`+ * modifier to it) and `...attributes` land on the wrapper.+ *+ * The scroller carries `data-d-scroll-*` attributes describing its edge+ * state; the `scroll-strip` stylesheet mixin reads them for the fade. The+ * fade is a mask, so it shows whatever background lies behind the scroller+ * and the scroller itself must not paint one. `--fade-width` sizes the+ * fade, `--fade-color` colors the chevron buttons only, and `--fade-inset`+ * holds the fade clear of the chevrons and is set by the wrapper. The chevrons+ * and their scrolling follow the document's direction; `reveal` follows+ * the scroller's.*/export default class DOverflowControls extends Component<DOverflowControlsSignature> {@tracked hasTopScroll = false;@@ -44,37 +191,174 @@ export default class DOverflowControls extends Component<DOverflowControlsSignat@tracked hasLeftScroll = false;@tracked hasRightScroll = false;- #scrollable: HTMLElement | null = null;- #canScrollX = false;- #canScrollY = false;- #mutationObserver?: MutationObserver;+ /**+ * Adopts an element as the strip's scroller and keeps its edge state+ * current for as long as it stays mounted. One stable definition, so a+ * scroller that survives a re-render keeps its watcher.+ */+ scroller = modifier((element: HTMLElement) => {+ if (DEBUG) {+ assert(+ "d-overflow-controls: strip.scroller was applied to a second element while another scroller is still mounted",+ !this.#scroller ||+ this.#scroller === element ||+ !this.#scroller.isConnected+ );+ }+ this.#scroller = element;+ const watcher = new ScrollEdgesWatcher(element, {+ axis: this.args.axis ?? "auto",+ onChange: (snapshot) => this.#applyEdges(element, snapshot),+ });++ return () => {+ watcher.disconnect();+ if (this.#scroller === element) {+ this.#scroller = null;+ this.#applyEdges(null, NO_EDGES);+ }+ };+ });- @action- setup(element: HTMLElement) {- this.#scrollable = element;- this.#refreshScrollableAxes(element);- this.#checkScroll(element);-- // content added/removed (e.g. async-loaded items) changes overflow without- // resizing the scroll box, which a ResizeObserver wouldn't catch- this.#mutationObserver = new MutationObserver(() =>- this.#checkScroll(element)- );- this.#mutationObserver.observe(element, { childList: true });- registerDestructor(this, () => this.#mutationObserver?.disconnect());+ /**+ * Press-and-hold on a chevron. State lives in the install closure, so a+ * chevron unmounted at its edge mid-hold takes its hold with it.+ *+ * The click that ends a real hold is swallowed once, so a plain click+ * still scrolls exactly one viewport.+ */+ hold = modifier((button: HTMLElement, [edge]: [DOverflowControlsEdge]) => {+ let held = false;+ let timer: ReturnType<typeof discourseLater> | null = null;+ let frame: number | null = null;+ let lastFrameAt = 0;+ let pointerId: number | null = null;++ const step = (now: number) => {+ const scroller = this.#scroller;+ if (!scroller) {+ return;+ }+ held = true;+ const seconds = Math.max(0, now - lastFrameAt) / 1000;+ lastFrameAt = now;+ const horizontal = edge === "left" || edge === "right";+ const viewport = horizontal+ ? scroller.clientWidth+ : scroller.clientHeight;+ const direction = edge === "left" || edge === "up" ? -1 : 1;+ const distance = direction * HOLD_VELOCITY * viewport * seconds;+ scroller.scrollBy({+ left: horizontal ? distance : 0,+ top: horizontal ? 0 : distance,+ behavior: "instant",+ });+ frame = requestAnimationFrame(step);+ };++ const stop = () => {+ if (timer) {+ cancel(timer);+ timer = null;+ }+ if (frame !== null) {+ cancelAnimationFrame(frame);+ frame = null;+ }+ window.removeEventListener("blur", abort);+ if (pointerId !== null) {+ if (button.hasPointerCapture(pointerId)) {+ button.releasePointerCapture(pointerId);+ }+ pointerId = null;+ }+ };++ // An end without a click must not leave the swallow armed for the next+ // press.+ const abort = () => {+ held = false;+ stop();+ };++ const onPointerDown = (event: PointerEvent) => {+ if (+ pointerId !== null ||+ event.button !== 0 ||+ event.isPrimary === false ||+ event.pointerType === "touch"+ ) {+ return;+ }+ held = false;+ stop();+ pointerId = event.pointerId;+ button.setPointerCapture(event.pointerId);+ // Losing window focus ends a press without a pointerup.+ window.addEventListener("blur", abort);+ timer = discourseLater(() => {+ timer = null;+ lastFrameAt = performance.now();+ frame = requestAnimationFrame(step);+ }, HOLD_DELAY_MS);+ };++ const onClick = (event: MouseEvent) => {+ if (!held) {+ return;+ }+ held = false;+ event.preventDefault();+ event.stopImmediatePropagation();+ };++ // Only the pointer that started the hold may end it. A second pointer+ // on the same button must not cut it short.+ const onPointerEnd = (event: PointerEvent) => {+ if (event.pointerId === pointerId) {+ stop();+ }+ };++ const onPointerCancel = (event: PointerEvent) => {+ if (event.pointerId === pointerId) {+ abort();+ }+ };++ button.addEventListener("pointerdown", onPointerDown);+ button.addEventListener("pointerup", onPointerEnd);+ button.addEventListener("pointercancel", onPointerCancel);+ button.addEventListener("lostpointercapture", onPointerEnd);+ button.addEventListener("click", onClick, { capture: true });++ return () => {+ stop();+ button.removeEventListener("pointerdown", onPointerDown);+ button.removeEventListener("pointerup", onPointerEnd);+ button.removeEventListener("pointercancel", onPointerCancel);+ button.removeEventListener("lostpointercapture", onPointerEnd);+ button.removeEventListener("click", onClick, { capture: true });+ };+ });+ #scroller: HTMLElement | null = null;++ /** Built without reading tracked state, so its identity never changes. */+ @cached+ get strip(): DOverflowControlsBag {+ return { scroller: this.scroller, reveal: this.reveal };}- @bind- onResize(entries: ResizeObserverEntry[]) {- // overflow can flip axis at a breakpoint, so re-read it on resize- const element = entries[0].target as HTMLElement;- this.#refreshScrollableAxes(element);- this.#checkScroll(element);+ @action+ reveal(element: HTMLElement, options?: RevealOptions) {+ if (this.#scroller) {+ revealInScroller(this.#scroller, element, options);+ }}@action- onScroll(event: Event) {- this.#checkScroll(event.target as HTMLElement);+ scrollDown() {+ this.#scrollByViewport(0, 1);}@action@@ -92,64 +376,48 @@ export default class DOverflowControls extends Component<DOverflowControlsSignatthis.#scrollByViewport(0, -1);}- @action- scrollDown() {- this.#scrollByViewport(0, 1);- }+ /**+ * Tracked writes are deferred one hop. The first measurement runs inside+ * the scroller's modifier install, still within the render transaction.+ * A snapshot only lands while its scroller is still the current one, so+ * a replaced or unmounted scroller cannot restore stale flags.+ */+ #applyEdges(scroller: HTMLElement | null, snapshot: ScrollEdgesSnapshot) {+ schedule("afterRender", () => {+ if (isDestroying(this) || this.#scroller !== scroller) {+ return;+ }- @action- preventFocusGrab(event: MouseEvent) {- event.preventDefault();- }-- #refreshScrollableAxes(element: HTMLElement) {- const { overflowX, overflowY } = getComputedStyle(element);- this.#canScrollX = overflowX === "auto" || overflowX === "scroll";- this.#canScrollY = overflowY === "auto" || overflowY === "scroll";- }-- #checkScroll(element: HTMLElement) {- const {- scrollWidth,- scrollLeft,- offsetWidth,- scrollHeight,- scrollTop,- offsetHeight,- } = element;-- const hasHorizontalOverflow = this.#canScrollX && scrollWidth > offsetWidth;- const canScrollBack = hasHorizontalOverflow && Math.abs(scrollLeft) > 2;- const canScrollForward =- hasHorizontalOverflow &&- scrollWidth - Math.abs(scrollLeft) - offsetWidth > 2;-- // Buttons stay in physical positions (rtl:ignore in CSS), but in RTL- // the scroll direction is reversed, so swap which button shows- if (isDocumentRTL()) {- this.hasLeftScroll = canScrollForward;- this.hasRightScroll = canScrollBack;- } else {- this.hasLeftScroll = canScrollBack;- this.hasRightScroll = canScrollForward;- }+ const { horizontal, vertical } = snapshot;+ const canScrollBack = !!horizontal?.overflowing && !horizontal.atStart;+ const canScrollForward = !!horizontal?.overflowing && !horizontal.atEnd;- const hasVerticalOverflow = this.#canScrollY && scrollHeight > offsetHeight;- this.hasTopScroll = hasVerticalOverflow && scrollTop > 2;- this.hasBottomScroll =- hasVerticalOverflow && scrollHeight - scrollTop - offsetHeight > 2;+ // Buttons stay in physical positions (rtl:ignore in CSS), but in RTL+ // the scroll direction is reversed, so swap which button shows.+ if (isDocumentRTL()) {+ this.hasLeftScroll = canScrollForward;+ this.hasRightScroll = canScrollBack;+ } else {+ this.hasLeftScroll = canScrollBack;+ this.hasRightScroll = canScrollForward;+ }+ this.hasTopScroll = !!vertical?.overflowing && !vertical.atStart;+ this.hasBottomScroll = !!vertical?.overflowing && !vertical.atEnd;+ });}#scrollByViewport(dx: number, dy: number) {- const element = this.#scrollable;+ const element = this.#scroller;if (!element) {return;}+ const options: ScrollToOptions = {+ behavior: prefersReducedMotion() ? "instant" : "smooth",+ };+// iOS Safari doesn't clamp smooth programmatic scrolls, so an// out-of-bounds target rubber-bands into blank overscroll space- const options: ScrollToOptions = { behavior: "smooth" };-if (dx) {const max = element.scrollWidth - element.offsetWidth;const target = element.scrollLeft + dx * element.offsetWidth;@@ -165,72 +433,101 @@ export default class DOverflowControls extends Component<DOverflowControlsSignat}<template>- <div class={{dConcatClass "d-overflow-controls" @wrapperClass}}>- {{#if this.hasTopScroll}}- {{! eslint-disable ember/template-no-pointer-down-event-binding }}- <button- aria-hidden="true"- class={{dConcatClass "d-overflow-controls__btn --up" @buttonClass}}- tabindex="-1"- type="button"- {{on "mousedown" this.preventFocusGrab}}- {{on "click" this.scrollUp}}- >- {{dIcon "chevron-up"}}- </button>- {{/if}}-- {{#if this.hasLeftScroll}}- {{! eslint-disable ember/template-no-pointer-down-event-binding }}- <button- aria-hidden="true"- class={{dConcatClass "d-overflow-controls__btn --left" @buttonClass}}- tabindex="-1"- type="button"- {{on "mousedown" this.preventFocusGrab}}- {{on "click" this.scrollLeft}}- >- {{dIcon "chevron-left"}}- </button>- {{/if}}-+ {{#if @ownedScroller}}<div- class={{dConcatClass "d-overflow-controls__content" @class}}+ class={{dConcatClass+ "d-overflow-controls"+ "--owned-scroller"+ @wrapperClass+ }}...attributes- {{didInsert this.setup}}- {{dOnResize this.onResize}}- {{on "scroll" this.onScroll}}>- {{yield}}+ {{#if this.hasTopScroll}}+ <EdgeButton+ @class={{dConcatClass @buttonClass (get @edgeButtonClasses "up")}}+ @edge="up"+ @hold={{this.hold}}+ @onClick={{this.scrollUp}}+ />+ {{/if}}+ {{#if this.hasLeftScroll}}+ <EdgeButton+ @class={{dConcatClass @buttonClass (get @edgeButtonClasses "left")}}+ @edge="left"+ @hold={{this.hold}}+ @onClick={{this.scrollLeft}}+ />+ {{/if}}++ {{yield this.strip}}++ {{#if this.hasRightScroll}}+ <EdgeButton+ @class={{dConcatClass+ @buttonClass+ (get @edgeButtonClasses "right")+ }}+ @edge="right"+ @hold={{this.hold}}+ @onClick={{this.scrollRight}}+ />+ {{/if}}+ {{#if this.hasBottomScroll}}+ <EdgeButton+ @class={{dConcatClass @buttonClass (get @edgeButtonClasses "down")}}+ @edge="down"+ @hold={{this.hold}}+ @onClick={{this.scrollDown}}+ />+ {{/if}}</div>+ {{else}}+ <div class={{dConcatClass "d-overflow-controls" @wrapperClass}}>+ {{#if this.hasTopScroll}}+ <EdgeButton+ @class={{dConcatClass @buttonClass (get @edgeButtonClasses "up")}}+ @edge="up"+ @hold={{this.hold}}+ @onClick={{this.scrollUp}}+ />+ {{/if}}+ {{#if this.hasLeftScroll}}+ <EdgeButton+ @class={{dConcatClass @buttonClass (get @edgeButtonClasses "left")}}+ @edge="left"+ @hold={{this.hold}}+ @onClick={{this.scrollLeft}}+ />+ {{/if}}- {{#if this.hasRightScroll}}- {{! eslint-disable ember/template-no-pointer-down-event-binding }}- <button- aria-hidden="true"- class={{dConcatClass "d-overflow-controls__btn --right" @buttonClass}}- tabindex="-1"- type="button"- {{on "mousedown" this.preventFocusGrab}}- {{on "click" this.scrollRight}}- >- {{dIcon "chevron-right"}}- </button>- {{/if}}-- {{#if this.hasBottomScroll}}- {{! eslint-disable ember/template-no-pointer-down-event-binding }}- <button- aria-hidden="true"- class={{dConcatClass "d-overflow-controls__btn --down" @buttonClass}}- tabindex="-1"- type="button"- {{on "mousedown" this.preventFocusGrab}}- {{on "click" this.scrollDown}}+ <div+ class={{dConcatClass "d-overflow-controls__content" @class}}+ ...attributes+ {{this.scroller}}>- {{dIcon "chevron-down"}}- </button>- {{/if}}- </div>+ {{yield this.strip}}+ </div>++ {{#if this.hasRightScroll}}+ <EdgeButton+ @class={{dConcatClass+ @buttonClass+ (get @edgeButtonClasses "right")+ }}+ @edge="right"+ @hold={{this.hold}}+ @onClick={{this.scrollRight}}+ />+ {{/if}}+ {{#if this.hasBottomScroll}}+ <EdgeButton+ @class={{dConcatClass @buttonClass (get @edgeButtonClasses "down")}}+ @edge="down"+ @hold={{this.hold}}+ @onClick={{this.scrollDown}}+ />+ {{/if}}+ </div>+ {{/if}}</template>}diff --git a/frontend/discourse/app/ui-kit/d-tabs.gts b/frontend/discourse/app/ui-kit/d-tabs.gtsnew file mode 100644index 00000000000..37eb047f88d--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-tabs.gts@@ -0,0 +1,586 @@+import Component from "@glimmer/component";+import { DEBUG } from "@glimmer/env";+import { cached, tracked } from "@glimmer/tracking";+import { assert } from "@ember/debug";+import { isDestroying } from "@ember/destroyable";+import Owner, { getOwner } from "@ember/owner";+import { schedule } from "@ember/runloop";+import curryComponent from "ember-curry-component";+import { modifier } from "ember-modifier";+import { revealInScroller } from "discourse/ui-kit/-internals/scroll-strip/reveal";+import DConditionalInElement from "discourse/ui-kit/d-conditional-in-element";+import Tab from "discourse/ui-kit/d-tabs/-internals/parts/tab";+import Tablist from "discourse/ui-kit/d-tabs/-internals/parts/tablist";+import type {+ DTabsBag,+ DTabsEngine,+ DTabsHeaderBag,+ DTabsOrientation,+ DTabsSignature,+} from "discourse/ui-kit/d-tabs/types";+import dUniqueId from "discourse/ui-kit/helpers/d-unique-id";++export type {+ DTabsBag,+ DTabsHeaderBag,+ DTabsOrientation,+ DTabsSignature,+} from "discourse/ui-kit/d-tabs/types";++const NEVER_RENDERED = Symbol("never rendered");++/**+ * An ARIA tabs widget that owns the tab strip, the roving keyboard cursor,+ * the persistent tabpanel, and the ids that pair them. A consumer declares+ * each tab with its label and panel content and supplies the selection.+ *+ * Selection is controlled: `@active` in, `@onActivate` out, and nothing+ * moves until the owner feeds the key back. The component never invents a+ * fallback, because which tab deserves one is the owner's policy.+ * Activation is manual: arrow keys move focus only, and a tab is selected+ * by click, Enter, or Space.+ *+ * A strip wider than its container scrolls rather than wraps, and the+ * selected tab is brought into view without the page moving.+ *+ * The declaration block renders inside the tablist element, wherever that+ * element sits. A `<:header>` block can place the yielded `Tablist` among+ * its own controls; the tabs still land in it.+ *+ * This is the tabs widget: content panels switched in place. Tab-shaped+ * route navigation stays on `DNavItem`, `DHorizontalOverflowNav`, and+ * `DPageHeader`, which render links, not `role="tab"`.+ *+ * ```gjs+ * <DTabs @active={{this.section}} @onActivate={{this.setSection}} @label={{i18n "user.sections"}} as |tabs|>+ * <tabs.Tab @key="account" @label={{i18n "user.account"}}>+ * <AccountSettings />+ * </tabs.Tab>+ * <tabs.Tab @key="security" @label={{i18n "user.security"}}>+ * <SecuritySettings />+ * </tabs.Tab>+ * </DTabs>+ * ```+ */+export default class DTabs extends Component<DTabsSignature> {+ @tracked tablistElement: HTMLElement | null = null;++ registerPanel = modifier((element: HTMLElement) => {+ this.#panelActual = element;+ this.#deferTrackedWrite(() => {+ if (this.#panelActual === element) {+ this._panelElement = element;+ }+ });++ return () => {+ if (this.#panelActual === element) {+ this.#panelActual = null;+ }+ if (this._panelElement === element) {+ this._panelElement = null;+ }+ };+ });++ /**+ * Joins a tab button to the registry and bumps the version on both ends+ * so the keyboard engine reconciles its cursor.+ *+ * The cleanup checks identity. Destructors run deferred, so a replaced+ * button's teardown can land after its successor registered and must not+ * evict it.+ */+ registerTab = modifier((element: Element, [key]: [string]) => {+ if (DEBUG) {+ // A duplicate and a branch replacement not yet torn down look alike+ // here. The post-render scan decides.+ const existing = this.#tabs.get(key);+ if (existing !== undefined && existing !== element) {+ this.#pendingDuplicateChecks.push({+ key,+ first: existing,+ second: element,+ });+ }+ this.#queueStrayContentScan();+ }++ this.#tabs.set(key, element);+ this.#tabKeys.set(element, key);+ // Only the selected tab's own arrival can leave it out of view. Revealing+ // on any registration would drag the strip back while the reader is+ // reading somewhere else in it.+ if (key === this.args.active) {+ this.#queueReveal();+ }+ this.#deferTrackedWrite(() => {+ if (this.#tabs.get(key) === element) {+ this._tabsVersion++;+ }+ });++ return () => {+ if (this.#tabs.get(key) === element) {+ this.#tabs.delete(key);+ // A live @key change tears down and reinstalls inside the tracked+ // update frame, so the bump is deferred like the install's.+ this.#deferTrackedWrite(() => this._tabsVersion++);+ }+ };+ });++ /** Captures the tablist element the declaration block portals into. */+ registerTablist = modifier((element: HTMLElement) => {+ let strayContentObserver: MutationObserver | undefined;+ if (DEBUG) {+ assert(+ "d-tabs: a group renders one Tablist — the <:header> block must place it exactly once",+ this.#tablistActual === null ||+ this.#tablistActual === element ||+ !this.#tablistActual.isConnected+ );+ // Content can enter the tablist without a tab registering. A group+ // whose guard already fired is reported once, not on every mutation+ // of its broken tree.+ strayContentObserver = new MutationObserver(() =>+ this.#queueStrayContentScan()+ );+ strayContentObserver.observe(element, { childList: true });+ }++ this.#tablistActual = element;+ this.#deferTrackedWrite(() => {+ if (this.#tablistActual === element) {+ this.tablistElement = element;+ }+ });++ return () => {+ strayContentObserver?.disconnect();+ if (this.#tablistActual === element) {+ this.#tablistActual = null;+ }+ if (this.tablistElement === element) {+ this.tablistElement = null;+ }+ };+ });++ /**+ * Swap effects keyed on `@active`: reset the panel's scroll and rescue+ * focus when the outgoing content held it.+ *+ * Focus is tracked with listeners, not read at swap time. By then the+ * outgoing content is already gone.+ */+ panelEffects = modifier((element: HTMLElement, [active]: [unknown]) => {+ const onFocusIn = () => (this.#focusWasInPanel = true);+ const onFocusOut = (event: FocusEvent) => {+ if (event.relatedTarget instanceof Node) {+ if (!element.contains(event.relatedTarget)) {+ this.#focusWasInPanel = false;+ }+ return;+ }++ // A null relatedTarget is either a real blur or Chromium removing the+ // focused element. One hop later only the blurred one is still connected.+ const previousTarget = event.target;+ schedule("afterRender", () => {+ if (!(previousTarget instanceof Node)) {+ return;+ }+ if (!previousTarget.isConnected) {+ // Removed by the consumer. A pending swap still rescues, so the+ // flag survives until its destroy effect reads it.+ if (!this.#swapPending) {+ this.#focusWasInPanel = false;+ }+ return;+ }+ if (!element.contains(document.activeElement)) {+ this.#focusWasInPanel = false;+ }+ });+ };+ element.addEventListener("focusin", onFocusIn);+ element.addEventListener("focusout", onFocusOut);++ if (+ this.#lastSwapActive !== NEVER_RENDERED &&+ this.#lastSwapActive !== active+ ) {+ // The outgoing content detaches in the `actions` queue, which the+ // runloop rewinds to after this render. `destroy` is the last queue,+ // so by then focus has already left. Earlier, it still looks held.+ // Being last also means this runs after the incoming content's own+ // effects, so a consumer restoring a per-tab scroll offset on mount+ // must do it after this, not during render.+ this.#swapPending = true;+ schedule("destroy", () => {+ this.#swapPending = false;+ if (isDestroying(this) || !element.isConnected) {+ return;+ }++ element.scrollTop = 0;+ element.scrollLeft = 0;++ // Focus resting on body means the removal dropped it. On a real+ // control, the user moved on.+ if (this.#focusWasInPanel && document.activeElement === document.body) {+ element.focus({ preventScroll: true });+ }+ this.#focusWasInPanel = element.contains(document.activeElement);+ });+ }+ this.#lastSwapActive = active;+ this.#queueReveal();++ return () => {+ element.removeEventListener("focusin", onFocusIn);+ element.removeEventListener("focusout", onFocusOut);+ };+ });+ #uid = dUniqueId();+ #tabs = new Map<string, Element>();++ /**+ * The key each tab element registered under. Read back rather than the+ * `data-d-tab` attribute, which is the same key stringified: a consumer+ * whose ids are not strings would otherwise be handed a different value+ * by the keyboard than by a click.+ */+ #tabKeys = new WeakMap<Element, string>();++ /**+ * Opaque DOM-id suffixes per tab key. Consumer keys cannot go into DOM ids:+ * `aria-labelledby` splits on whitespace, so "account settings" would+ * point at two missing elements.+ */+ #domIdSuffixes = new Map<string, number>();+ #nextDomIdSuffix = 0;++ /**+ * Untracked mirrors written synchronously at modifier install. The tracked+ * twins are written one hop later, because a tracked write from a modifier+ * lands inside the transaction that already read it.+ *+ * The DEBUG guards and the post-render reveal read these, so neither+ * races the deferral.+ */+ #tablistActual: HTMLElement | null = null;+ #panelActual: HTMLElement | null = null;++ /**+ * Whether focus sits inside the tabpanel. Held on the class because the+ * `panelEffects` install closure is torn down and re-run on every+ * `@active` swap, which is exactly when the swap logic needs the value.+ */+ #focusWasInPanel = false;++ /** Whether a swap is between its render and its `destroy` effect. */+ #swapPending = false;++ /** The `@active` the panel effects last saw, to tell swaps from setup. */+ #lastSwapActive: unknown = NEVER_RENDERED;+ #strayScanQueued = false;+ #guardTripped = false;+ #revealQueued = false;++ /** Same-key registrations awaiting the post-render duplicate verdict. */+ #pendingDuplicateChecks: Array<{+ key: string;+ first: Element;+ second: Element;+ }> = [];++ #engine: DTabsEngine = (() => {+ /* eslint-disable-next-line @typescript-eslint/no-this-alias */+ const self = this;++ return {+ get active() {+ return self.args.active;+ },+ get label() {+ return self.args.label;+ },+ get orientation() {+ return self.orientation;+ },+ get hasTabs() {+ return self.hasTabs;+ },+ get panelDomId() {+ return self.panelDomId;+ },+ get panelElement() {+ return self._panelElement;+ },+ get tabsVersion() {+ return self._tabsVersion;+ },+ tabDomIdFor: (key: string) => this.#tabDomIdFor(key),+ activate: (key: string) => this.args.onActivate(key),+ activateFromElement: (item: HTMLElement) => {+ const key = this.#tabKeys.get(item);+ if (key !== undefined) {+ this.args.onActivate(key);+ }+ },+ registerTab: this.registerTab,+ registerTablist: this.registerTablist,+ checkTabLabel: (+ key: string,+ label: string | undefined,+ hasBlock: boolean+ ) => {+ if (DEBUG && (label !== undefined) === hasBlock) {+ this.#guardTripped = true;+ assert(+ `d-tabs: tab "${key}" needs either @label or a <:label> block, and not both`,+ false+ );+ }+ },+ };+ })();+ @tracked _panelElement: HTMLElement | null = null;++ /**+ * Bumped whenever the tab registry changes. The registry is a plain Map, so+ * a getter that reads it must consume this tag to recompute; the `void`+ * reads below are load-bearing, not dead statements.+ */+ @tracked _tabsVersion = 0;++ constructor(owner: Owner, args: DTabsSignature["Args"]) {+ super(owner, args);++ if (DEBUG) {+ assert(+ "d-tabs: @label is required — the tablist needs an accessible name",+ typeof args.label === "string" && args.label.length > 0+ );+ assert(+ "d-tabs: @onActivate is required — selection is controlled by the consumer",+ typeof args.onActivate === "function"+ );++ schedule("afterRender", () => {+ if (isDestroying(this)) {+ return;+ }++ assert(+ "d-tabs: no tablist rendered — a <:header> block must place the yielded Tablist",+ this.#tablistActual !== null+ );+ });+ }+ }++ get orientation(): DTabsOrientation {+ return this.args.orientation ?? "horizontal";+ }++ get hasTabs() {+ void this._tabsVersion;+ return this.#tabs.size > 0;+ }++ get panelDomId() {+ return `d-tabs-${this.#uid}-panel`;+ }++ /**+ * The active tab button's DOM id. `undefined` while `@active` names no+ * registered tab, so the panel never labels itself by a missing element.+ */+ get activeTabDomId() {+ void this._tabsVersion;+ const { active } = this.args;++ if (active === undefined || !this.#tabs.has(active)) {+ return undefined;+ }++ return this.#tabDomIdFor(active);+ }++ /** Names the panel while it has tabs but none of them is selected. */+ get panelAriaLabel() {+ if (this.hasTabs && this.activeTabDomId === undefined) {+ return this.args.label;+ }++ return undefined;+ }++ /**+ * The yielded parts, curried once. Nothing here reads tracked state, so+ * the cache never invalidates and part identity survives re-renders. A+ * new identity would remount every tab's label subtree.+ */+ @cached+ get parts(): { bag: DTabsBag; headerBag: DTabsHeaderBag } {+ const owner = getOwner(this)!;+ const tabs = this.#engine;++ return {+ bag: { Tab: curryComponent(Tab, { tabs }, owner) as DTabsBag["Tab"] },+ headerBag: {+ Tablist: curryComponent(+ Tablist,+ { tabs },+ owner+ ) as DTabsHeaderBag["Tablist"],+ },+ };+ }++ #tabDomIdFor(key: string) {+ let suffix = this.#domIdSuffixes.get(key);+ if (suffix === undefined) {+ suffix = this.#nextDomIdSuffix++;+ this.#domIdSuffixes.set(key, suffix);+ }++ return `d-tabs-${this.#uid}-tab-${suffix}`;+ }++ /**+ * Runs a tracked write after the current render transaction closes. The+ * callback re-checks its own precondition, because a teardown can land+ * between the schedule and the flush.+ */+ #deferTrackedWrite(write: () => void) {+ schedule("afterRender", () => {+ if (isDestroying(this)) {+ return;+ }++ write();+ });+ }++ /** Queues one post-render reveal of the selected tab. */+ #queueReveal() {+ if (this.#revealQueued) {+ return;+ }+ this.#revealQueued = true;++ schedule("afterRender", () => {+ this.#revealQueued = false;+ if (isDestroying(this)) {+ return;+ }++ this.#revealActiveTab();+ });+ }++ /**+ * Scrolls the strip, never the page, until the selected tab is fully+ * inside it.+ */+ #revealActiveTab() {+ const tablist = this.#tablistActual;+ const tab = tablist?.querySelector<HTMLElement>(+ '[role="tab"][aria-selected="true"]'+ );+ if (!tablist || !tab) {+ return;+ }++ revealInScroller(tablist, tab);+ }++ /**+ * Queues one post-render sweep of the tablist for content that is not a+ * tab. Never queued from construction: it must run after the declaration+ * block has actually landed in the tablist. Tab registration queues it,+ * and so do the tablist's own child mutations.+ */+ #queueStrayContentScan() {+ if (this.#strayScanQueued || this.#guardTripped) {+ return;+ }+ this.#strayScanQueued = true;++ schedule("afterRender", () => {+ this.#strayScanQueued = false;+ if (isDestroying(this) || this.#guardTripped || !this.#tablistActual) {+ return;+ }++ try {+ this.#scanDeclaration(this.#tablistActual);+ } catch (error) {+ this.#guardTripped = true;+ throw error;+ }+ });+ }++ #scanDeclaration(tablist: HTMLElement) {+ // By now a branch replacement's predecessor has detached, while a+ // genuine duplicate keeps both claimants attached.+ const pending = this.#pendingDuplicateChecks.splice(0);+ for (const { key, first, second } of pending) {+ assert(+ `d-tabs: duplicate tab key "${key}" — tab keys must be unique within a group`,+ !(first.isConnected && second.isConnected)+ );+ }++ for (const node of tablist.childNodes) {+ // An unregistered role="tab" element is as stray as a div. It would+ // join the keyboard cursor without joining the group. Identity, not the+ // data attribute: the attribute is the key stringified, so a non-string+ // key would fail the lookup and report a stray tab that is not one.+ const registeredKey = node instanceof Element && this.#tabKeys.get(node);+ const isStrayElement =+ node instanceof Element &&+ (node.getAttribute("role") !== "tab" ||+ registeredKey === undefined ||+ this.#tabs.get(registeredKey) !== node);+ const isStrayText =+ node.nodeType === Node.TEXT_NODE &&+ (node.textContent ?? "").trim() !== "";++ assert(+ "d-tabs: the declaration block may contain only tab declarations — found unexpected content in the tablist",+ !isStrayElement && !isStrayText+ );+ }+ }++ <template>+ <div class="d-tabs" ...attributes>+ {{#if (has-block "header")}}+ {{yield this.parts.headerBag to="header"}}+ {{else}}+ <div class="d-tabs__strip"><this.parts.headerBag.Tablist /></div>+ {{/if}}++ <div+ aria-label={{this.panelAriaLabel}}+ aria-labelledby={{this.activeTabDomId}}+ class="d-tabs__panel"+ id={{this.panelDomId}}+ role={{if this.hasTabs "tabpanel"}}+ tabindex={{if this.hasTabs "0"}}+ {{this.registerPanel}}+ {{this.panelEffects @active}}+ ></div>++ <DConditionalInElement @element={{this.tablistElement}}>+ {{yield this.parts.bag}}+ </DConditionalInElement>+ </div>+ </template>+}diff --git a/frontend/discourse/app/ui-kit/d-tabs/-internals/parts/tab.gts b/frontend/discourse/app/ui-kit/d-tabs/-internals/parts/tab.gtsnew file mode 100644index 00000000000..7cdd60d2d9b--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-tabs/-internals/parts/tab.gts@@ -0,0 +1,73 @@+import Component from "@glimmer/component";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import booleanString from "discourse/helpers/boolean-string";+import DConditionalInElement from "discourse/ui-kit/d-conditional-in-element";+import type { DTabsTabSignature } from "discourse/ui-kit/d-tabs/types";++/**+ * One declared tab: the strip button and the panel content, together.+ *+ * The button renders in place. The group portals the declaration block into+ * the tablist, so declaration order is strip order. While the tab is active,+ * its panel content portals into the group's tabpanel.+ */+export default class Tab extends Component<DTabsTabSignature> {+ get domId() {+ return this.args.tabs.tabDomIdFor(this.args.key);+ }++ get isActive() {+ return this.args.key === this.args.tabs.active;+ }++ /**+ * The only guard for a disabled tab. The keyboard engine refuses Enter+ * and Space but does not prevent them, so the browser still synthesizes+ * a click here.+ */+ @action+ click() {+ if (this.args.disabled) {+ return;+ }++ this.args.tabs.activate(this.args.key);+ }++ /**+ * Called from the template as a helper, because only the template knows+ * whether a label block was given.+ */+ @action+ checkLabel(hasLabelBlock: boolean) {+ this.args.tabs.checkTabLabel(this.args.key, this.args.label, hasLabelBlock);+ }++ <template>+ {{! Splattributes come first so the attributes below win. A consumer key+ or role would sever the ARIA pairing. }}+ <button+ class="d-tabs__tab"+ ...attributes+ aria-controls={{@tabs.panelDomId}}+ aria-disabled={{if @disabled "true"}}+ aria-selected={{booleanString this.isActive omitFalse=false}}+ data-d-tab={{@key}}+ id={{this.domId}}+ role="tab"+ type="button"+ {{on "click" this.click}}+ {{@tabs.registerTab @key}}+ >+ {{this.checkLabel (has-block "label")}}+ {{#if (has-block "label")}}{{yield to="label"}}{{else}}{{@label}}{{/if}}+ </button>++ {{#if this.isActive}}+ <DConditionalInElement @append={{true}} @element={{@tabs.panelElement}}>+ {{yield}}+ </DConditionalInElement>+ {{/if}}+ </template>+}diff --git a/frontend/discourse/app/ui-kit/d-tabs/-internals/parts/tablist.gts b/frontend/discourse/app/ui-kit/d-tabs/-internals/parts/tablist.gtsnew file mode 100644index 00000000000..eae7ffac0f0--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-tabs/-internals/parts/tablist.gts@@ -0,0 +1,54 @@+import Component from "@glimmer/component";+import { and } from "discourse/truth-helpers";+import DOverflowControls from "discourse/ui-kit/d-overflow-controls";+import type { DTabsTablistSignature } from "discourse/ui-kit/d-tabs/types";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";++/**+ * The tablist element: the keyboard surface and ARIA container the group's+ * tab buttons render into.+ *+ * It renders empty. The core portals the declaration block into it, so a+ * `<:header>` block can place it anywhere.+ *+ * The tablist role is withheld while no tab is registered, because an+ * empty tablist violates its required contents.+ */+export default class Tablist extends Component<DTabsTablistSignature> {+ get isVertical() {+ return this.args.tabs.orientation === "vertical";+ }++ <template>+ <DOverflowControls+ @axis={{@tabs.orientation}}+ @ownedScroller={{true}}+ @wrapperClass="d-tabs__strip-controls"+ as |strip|+ >+ {{! Splattributes come first so the role below stays authoritative. }}+ {{! The role is dynamic, so the linter only sees a bare div and would+ strip the orientation it cannot match to the tablist role. }}+ {{! eslint-disable-next-line ember/template-no-unsupported-role-attributes }}+ <div+ class="d-tabs__tablist"+ ...attributes+ aria-label={{if @tabs.hasTabs @tabs.label}}+ aria-orientation={{if (and @tabs.hasTabs this.isVertical) "vertical"}}+ role={{if @tabs.hasTabs "tablist"}}+ {{dRovingFocus+ itemSelector="[role='tab']"+ wrap=true+ tabStopAnchor="selection"+ disabledItems="focusable"+ }}+ {{@tabs.registerTablist}}+ {{strip.scroller}}+ ></div>+ </DOverflowControls>+ </template>+}diff --git a/frontend/discourse/app/ui-kit/d-tabs/README.md b/frontend/discourse/app/ui-kit/d-tabs/README.mdnew file mode 100644index 00000000000..6c22a24a7c2--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-tabs/README.md@@ -0,0 +1,53 @@+# DTabs++`d-tabs.gts` is the entry and the only import path. This directory holds the+collaborators it renders with.++| File | Owns |+| --- | --- |+| `types.ts` | The public signatures and the argument reference the entry points at. |+| `-internals/parts/tablist.gts` | The `role="tablist"` element, the keyboard engine, and the scroll strip wrapped around it. |+| `-internals/parts/tab.gts` | One `role="tab"` button, and the guard that makes a disabled tab inert. |++## Invariants that cross these files++**One portal, rendered once.** The tablist part registers its element into+tracked state, and the entry portals the *whole* declaration block into it in a+single `{{#in-element}}`. Each `tabs.Tab` then renders its button in place, so+declaration order is DOM order by construction rather than by sorting. Splitting+this into a portal per tab would reintroduce the ordering problem it exists to+avoid.++**Nothing renders until the tablist exists.** The portal target starts `null`, so+a `<:header>` block that never places the yielded `Tablist` renders no tabs at+all rather than falling back to a strip of its own. A DEBUG assert after the+first render catches that, because the failure is otherwise total and silent:+the widget renders the header's own markup and an empty panel. Placement is+therefore required on the first render, not merely eventually.++**Tracked writes from modifiers are deferred one hop.** A modifier installing+during render cannot write tracked state that the same render already read, so+the register modifiers schedule their writes to `afterRender` and keep untracked+mirrors (`#tablistActual`, `#panelActual`) for anything that must read the value+synchronously. Static analysis will suggest the deferral is unnecessary. It is+not; removing it trips the backtracking assertion.++**Cleanups are identity-guarded.** Ember defers destructors, so a cleanup can run+*after* its successor has already registered. Every `register*` teardown checks+that the entry still points at its own element before clearing it.++**Keys round-trip by element identity, not by attribute.** `data-d-tab` is the+key stringified. Reading it back would hand a consumer with non-string keys a+different value from the keyboard than from a click, so the registry is consulted+by element instead. The keys a consumer supplies never become DOM ids either:+the widget mints its own, which is why two groups may reuse the same key.++**The panel is mounted once and never replaced.** Content is portalled into it in+append mode, which never clears the target, so there is no swap race. Activation+resets its scroll offset and rescues focus if the outgoing content held it.++## Deliberately absent++There is no `@activation` argument. Arrow keys move focus without selecting, and+automatic activation would land additively through the keyboard engine's own+`onActiveChange` rather than as a placeholder argument here.diff --git a/frontend/discourse/app/ui-kit/d-tabs/types.ts b/frontend/discourse/app/ui-kit/d-tabs/types.tsnew file mode 100644index 00000000000..8eaca9d35b2--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-tabs/types.ts@@ -0,0 +1,188 @@+import type { ComponentLike, ModifierLike } from "@glint/template";++/** The arrow-key axis of the tab strip. */+export type DTabsOrientation = "horizontal" | "vertical";++/**+ * The live state and controls one `DTabs` instance shares with its parts.+ *+ * Internal contract between the core and its `-internals` parts; consumers+ * never see it because the curried parts erase the `tabs` argument.+ */+export interface DTabsEngine {+ /** The controlled active tab key. */+ readonly active: string | undefined;++ /** The tablist's accessible name. */+ readonly label: string;++ /** The resolved orientation, defaulted to `"horizontal"`. */+ readonly orientation: DTabsOrientation;++ /** Whether any tab is currently registered. */+ readonly hasTabs: boolean;++ /** The persistent tabpanel's DOM id, minted once per instance. */+ readonly panelDomId: string;++ /** The persistent tabpanel element, once it has rendered. */+ readonly panelElement: HTMLElement | null;++ /** Reactivity key that changes whenever the registered tab set does. */+ readonly tabsVersion: number;++ /** Derives the DOM id a tab with the given key renders under. */+ tabDomIdFor(key: string): string;++ /** Requests activation of the given tab through the consumer's callback. */+ activate(key: string): void;++ /** Bridges the roving-focus engine's element reports back to tab keys. */+ activateFromElement(item: HTMLElement): void;++ /** Element modifier a tab button applies to join the registry. */+ registerTab: ModifierLike<{+ Element: HTMLElement;+ Args: { Positional: [key: string] };+ }>;++ /** Element modifier the tablist part applies to become the portal target. */+ registerTablist: ModifierLike<{+ Element: HTMLElement;+ Args: { Positional: [] };+ }>;++ /** Asserts in DEBUG that exactly one of `@label` and the `<:label>` block was given. */+ checkTabLabel(+ key: string,+ label: string | undefined,+ hasBlock: boolean+ ): void;+}++/**+ * What the default block receives: the tab declaration part.+ *+ * Typed as the consumer surface. The curried engine argument is omitted,+ * not optional, so a consumer cannot wire a tab into another group's+ * registry.+ */+export interface DTabsBag {+ /** Declares one tab: its strip button and its panel content together. */+ Tab: ComponentLike<{+ Element: DTabsTabSignature["Element"];+ Args: Omit<DTabsTabSignature["Args"], "tabs">;+ Blocks: DTabsTabSignature["Blocks"];+ }>;+}++/** What the `<:header>` block receives: the placeable tablist. */+export interface DTabsHeaderBag {+ /**+ * The tablist, pre-wired with the keyboard engine. Placing it renders the+ * strip's scroll wrapper around the tablist element, so a header row lays+ * out that wrapper; splattributes still land on the tablist itself.+ *+ * Place it exactly once, on the first render, and keep it in that place:+ * nothing renders until it exists, and moving it between branches remounts+ * every tab and the active panel content. Placing it behind a condition+ * that starts false is a DEBUG error, not a way to defer the strip.+ */+ Tablist: ComponentLike<{ Element: DTabsTablistSignature["Element"] }>;+}++export interface DTabsSignature {+ /** The widget root: a column of the strip row and the persistent panel. */+ Element: HTMLDivElement;+ Args: {+ /**+ * The key of the selected tab. Controlled only: the component holds no+ * selection state and never picks a fallback. `undefined`, or a key no+ * declared tab carries, selects nothing and leaves the panel empty. The+ * argument is required, so a typed consumer with nothing selected+ * passes `undefined` explicitly.+ */+ active: string | undefined;++ /**+ * Called with the key of the tab the user activates. Activation is+ * manual: arrow keys only move focus, and a tab is selected by click,+ * Enter, or Space.+ */+ onActivate: (key: string) => void;++ /**+ * The tablist's accessible name, already translated. Required: an+ * unnamed tablist is announced as an anonymous group.+ */+ label: string;++ /**+ * The arrow-key axis. `"vertical"` also announces the orientation,+ * which assistive technology otherwise assumes horizontal. It is also+ * the strip's scroll axis: the chevrons and the edge fade follow it.+ */+ orientation?: DTabsOrientation;+ };+ Blocks: {+ /**+ * The tabs, declared as `Tab` children in display order. The block+ * renders inside the tablist element, so it may contain only tab+ * declarations and the control flow around them.+ */+ default: [tabs: DTabsBag];++ /**+ * Replaces the default strip row. The block must place the yielded+ * `Tablist` on the first render and exactly once; the tabs render+ * inside it, so a block that omits it renders no tabs at all. With this+ * block present, the tabs go in an explicit `<:default>` block.+ */+ header: [header: DTabsHeaderBag];+ };+}++/** The signature of the curried `Tab` part. */+export interface DTabsTabSignature {+ /** The real tab button; splattributes and modifiers land on it. */+ Element: HTMLButtonElement;+ Args: {+ /** The engine of the owning group, curried by the core. */+ tabs: DTabsEngine;++ /**+ * Stable identity for selection, unique within this group. Not a DOM id:+ * the widget mints its own, so two groups may reuse the same key.+ */+ key: string;++ /**+ * The button's text. Exactly one of this and the `<:label>` block must+ * be given.+ */+ label?: string;++ /**+ * Announces the tab as unavailable. It stays focusable so it stays+ * discoverable, but it never activates.+ */+ disabled?: boolean;+ };+ Blocks: {+ /** The panel content, mounted only while this tab is active. */+ default: [];++ /** Arbitrary label content, rendered inside the button. */+ label: [];+ };+}++/** The signature of the curried `Tablist` part. */+export interface DTabsTablistSignature {+ /** The tablist element itself; splattributes land on it. */+ Element: HTMLDivElement;+ Args: {+ /** The engine of the owning group, curried by the core. */+ tabs: DTabsEngine;+ };+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.tsindex 01bd29ea6ff..3aea68e1a02 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.ts@@ -57,7 +57,8 @@ export type {** - `"roving-tabindex"` (the default) — exactly one item is reachable with Tab* (`tabindex="0"`) and the rest are set to `tabindex="-1"`; with `tabStop=false` every item is- * set to `-1`. Arrow keys move real DOM focus between items and update tabindex along with it.+ * set to `-1`. Arrow keys move real DOM focus between items and, unless `tabStopAnchor` pins the+ * stop to the marked item, update tabindex along with it.* Use this when the active item should itself hold focus (a tile grid, a toolbar).* - `"active-descendant"` — DOM focus stays on a separate controller* element (typically a text input); arrow keys move a *virtual* highlight throughdiff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/config.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/config.tsindex 24ce319d723..2795cdf4a2e 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/config.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/config.ts@@ -3,6 +3,7 @@ import type {DRovingFocusDisabledItems,DRovingFocusEntry,DRovingFocusStrategy,+ DRovingFocusTabStopAnchor,Orientation,} from "./types";@@ -22,6 +23,7 @@ export interface DRovingFocusConfig {onRegisterApi: DRovingFocusArgs["onRegisterApi"];wrap: boolean;tabStop: boolean;+ tabStopAnchor: DRovingFocusTabStopAnchor;restoreLostFocus: boolean;activeClass: string | null;itemsKey: unknown;@@ -51,6 +53,7 @@ export function normalizeConfig(named: DRovingFocusArgs): DRovingFocusConfig {onRegisterApi: named.onRegisterApi,wrap: named.wrap ?? false,tabStop: named.tabStop ?? true,+ tabStopAnchor: named.tabStopAnchor ?? "focus",restoreLostFocus: named.restoreLostFocus ?? true,activeClass: named.activeClass ?? null,// This read is load-bearing even though the value is never consulted: consuming thediff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/entry-policy.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/entry-policy.tsindex 0a908dcf377..21059643e67 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/entry-policy.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/entry-policy.ts@@ -13,6 +13,15 @@ export function prefersSelected(config: DRovingFocusConfig): boolean {);}+/**+ * Returns whether the Tab stop belongs to the marked item rather than to whatever focus reached.+ * The stop is then re-derived on every seed, so a cursor left elsewhere never becomes the entry+ * point.+ */+export function anchorsToSelection(config: DRovingFocusConfig): boolean {+ return config.tabStopAnchor === "selection";+}+/** Returns whether entry may fall back to the first eligible item. */export function fallsBackToFirst(config: DRovingFocusConfig): boolean {return (diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/roving-tabindex.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/roving-tabindex.tsindex dc6b0acbcee..1316aad79a9 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/roving-tabindex.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/roving-tabindex.ts@@ -1,5 +1,6 @@import type { DRovingFocusConfig } from "../config";import {+ anchorsToSelection,fallsBackToFirst,findMarked,isMarked,@@ -53,16 +54,24 @@ export default class RovingTabindexStrategy {return items.find((item) => item.getAttribute("tabindex") === "0") ?? null;}- /** Records focus that entered an item and promotes it as the tab stop. */+ /**+ * Records focus that entered an item and promotes it as the tab stop. Anchored to selection the+ * promotion is skipped, but the item is still remembered, because restoration answers "where was+ * the reader" rather than "where does Tab return".+ */recordFocus(target: HTMLElement): void {- this.#promote(target);+ if (!anchorsToSelection(this.#config)) {+ this.#promote(target);+ }this.#lastFocusedItem = target;this.#lastFocusedIndex = this.#scope.all().indexOf(target);}- /** Promotes an item and moves DOM focus to it. */+ /** Promotes an item and moves DOM focus to it, or moves focus alone when anchored to selection. */activate(target: HTMLElement): void {- this.#promote(target);+ if (!anchorsToSelection(this.#config)) {+ this.#promote(target);+ }target.focus();}@@ -77,10 +86,13 @@ export default class RovingTabindexStrategy {let preferred: HTMLElement | undefined;if (this.#config.tabStop) {const navigable = (item: HTMLElement) => this.#scope.isNavigable(item);- const current = reseed ? null : this.current(all);+ // Anchoring to selection is a standing reseed: honouring a surviving cursor is exactly what+ // it exists to prevent, so the entry policy alone decides where the stop sits.+ const fresh = reseed || anchorsToSelection(this.#config);+ const current = fresh ? null : this.current(all);preferred =(current && navigable(current) ? current : undefined) ??- (reseed+ (fresh? undefined: all.find((item) => item.getAttribute("tabindex") === "0" && navigable(item)diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/types.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/types.tsindex 70b5791c852..87719ace275 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/types.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/types.ts@@ -118,6 +118,12 @@ export type DRovingFocusEntry =| "selected-or-first"| "selected-or-none";+/**+ * What the Tab stop tracks in focus mode: `"focus"` moves it to whatever the cursor reaches,+ * `"selection"` leaves it on the marked item however far focus travels.+ */+export type DRovingFocusTabStopAnchor = "focus" | "selection";+/*** The outcome of an API-driven step: `"moved"` when the cursor advanced, `"edge"` when a cursor* exists but is already against a boundary, and `"unavailable"` when the group has no items at@@ -222,6 +228,25 @@ export interface DRovingFocusArgs {* Shape dictated by: Navigation Between Components, the single-tab-stop contract.*/tabStop?: boolean;+ /**+ * Focus mode: what the Tab stop tracks (default `"focus"`).+ *+ * `"focus"` is the roving convention: the item the cursor reaches becomes the one Tab returns+ * to. `"selection"` pins the stop to the marked item instead, so arrow keys move focus while+ * Tab still comes back to the chosen value.+ *+ * Reach for `"selection"` only where a pattern says entry belongs to the chosen value rather+ * than to wherever the reader last looked, which in practice means a group whose arrow keys do+ * not themselves choose. Tabs with manual activation are the case it exists for: arrowing+ * explores without selecting, and leaving must not strand the reader on a tab whose panel is+ * not the one on screen. Where arrows do choose, the two settings agree anyway, because+ * whatever focus reaches is also what is marked.+ *+ * Ignored under `focusStrategy="active-descendant"`, which has no Tab stop to place.+ *+ * Shape dictated by: the tabs pattern, whose entry convention is the active tab.+ */+ tabStopAnchor?: DRovingFocusTabStopAnchor;/*** Focus mode: whether removing the item that holds focus moves the cursor to the item that* took its place, rather than letting focus fall to `body` (default `true`).diff --git a/frontend/discourse/app/ui-kit/modifiers/d-scroll-edges.ts b/frontend/discourse/app/ui-kit/modifiers/d-scroll-edges.tsnew file mode 100644index 00000000000..49303e10a00--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-scroll-edges.ts@@ -0,0 +1,73 @@+import { registerDestructor } from "@ember/destroyable";+import type Owner from "@ember/owner";+import Modifier, { type ArgsFor } from "ember-modifier";+import {+ type ScrollAxis,+ ScrollEdgesWatcher,+} from "discourse/ui-kit/-internals/scroll-strip/edges";++/** The axis `dScrollEdges` reports on. */+export type DScrollEdgesAxis = ScrollAxis;++interface DScrollEdgesSignature {+ /** The scroll container being observed. */+ Element: HTMLElement;+ Args: {+ Named: {+ /** The scroll axis to report on. Defaults to `"horizontal"`. */+ axis?: ScrollAxis;+ };+ Positional: [];+ };+}++/**+ * Stamps a scroll container's overflow state onto it as data attributes, so+ * a stylesheet can hint at content beyond an edge without any of the+ * measuring living in CSS:+ *+ * - `data-d-scroll-axis`, the axis being reported;+ * - `data-d-scroll-overflow` while the content is larger than the container;+ * - `data-d-scroll-at-start` while it rests on its start edge;+ * - `data-d-scroll-at-end` while it rests on its end edge.+ *+ * The state follows scrolling, the container resizing, children coming and+ * going, and children changing size, which covers a web font swapping in+ * after first paint. Offsets are read as magnitudes, so a right-to-left+ * container reports the same logical edges. An axis the container's+ * computed overflow does not let it scroll on is never reported as+ * overflowing.+ */+export default class DScrollEdgesModifier extends Modifier<DScrollEdgesSignature> {+ #element: HTMLElement | null = null;+ #axis: ScrollAxis | null = null;+ #watcher: ScrollEdgesWatcher | null = null;++ constructor(owner: Owner, args: ArgsFor<DScrollEdgesSignature>) {+ super(owner, args);+ registerDestructor(this, () => this.#teardown());+ }++ modify(+ element: HTMLElement,+ _positional: [],+ { axis = "horizontal" }: DScrollEdgesSignature["Args"]["Named"]+ ) {+ if (this.#element !== element || this.#axis !== axis) {+ this.#teardown();+ this.#element = element;+ this.#axis = axis;+ this.#watcher = new ScrollEdgesWatcher(element, { axis });+ return;+ }++ this.#watcher?.refresh();+ }++ #teardown() {+ this.#watcher?.disconnect();+ this.#watcher = null;+ this.#element = null;+ this.#axis = null;+ }+}diff --git a/frontend/discourse/tests/integration/ui-kit/d-horizontal-overflow-nav-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-horizontal-overflow-nav-test.gjsnew file mode 100644index 00000000000..455aa81f54d--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/d-horizontal-overflow-nav-test.gjs@@ -0,0 +1,561 @@+import { tracked } from "@glimmer/tracking";+import {+ click,+ find,+ render,+ settled,+ triggerEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import { resetSiteDirForTesting } from "discourse/lib/text-direction";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import { stubPointerCapture } from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";+import { eq } from "discourse/truth-helpers";+import DHorizontalOverflowNav from "discourse/ui-kit/d-horizontal-overflow-nav";++const ITEMS = Array.from({ length: 10 }, (_, index) => `Item ${index + 1}`);++class PortalState {+ @tracked show = false;+ @tracked target = null;+}++const LateNavItems = <template>+ {{#if @state.show}}+ {{#in-element @state.target}}+ {{#each @items as |item index|}}+ <li style="flex: 0 0 80px">+ <a+ class={{if (eq index 7) "active"}}+ href="#late-{{item}}"+ >{{item}}</a>+ </li>+ {{/each}}+ {{/in-element}}+ {{/if}}+</template>;++function nextFrame() {+ return new Promise((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(resolve))+ );+}++function requireList(assert, selector = "ul.nav-pills") {+ assert.dom(selector).exists({ count: 1 }, "the navigation list renders");+ return find(selector);+}++function requireActive(assert, selector = "a.active") {+ assert+ .dom(selector)+ .exists({ count: 1 }, "the active navigation item renders");+ return find(selector);+}++function stubReducedMotion(matches) {+ return sinon.stub(window, "matchMedia").returns({ matches });+}++async function scrollTo(selector, props) {+ const element = find(selector);+ Object.assign(element, props);+ await triggerEvent(element, "scroll");+}++module("Integration | ui-kit | DHorizontalOverflowNav", function (hooks) {+ setupRenderingTest(hooks);++ let rtlEnabled = false;++ hooks.afterEach(function () {+ if (rtlEnabled) {+ document.documentElement.classList.remove("rtl");+ resetSiteDirForTesting();+ rtlEnabled = false;+ }+ });++ test("overflow strip: preserves the nav and consumer-owned list structure", async function (assert) {+ await render(+ <template>+ <DHorizontalOverflowNav+ class="consumer-attribute"+ data-consumer="yes"+ @ariaLabel="Section navigation"+ @className="consumer-class"+ >+ <li><a href="#one">One</a></li>+ </DHorizontalOverflowNav>+ </template>+ );++ const nav = find("nav.horizontal-overflow-nav");+ const controls = find(+ ".d-overflow-controls.--owned-scroller.horizontal-overflow-nav__controls"+ );+ const list = requireList(assert, "ul.nav-pills.action-list");++ assert+ .dom("nav.horizontal-overflow-nav")+ .hasAttribute("aria-label", "Section navigation", "the nav is outermost");+ assert+ .dom(+ ".d-overflow-controls.--owned-scroller.horizontal-overflow-nav__controls"+ )+ .exists("the nav uses owned overflow controls");+ assert.dom(nav).exists("the navigation landmark renders");+ assert.strictEqual(+ controls.parentElement,+ nav,+ "the overflow controls are directly inside the nav"+ );+ assert.strictEqual(+ list.parentElement,+ controls,+ "the consumer-owned list is directly inside the controls"+ );+ assert.dom(list).hasClass("consumer-class", "@className lands on the list");+ assert+ .dom(list)+ .hasClass(+ "consumer-attribute",+ "the class splattribute lands on the list"+ );+ assert+ .dom(list)+ .hasAttribute(+ "data-consumer",+ "yes",+ "other splattributes land on the list"+ );+ assert+ .dom(".d-overflow-controls__content")+ .doesNotExist("owned mode renders no generated content scroller");+ });++ test("overflow strip: exposes the wrapper fade width as the nav scale", async function (assert) {+ await render(+ <template>+ <DHorizontalOverflowNav @ariaLabel="Fade width navigation">+ <li><a href="#one">One</a></li>+ </DHorizontalOverflowNav>+ </template>+ );++ const controls = find(".horizontal-overflow-nav__controls");+ assert.strictEqual(+ getComputedStyle(controls).getPropertyValue("--fade-width").trim(),+ "1.5em",+ "the wrapper exposes the nav-specific fade width"+ );+ });++ test("overflow strip: fades the physical trailing edge at logical start", async function (assert) {+ await render(+ <template>+ <div style="width: 200px">+ <DHorizontalOverflowNav @ariaLabel="LTR fade navigation">+ {{#each ITEMS as |item|}}+ <li style="flex: 0 0 80px"><a href="#{{item}}">{{item}}</a></li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>+ </template>+ );+ await nextFrame();++ let list = requireList(assert);+ let styles = getComputedStyle(list);+ let maskImage = styles.maskImage || styles.webkitMaskImage;+ assert.true(+ maskImage.startsWith("linear-gradient(to right"),+ "LTR logical start fades the physical right edge"+ );++ document.documentElement.classList.add("rtl");+ resetSiteDirForTesting();+ rtlEnabled = true;+ await render(+ <template>+ <div dir="rtl" style="width: 200px">+ <DHorizontalOverflowNav @ariaLabel="RTL fade navigation">+ {{#each ITEMS as |item|}}+ <li style="flex: 0 0 80px"><a+ href="#rtl-{{item}}"+ >{{item}}</a></li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>+ </template>+ );+ await nextFrame();++ list = requireList(assert);+ styles = getComputedStyle(list);+ maskImage = styles.maskImage || styles.webkitMaskImage;+ assert.strictEqual(+ getComputedStyle(list).direction,+ "rtl",+ "the list is RTL"+ );+ assert.true(+ maskImage.startsWith("linear-gradient(to left"),+ "RTL logical start fades the physical left edge"+ );+ });++ test("overflow strip: buttons follow the horizontal scroll edges", async function (assert) {+ await render(+ <template>+ <div style="width: 200px">+ <DHorizontalOverflowNav @ariaLabel="Fitting navigation">+ <li style="flex: 0 0 80px"><a href="#one">One</a></li>+ <li style="flex: 0 0 80px"><a href="#two">Two</a></li>+ </DHorizontalOverflowNav>+ </div>+ </template>+ );+ await nextFrame();++ assert+ .dom(".d-overflow-controls__btn")+ .doesNotExist("a fitting list renders no buttons");++ await render(+ <template>+ <div style="width: 200px">+ <DHorizontalOverflowNav @ariaLabel="Overflowing navigation">+ {{#each ITEMS as |item|}}+ <li style="flex: 0 0 80px"><a href="#{{item}}">{{item}}</a></li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>+ </template>+ );+ await nextFrame();++ assert+ .dom(+ ".d-overflow-controls__btn.--right.horizontal-overflow-nav__scroll-right"+ )+ .exists("the physical right button appears at the start");+ assert+ .dom(".d-overflow-controls__btn.--left")+ .doesNotExist("the physical left button is absent at the start");++ const list = find("ul.nav-pills");+ await scrollTo("ul.nav-pills", {+ scrollLeft: list.scrollWidth - list.clientWidth,+ });+ await nextFrame();++ assert+ .dom(+ ".d-overflow-controls__btn.--left.horizontal-overflow-nav__scroll-left"+ )+ .exists("the physical left button appears at the end");+ assert+ .dom(".d-overflow-controls__btn.--right")+ .doesNotExist("the physical right button is absent at the end");+ });++ test("overflow strip: a plain click scrolls one viewport", async function (assert) {+ const matchMediaStub = stubReducedMotion(false);+ await render(+ <template>+ <div style="width: 200px">+ <DHorizontalOverflowNav @ariaLabel="Clickable navigation">+ {{#each ITEMS as |item|}}+ <li style="flex: 0 0 80px"><a href="#{{item}}">{{item}}</a></li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>+ </template>+ );+ await nextFrame();++ const list = requireList(assert);+ const button = find(".d-overflow-controls__btn.--right");+ assert.dom(button).exists("the trailing shared button is available");+ let target;+ list.scrollTo = (options) => (target = options);++ await click(button);++ assert.deepEqual(+ target,+ { left: list.clientWidth, behavior: "smooth" },+ "one click requests exactly one measured viewport"+ );+ matchMediaStub.restore();+ });++ test("overflow strip: mouse hold scrolls continuously and swallows its click once", async function (assert) {+ await render(+ <template>+ <div style="width: 200px">+ <DHorizontalOverflowNav @ariaLabel="Hold navigation">+ {{#each ITEMS as |item|}}+ <li style="flex: 0 0 80px"><a href="#{{item}}">{{item}}</a></li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>+ </template>+ );+ await nextFrame();++ const list = requireList(assert);+ const button = find(".d-overflow-controls__btn.--right");+ assert.dom(button).exists("the trailing shared button is available");+ stubPointerCapture(button);++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "mouse",+ });+ await nextFrame();++ assert.true(list.scrollLeft > 0, "the hold advances the strip");+ const firstOffset = list.scrollLeft;++ await nextFrame();+ assert.true(+ list.scrollLeft > firstOffset,+ "the hold continues advancing on later frames"+ );++ await triggerEvent(button, "pointerup", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "mouse",+ });++ let clicks = 0;+ list.scrollTo = () => clicks++;+ await click(button);+ assert.strictEqual(clicks, 0, "the click following a hold is swallowed");++ await click(button);+ assert.strictEqual(clicks, 1, "the next plain click scrolls exactly once");+ });++ test("overflow strip: late portaled items are measured and reveal the active item", async function (assert) {+ const state = new PortalState();++ await render(+ <template>+ <div style="width: 200px">+ <DHorizontalOverflowNav id="late-nav" @ariaLabel="Late navigation" />+ </div>+ <LateNavItems @items={{ITEMS}} @state={{state}} />+ </template>+ );++ const list = find("#late-nav");+ const nativeScrollTo = list.scrollTo.bind(list);+ let revealCalls = 0;+ list.scrollTo = (options) => {+ revealCalls++;+ nativeScrollTo(options);+ };+ state.target = list;+ state.show = true;+ await settled();+ await nextFrame();++ assert+ .dom("#late-nav")+ .hasAttribute(+ "data-d-scroll-overflow",+ "",+ "the list reports overflow after portal insertion"+ );+ assert+ .dom(".d-overflow-controls__btn.--right")+ .exists("the trailing button appears after portal insertion");+ assert.strictEqual(+ revealCalls,+ 1,+ "the first late active item is revealed exactly once"+ );+ const active = requireActive(assert, "#late-nav a.active");+ const listRect = list.getBoundingClientRect();+ const activeRect = active.getBoundingClientRect();+ assert.true(list.scrollLeft > 0, "the late active item moves the strip");+ assert.true(+ activeRect.left >= listRect.left - 1,+ "the late active item's leading edge is inside the strip"+ );+ assert.true(+ activeRect.right <= listRect.right + 1,+ "the late active item's trailing edge is inside the strip"+ );+ assert.true(+ Math.abs(+ (activeRect.left + activeRect.right) / 2 -+ (listRect.left + listRect.right) / 2+ ) <= 1,+ "the late active item is centered in the strip"+ );+ });++ test("overflow strip: mount reveal centers the active item without moving the page", async function (assert) {+ const pageScroll = window.scrollY;++ await render(+ <template>+ <div style="width: 200px">+ <DHorizontalOverflowNav @ariaLabel="Active navigation">+ {{#each ITEMS as |item index|}}+ <li style="flex: 0 0 80px">+ <a+ class={{if (eq index 7) "active"}}+ href="#{{item}}"+ >{{item}}</a>+ </li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>+ </template>+ );++ await nextFrame();++ const list = requireList(assert);+ const active = requireActive(assert);+ assert+ .dom(".d-overflow-controls.--owned-scroller")+ .exists("the active list owns the shared scroller");+ const listRect = list.getBoundingClientRect();+ const activeRect = active.getBoundingClientRect();++ assert.true(list.scrollLeft > 0, "the strip moves toward the active item");+ assert.true(+ activeRect.left >= listRect.left - 1,+ "the active item's leading edge lies inside the strip"+ );+ assert.true(+ activeRect.right <= listRect.right + 1,+ "the active item's trailing edge lies inside the strip"+ );+ assert.true(+ Math.abs(+ (activeRect.left + activeRect.right) / 2 -+ (listRect.left + listRect.right) / 2+ ) <= 1,+ "the active item is centered in the strip"+ );+ assert.strictEqual(window.scrollY, pageScroll, "the page does not move");+ });++ test("overflow strip: RTL maps logical start to the physical left button", async function (assert) {+ const matchMediaStub = stubReducedMotion(false);+ document.documentElement.classList.add("rtl");+ resetSiteDirForTesting();+ rtlEnabled = true;++ await render(+ <template>+ <div dir="rtl" style="width: 200px">+ <DHorizontalOverflowNav @ariaLabel="RTL navigation">+ {{#each ITEMS as |item|}}+ <li style="flex: 0 0 80px"><a href="#{{item}}">{{item}}</a></li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>+ </template>+ );+ await nextFrame();++ assert+ .dom(".d-overflow-controls__btn.--left")+ .exists("the physical left button appears at logical start");+ assert+ .dom(".d-overflow-controls__btn.--right")+ .doesNotExist("the physical right button is absent at logical start");++ const list = requireList(assert);+ const button = find(".d-overflow-controls__btn.--left");+ assert.dom(button).exists("the logical trailing button renders");+ assert.strictEqual(+ getComputedStyle(list).direction,+ "rtl",+ "the fixture list resolves to RTL"+ );+ let target;+ list.scrollTo = (options) => (target = options);+ await click(button);++ assert.deepEqual(+ target,+ { left: -list.clientWidth, behavior: "smooth" },+ "the physical left button requests one negative viewport"+ );+ matchMediaStub.restore();+ });++ test("overflow strip: RTL mount reveal keeps the active item inside the list", async function (assert) {+ document.documentElement.classList.add("rtl");+ resetSiteDirForTesting();+ rtlEnabled = true;+ const pageScroll = window.scrollY;++ await render(+ <template>+ <div dir="rtl" style="width: 200px">+ <DHorizontalOverflowNav @ariaLabel="RTL active navigation">+ {{#each ITEMS as |item index|}}+ <li style="flex: 0 0 80px">+ <a+ class={{if (eq index 7) "active"}}+ href="#{{item}}"+ >{{item}}</a>+ </li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>+ </template>+ );++ await nextFrame();++ const list = requireList(assert);+ const active = requireActive(assert);+ assert+ .dom(".d-overflow-controls.--owned-scroller")+ .exists("the RTL list owns the shared scroller");+ assert.deepEqual(+ {+ direction: getComputedStyle(list).direction,+ overflows: list.scrollWidth > list.clientWidth,+ },+ { direction: "rtl", overflows: true },+ "the fixture is an overflowing RTL scroller"+ );+ const listRect = list.getBoundingClientRect();+ const activeRect = active.getBoundingClientRect();++ assert.true(list.scrollLeft < 0, "the RTL strip uses a negative offset");+ assert.true(+ activeRect.left >= listRect.left - 1,+ "the active item's leading edge lies inside the RTL strip"+ );+ assert.true(+ activeRect.right <= listRect.right + 1,+ "the active item's trailing edge lies inside the RTL strip"+ );+ assert.true(+ Math.abs(+ (activeRect.left + activeRect.right) / 2 -+ (listRect.left + listRect.right) / 2+ ) <= 1,+ "the active item is centered in the RTL strip"+ );+ assert.strictEqual(window.scrollY, pageScroll, "the page does not move");+ });+});diff --git a/frontend/discourse/tests/integration/ui-kit/d-overflow-controls-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-overflow-controls-test.gjsindex 14dd94c4cd6..14153a77b3f 100644--- a/frontend/discourse/tests/integration/ui-kit/d-overflow-controls-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/d-overflow-controls-test.gjs@@ -1,8 +1,68 @@-import { click, render, triggerEvent } from "@ember/test-helpers";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import {+ click,+ find,+ render,+ resetOnerror,+ settled,+ setupOnerror,+ triggerEvent,+} from "@ember/test-helpers";import { module, test } from "qunit";+import sinon from "sinon";import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import { stubPointerCapture } from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";import DOverflowControls from "discourse/ui-kit/d-overflow-controls";+const EDGE_BUTTON_CLASSES = {+ left: "consumer-left",+ right: "consumer-right",+ up: "consumer-up",+ down: "consumer-down",+};++class ConditionalScrollerState {+ @tracked show = false;++ scrollToEnd = (element) => (element.scrollLeft = element.scrollWidth);+}++class RevealState {+ capture = (strip, element) => {+ this.strip = strip;+ this.target = element;+ };++ strip = null;+ target = null;+}++function nextFrame() {+ return new Promise((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(resolve))+ );+}++function layoutOffset(element) {+ let x = 0;+ let y = 0;+ let node = element;++ while (node) {+ x += node.offsetLeft;+ y += node.offsetTop;+ node = node.offsetParent instanceof HTMLElement ? node.offsetParent : null;+ }++ return { x, y };+}++function stubReducedMotion(matches) {+ return sinon.stub(window, "matchMedia").returns({ matches });+}+async function scrollTo(selector, props) {const element = document.querySelector(selector);Object.assign(element, props);@@ -96,6 +156,7 @@ module("Integration | ui-kit | DOverflowControls", function (hooks) {});test("clamps button scroll targets to the content edges", async function (assert) {+ const matchMediaStub = stubReducedMotion(false);await render(<template><DOverflowControls style="width: 100px; overflow-x: auto">@@ -123,9 +184,11 @@ module("Integration | ui-kit | DOverflowControls", function (hooks) {{ left: 0, behavior: "smooth" },"backward tap targets the start instead of overshooting");+ matchMediaStub.restore();});test("targets only the tapped axis when both axes overflow", async function (assert) {+ const matchMediaStub = stubReducedMotion(false);await render(<template>{{! scrollbar-width: none keeps offset sizes exact across platforms }}@@ -159,6 +222,32 @@ module("Integration | ui-kit | DOverflowControls", function (hooks) {{ top: 150, behavior: "smooth" },"vertical tap targets the vertical axis only");+ matchMediaStub.restore();+ });++ test("uses instant scrolling when reduced motion is preferred", async function (assert) {+ const matchMediaStub = stubReducedMotion(true);++ await render(+ <template>+ <DOverflowControls style="width: 100px; overflow-x: auto">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );++ const content = find(".d-overflow-controls__content");+ let target;+ content.scrollTo = (options) => (target = options);++ await click(".d-overflow-controls__btn.--right");++ assert.deepEqual(+ target,+ { left: content.clientWidth, behavior: "instant" },+ "a click respects the reduced-motion preference"+ );+ matchMediaStub.restore();});test("applies consumer classes and attributes", async function (assert) {@@ -190,4 +279,949 @@ module("Integration | ui-kit | DOverflowControls", function (hooks) {.dom(".d-overflow-controls__btn.my-btn").exists("buttons get @buttonClass");});++ test("overflow strip: default mode stamps its measured horizontal state", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="width: 100px; overflow-x: auto">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ assert+ .dom(".d-overflow-controls__content")+ .hasAttribute(+ "data-d-scroll-overflow",+ "",+ "the content reports overflow"+ );+ assert+ .dom(".d-overflow-controls__content")+ .hasAttribute(+ "data-d-scroll-at-start",+ "",+ "the content reports its start edge"+ );+ assert+ .dom(".d-overflow-controls__content")+ .doesNotHaveAttribute(+ "data-d-scroll-at-end",+ "the end remains out of view"+ );+ assert+ .dom(".d-overflow-controls__content")+ .hasAttribute(+ "data-d-scroll-axis",+ "horizontal",+ "the content reports the measured axis"+ );+ });++ test("overflow strip: owned mode uses the consumer element as the scroller", async function (assert) {+ await render(+ <template>+ <DOverflowControls+ data-wrapper="yes"+ @axis="horizontal"+ @ownedScroller={{true}}+ @wrapperClass="consumer-wrapper"+ as |strip|+ >+ <div+ class="mine"+ style="width: 100px; overflow-x: auto"+ {{strip.scroller}}+ >+ <div style="width: 500px; height: 20px"></div>+ </div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ assert+ .dom(".d-overflow-controls.--owned-scroller.consumer-wrapper")+ .hasAttribute(+ "data-wrapper",+ "yes",+ "owned-mode splattributes land on the wrapper"+ );+ assert+ .dom(".mine")+ .hasAttribute(+ "data-d-scroll-overflow",+ "",+ "the consumer element is measured"+ );+ assert+ .dom(".mine")+ .hasAttribute(+ "data-d-scroll-at-start",+ "",+ "the consumer element is at start"+ );+ assert+ .dom(".mine")+ .hasAttribute(+ "data-d-scroll-axis",+ "horizontal",+ "the consumer element carries the axis"+ );+ assert+ .dom(".d-overflow-controls__btn.--right")+ .exists("owned mode renders its trailing button");+ assert+ .dom(".d-overflow-controls__content")+ .doesNotExist("owned mode renders no generated content scroller");+ });++ test("overflow strip: an explicit vertical axis ignores horizontal overflow", async function (assert) {+ await render(+ <template>+ <DOverflowControls+ style="width: 100px; height: 100px; overflow: auto"+ @axis="vertical"+ >+ <div style="width: 500px; height: 500px"></div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ assert+ .dom(".d-overflow-controls__content")+ .hasAttribute(+ "data-d-scroll-axis",+ "vertical",+ "the explicit axis is stamped"+ );+ assert+ .dom(".d-overflow-controls__btn.--down")+ .exists("the vertical trailing button renders");+ assert+ .dom(".d-overflow-controls__btn.--right")+ .doesNotExist("horizontal overflow is ignored");+ });++ test("overflow strip: an explicit hidden axis never renders owned-mode buttons", async function (assert) {+ await render(+ <template>+ <DOverflowControls+ @axis="horizontal"+ @ownedScroller={{true}}+ as |strip|+ >+ <div+ class="mine"+ style="width: 100px; overflow-x: hidden"+ {{strip.scroller}}+ >+ <div style="width: 500px; height: 20px"></div>+ </div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ assert+ .dom(".d-overflow-controls.--owned-scroller")+ .exists("the consumer element owns the scroller");+ assert.true(+ find(".mine").scrollWidth > find(".mine").clientWidth,+ "the fixture has geometric overflow"+ );+ assert+ .dom(".d-overflow-controls__btn")+ .doesNotExist("hidden overflow is not treated as scrollable");+ });++ test("overflow strip: edge button classes are applied per physical edge", async function (assert) {+ await render(+ <template>+ <DOverflowControls+ style="width: 100px; height: 100px; overflow: auto; scrollbar-width: none"+ @edgeButtonClasses={{EDGE_BUTTON_CLASSES}}+ >+ <div style="width: 500px; height: 500px"></div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ assert+ .dom(".d-overflow-controls__btn.--right.consumer-right")+ .exists("the right edge receives only its class");+ for (const className of ["consumer-left", "consumer-up", "consumer-down"]) {+ assert+ .dom(".d-overflow-controls__btn.--right")+ .doesNotHaveClass(className, `the right edge excludes ${className}`);+ }+ assert+ .dom(".d-overflow-controls__btn.--down.consumer-down")+ .exists("the bottom edge receives only its class");+ for (const className of [+ "consumer-left",+ "consumer-right",+ "consumer-up",+ ]) {+ assert+ .dom(".d-overflow-controls__btn.--down")+ .doesNotHaveClass(className, `the bottom edge excludes ${className}`);+ }++ const content = find(".d-overflow-controls__content");+ await scrollTo(".d-overflow-controls__content", {+ scrollLeft: content.scrollWidth - content.clientWidth,+ scrollTop: content.scrollHeight - content.clientHeight,+ });+ await nextFrame();++ assert+ .dom(".d-overflow-controls__btn.--left.consumer-left")+ .exists("the left edge receives only its class");+ for (const className of [+ "consumer-right",+ "consumer-up",+ "consumer-down",+ ]) {+ assert+ .dom(".d-overflow-controls__btn.--left")+ .doesNotHaveClass(className, `the left edge excludes ${className}`);+ }+ assert+ .dom(".d-overflow-controls__btn.--up.consumer-up")+ .exists("the top edge receives only its class");+ for (const className of [+ "consumer-left",+ "consumer-right",+ "consumer-down",+ ]) {+ assert+ .dom(".d-overflow-controls__btn.--up")+ .doesNotHaveClass(className, `the top edge excludes ${className}`);+ }+ });++ test("overflow strip: touch skips hold while mouse hold scrolls continuously", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="width: 100px; overflow-x: auto">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ const content = find(".d-overflow-controls__content");+ const button = find(".d-overflow-controls__btn.--right");+ stubPointerCapture(button);++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "touch",+ });+ await nextFrame();+ await nextFrame();++ assert.strictEqual(content.scrollLeft, 0, "a touch press never arms hold");++ await triggerEvent(button, "pointerup", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "touch",+ });++ let touchClicks = 0;+ const nativeScrollTo = content.scrollTo.bind(content);+ content.scrollTo = () => touchClicks++;+ await click(button);+ assert.strictEqual(+ touchClicks,+ 1,+ "a touch tap keeps the plain-click path"+ );+ content.scrollTo = nativeScrollTo;++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 2,+ isPrimary: true,+ pointerType: "mouse",+ });+ await nextFrame();++ assert.true(content.scrollLeft > 0, "the hold advances the content");+ const firstOffset = content.scrollLeft;++ await nextFrame();+ assert.true(+ content.scrollLeft > firstOffset,+ "the hold continues advancing on later frames"+ );++ await triggerEvent(button, "pointerup", {+ button: 0,+ pointerId: 2,+ isPrimary: true,+ pointerType: "mouse",+ });++ let clicks = 0;+ content.scrollTo = () => clicks++;+ await click(button);+ assert.strictEqual(clicks, 0, "the click following a hold is swallowed");++ await click(button);+ assert.strictEqual(clicks, 1, "the next plain click scrolls exactly once");+ });++ test("overflow strip: reveal supports nearest and center without moving the page", async function (assert) {+ const state = new RevealState();+ const pageScroll = window.scrollY;++ await render(+ <template>+ <DOverflowControls+ style="width: 160px; overflow-x: auto; white-space: nowrap"+ @axis="horizontal"+ as |strip|+ >+ <span+ style="display: inline-block; width: 320px; height: 20px"+ ></span>+ <button+ class="reveal-target"+ style="display: inline-block; width: 80px"+ type="button"+ {{didInsert (fn state.capture strip)}}+ >Target</button>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ const content = find(".d-overflow-controls__content");+ const target = find(".reveal-target");+ const contentPosition = layoutOffset(content);+ const targetPosition = layoutOffset(target);+ const targetStart = targetPosition.x - contentPosition.x;+ const paddingRight =+ Number.parseFloat(getComputedStyle(content).scrollPaddingRight) || 0;+ let scrollTarget;+ content.scrollTo = (options) => (scrollTarget = options);+ const reveal = state.strip?.reveal;++ assert.strictEqual(+ typeof reveal,+ "function",+ "the yielded strip exposes reveal"+ );++ if (typeof reveal !== "function") {+ // eslint-disable-next-line qunit/no-early-return+ return;+ }++ reveal(target);+ assert.strictEqual(+ scrollTarget.left,+ targetStart + target.offsetWidth + paddingRight - content.clientWidth,+ "nearest reveals the measured trailing edge clear of scroll padding"+ );+ assert.strictEqual(+ scrollTarget.behavior,+ "instant",+ "nearest reveal is instant"+ );++ reveal(target, { align: "center" });+ assert.strictEqual(+ scrollTarget.left,+ targetStart + target.offsetWidth / 2 - content.clientWidth / 2,+ "center aligns the measured target and viewport centers"+ );+ assert.strictEqual(+ scrollTarget.behavior,+ "instant",+ "center reveal is instant"+ );+ assert.strictEqual(window.scrollY, pageScroll, "the page does not move");+ });++ test("overflow strip: reveal leaves a fully visible horizontal item in place", async function (assert) {+ const state = new RevealState();++ await render(+ <template>+ <DOverflowControls+ style="width: 160px; overflow-x: auto; white-space: nowrap"+ @axis="horizontal"+ as |strip|+ >+ <button+ class="visible-reveal-target"+ style="display: inline-block; width: 80px"+ type="button"+ {{didInsert (fn state.capture strip)}}+ >Visible target</button>+ <span+ style="display: inline-block; width: 320px; height: 20px"+ ></span>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ const content = find(".d-overflow-controls__content");+ const target = find(".visible-reveal-target");+ const contentRect = content.getBoundingClientRect();+ const targetRect = target.getBoundingClientRect();+ assert.true(+ targetRect.left >= contentRect.left,+ "the measured target starts after the viewport's leading edge"+ );+ assert.true(+ targetRect.right <= contentRect.right,+ "the measured target ends before the viewport's trailing edge"+ );++ const scrollToSpy = sinon.spy();+ content.scrollTo = scrollToSpy;+ state.strip.reveal(target);++ assert.true(+ scrollToSpy.notCalled,+ "revealing an already visible item does not request any scroll"+ );+ });++ test("overflow strip: a scroller mounted later inside a conditional is observed", async function (assert) {+ const state = new ConditionalScrollerState();++ await render(+ <template>+ <DOverflowControls+ @axis="horizontal"+ @ownedScroller={{true}}+ as |strip|+ >+ {{#if state.show}}+ <div+ class="late-scroller"+ style="width: 100px; overflow-x: auto"+ {{strip.scroller}}+ >+ <div style="width: 500px; height: 20px"></div>+ </div>+ {{/if}}+ </DOverflowControls>+ </template>+ );++ assert+ .dom(".late-scroller")+ .doesNotExist("the consumer has not mounted its scroller yet");++ state.show = true;+ await settled();+ await nextFrame();++ assert+ .dom(".late-scroller")+ .hasAttribute(+ "data-d-scroll-overflow",+ "",+ "the late scroller is measured"+ );+ assert+ .dom(".d-overflow-controls__btn.--right")+ .exists("the late scroller receives a trailing button");+ });++ test("overflow strip: removes buttons when an owned scroller unmounts", async function (assert) {+ const state = new ConditionalScrollerState();+ state.show = true;++ await render(+ <template>+ <DOverflowControls+ @axis="horizontal"+ @ownedScroller={{true}}+ as |strip|+ >+ {{#if state.show}}+ <div+ class="conditional-scroller"+ style="width: 100px; overflow-x: auto"+ {{strip.scroller}}+ >+ <div style="width: 500px; height: 20px"></div>+ </div>+ {{/if}}+ </DOverflowControls>+ </template>+ );+ await nextFrame();+ assert+ .dom(".d-overflow-controls__btn.--right")+ .exists("the overflowing owned scroller initially has a button");++ state.show = false;+ await settled();+ await nextFrame();++ assert+ .dom(".d-overflow-controls__btn")+ .doesNotExist("unmounting the owned scroller removes its buttons");+ });++ test("overflow strip: replaces edge state when owned scrollers swap", async function (assert) {+ const state = new ConditionalScrollerState();+ state.show = true;++ await render(+ <template>+ <DOverflowControls+ @axis="horizontal"+ @ownedScroller={{true}}+ as |strip|+ >+ {{#if state.show}}+ <div+ class="first-conditional-scroller"+ style="width: 100px; overflow-x: auto"+ {{strip.scroller}}+ >+ <div style="width: 500px; height: 20px"></div>+ </div>+ {{else}}+ <div+ class="second-conditional-scroller"+ style="width: 100px; overflow-x: auto"+ {{didInsert state.scrollToEnd}}+ {{strip.scroller}}+ >+ <div style="width: 500px; height: 20px"></div>+ </div>+ {{/if}}+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ assert+ .dom(".d-overflow-controls__btn.--right")+ .exists("the first scroller starts with only the trailing button");+ assert+ .dom(".d-overflow-controls__btn.--left")+ .doesNotExist("the first scroller has no leading button");++ state.show = false;+ await settled();+ await nextFrame();++ assert+ .dom(".first-conditional-scroller")+ .doesNotExist("the first owned scroller unmounts during the swap");+ assert+ .dom(".second-conditional-scroller")+ .exists("the second owned scroller mounts during the same render");+ assert+ .dom(".d-overflow-controls__btn.--left")+ .exists("the second scroller at its end has a leading button");+ assert+ .dom(".d-overflow-controls__btn.--right")+ .doesNotExist(+ "the first scroller's stale trailing flag does not survive"+ );+ });++ test("overflow strip: hold stops when the window loses focus", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="width: 100px; overflow-x: auto">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ const content = find(".d-overflow-controls__content");+ const button = find(".d-overflow-controls__btn.--right");+ const { captured, released } = stubPointerCapture(button);++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "mouse",+ });+ await nextFrame();+ await nextFrame();++ assert.true(content.scrollLeft > 0, "the hold advances the content");+ assert.true(captured.has(1), "the hold captures its pointer");++ await triggerEvent(window, "blur");+ const offsetAfterBlur = content.scrollLeft;+ await nextFrame();+ await nextFrame();++ assert.strictEqual(+ content.scrollLeft,+ offsetAfterBlur,+ "losing window focus stops the hold"+ );+ assert.true(+ released.includes(1),+ "losing window focus releases the pointer capture"+ );+ });++ test("overflow strip: a touch click is not swallowed after blur ends a mouse hold", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="width: 100px; overflow-x: auto">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ const content = find(".d-overflow-controls__content");+ const button = find(".d-overflow-controls__btn.--right");+ stubPointerCapture(button);++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "mouse",+ });++ await nextFrame();+ await nextFrame();+ await triggerEvent(window, "blur");++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 2,+ isPrimary: true,+ pointerType: "touch",+ });+ await triggerEvent(button, "pointerup", {+ button: 0,+ pointerId: 2,+ isPrimary: true,+ pointerType: "touch",+ });++ const scrollToSpy = sinon.spy();+ content.scrollTo = scrollToSpy;+ await click(button);++ assert.strictEqual(+ scrollToSpy.callCount,+ 1,+ "the touch click scrolls once after blur cancels the mouse hold"+ );+ });++ test("overflow strip: a click is not swallowed after pointercancel ends a mouse hold", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="width: 100px; overflow-x: auto">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ const content = find(".d-overflow-controls__content");+ const button = find(".d-overflow-controls__btn.--right");+ stubPointerCapture(button);++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "mouse",+ });+ await nextFrame();+ await nextFrame();+ await triggerEvent(button, "pointercancel", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "mouse",+ });++ const scrollToSpy = sinon.spy();+ content.scrollTo = scrollToSpy;+ await click(button);++ assert.strictEqual(+ scrollToSpy.callCount,+ 1,+ "the click scrolls once after pointercancel ends the mouse hold"+ );+ });++ test("overflow strip: scrolling does not reread computed styles", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="width: 100px; overflow-x: auto">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ const getComputedStyleSpy = sinon.spy(window, "getComputedStyle");+ const content = find(".d-overflow-controls__content");++ try {+ for (const scrollLeft of [50, 100, 150]) {+ await scrollTo(".d-overflow-controls__content", { scrollLeft });+ await nextFrame();+ }++ assert.strictEqual(+ getComputedStyleSpy+ .getCalls()+ .filter((call) => call.args[0] === content).length,+ 0,+ "scrolling remeasures geometry without rereading scrollability"+ );+ } finally {+ getComputedStyleSpy.restore();+ }+ });++ test("overflow strip: rejects a second concurrent owned scroller", async function (assert) {+ const expectedMessage =+ "d-overflow-controls: strip.scroller was applied to a second element while another scroller is still mounted";+ let errors = 0;+ setupOnerror((error) => {+ errors++;+ assert.true(+ error.message.endsWith(expectedMessage),+ "the assertion identifies the second concurrently owned scroller"+ );+ assert.true(+ /d-overflow-controls: .*second/i.test(error.message),+ "the assertion names d-overflow-controls and the second scroller"+ );+ });++ await render(+ <template>+ <DOverflowControls @ownedScroller={{true}} as |strip|>+ <div class="first-owned-scroller" {{strip.scroller}}></div>+ <div class="second-owned-scroller" {{strip.scroller}}></div>+ </DOverflowControls>+ </template>+ );++ assert.strictEqual(errors, 1, "a second owned scroller raises one error");+ resetOnerror();+ });++ test("overflow strip: percentage scroll padding uses the scrollport", async function (assert) {+ const state = new RevealState();++ await render(+ <template>+ <DOverflowControls+ style="width: 160px; overflow-x: auto; white-space: nowrap; scroll-padding-right: 25%"+ as |strip|+ >+ <span+ style="display: inline-block; width: 320px; height: 20px"+ ></span>+ <button+ class="percentage-padding-target"+ style="display: inline-block; width: 80px"+ type="button"+ {{didInsert (fn state.capture strip)}}+ >Target</button>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ const content = find(".d-overflow-controls__content");+ const target = find(".percentage-padding-target");+ const contentPosition = layoutOffset(content);+ const targetPosition = layoutOffset(target);+ const targetStart = targetPosition.x - contentPosition.x;+ let scrollTarget;+ content.scrollTo = (options) => (scrollTarget = options);+ const reveal = state.strip?.reveal;++ assert.strictEqual(+ typeof reveal,+ "function",+ "the yielded strip exposes reveal"+ );++ if (typeof reveal !== "function") {+ // eslint-disable-next-line qunit/no-early-return+ return;+ }++ reveal(target);+ assert.strictEqual(+ scrollTarget.left,+ targetStart ++ target.offsetWidth ++ 0.25 * content.clientWidth -+ content.clientWidth,+ "nearest resolves percentage padding against the measured scrollport"+ );+ });++ test("overflow strip: a second pointer's release does not end another pointer's hold", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="width: 100px; overflow-x: auto">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ const content = find(".d-overflow-controls__content");+ const button = find(".d-overflow-controls__btn.--right");+ const { captured, released } = stubPointerCapture(button);++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "mouse",+ });+ await nextFrame();+ await nextFrame();++ assert.true(content.scrollLeft > 0, "the mouse hold advances the content");+ assert.true(captured.has(1), "the mouse hold captures its pointer");++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 2,+ isPrimary: true,+ pointerType: "touch",+ });+ await triggerEvent(button, "pointerup", {+ button: 0,+ pointerId: 2,+ isPrimary: true,+ pointerType: "touch",+ });+ const offsetAfterTouchRelease = content.scrollLeft;+ await nextFrame();+ await nextFrame();++ assert.true(+ content.scrollLeft > offsetAfterTouchRelease,+ "another pointer's release leaves the mouse hold running"+ );+ assert.false(+ released.includes(1),+ "another pointer's release does not release the mouse capture"+ );++ await triggerEvent(button, "pointerup", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "mouse",+ });+ const offsetAfterMouseRelease = content.scrollLeft;+ await nextFrame();+ await nextFrame();++ assert.strictEqual(+ content.scrollLeft,+ offsetAfterMouseRelease,+ "the matching pointer's release stops the hold"+ );+ assert.true(+ released.includes(1),+ "the matching pointer's release releases its capture"+ );+ });++ test("overflow strip: a second pointer's press does not replace an active hold", async function (assert) {+ await render(+ <template>+ <DOverflowControls style="width: 100px; overflow-x: auto">+ <div style="width: 500px; height: 20px"></div>+ </DOverflowControls>+ </template>+ );+ await nextFrame();++ const content = find(".d-overflow-controls__content");+ const button = find(".d-overflow-controls__btn.--right");+ const { captured, released } = stubPointerCapture(button);+ const offsetBeforeMouseHold = content.scrollLeft;++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "mouse",+ });+ await nextFrame();+ await nextFrame();++ assert.true(+ content.scrollLeft > offsetBeforeMouseHold,+ "the mouse hold advances the content"+ );++ await triggerEvent(button, "pointerdown", {+ button: 0,+ pointerId: 3,+ isPrimary: true,+ pointerType: "pen",+ });+ const offsetAfterPenPress = content.scrollLeft;+ await nextFrame();+ await nextFrame();++ assert.true(+ content.scrollLeft > offsetAfterPenPress,+ "the pen press leaves the mouse hold running"+ );+ assert.false(+ released.includes(1),+ "the pen press does not release the mouse capture"+ );+ assert.false(captured.has(3), "the ignored pen press is not captured");++ await triggerEvent(button, "pointerup", {+ button: 0,+ pointerId: 1,+ isPrimary: true,+ pointerType: "mouse",+ });+ const offsetAfterMouseRelease = content.scrollLeft;+ await nextFrame();+ await nextFrame();++ assert.strictEqual(+ content.scrollLeft,+ offsetAfterMouseRelease,+ "the mouse release stops its hold"+ );+ assert.true(released.includes(1), "the mouse release releases its capture");+ });});diff --git a/frontend/discourse/tests/integration/ui-kit/d-tabs-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-tabs-test.gjsnew file mode 100644index 00000000000..d60bdf1aa8e--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/d-tabs-test.gjs@@ -0,0 +1,2448 @@+import { tracked } from "@glimmer/tracking";+import { get } from "@ember/helper";+import { on } from "@ember/modifier";+import {+ click,+ find,+ findAll,+ focus,+ render,+ resetOnerror,+ settled,+ setupOnerror,+ triggerKeyEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import { resetSiteDirForTesting } from "discourse/lib/text-direction";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import DTabs from "discourse/ui-kit/d-tabs";++/* eslint-disable qunit/no-early-return */++class TabsState {+ @tracked active;+ @tracked items;+ @tracked showExtra = false;++ constructor(active, items = []) {+ this.active = active;+ this.items = items;+ }+}++function requireTabs(assert, expectedCount) {+ const selector = '[role="tab"]';+ const tabs = findAll(selector);++ assert+ .dom(selector)+ .exists(+ { count: expectedCount },+ `the tablist contains the measured ${expectedCount} declared tabs`+ );++ return tabs.length === expectedCount ? tabs : null;+}++function requirePanel(assert) {+ const selector = '[role="tabpanel"]';+ const panel = find(selector);++ assert.dom(selector).exists({ count: 1 }, "one persistent tabpanel renders");++ return panel;+}++function nextFrame() {+ return new Promise((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(resolve))+ );+}++function layoutOffset(element) {+ let x = 0;+ let node = element;++ while (node) {+ x += node.offsetLeft;+ node = node.offsetParent instanceof HTMLElement ? node.offsetParent : null;+ }++ return x;+}++function guardMessageMatches(error, patterns) {+ return patterns.every((pattern) => pattern.test(error.message));+}++module("Integration | ui-kit | DTabs", function (hooks) {+ setupRenderingTest(hooks);++ test("renders declared tabs in order and only the active panel content", async function (assert) {+ const ids = ["overview", "activity", "preferences"];+ const labels = ["Overview", "Activity", "Preferences"];+ const widgetLabel = "Profile sections";+ const contents = [+ "Overview content",+ "Activity content",+ "Preferences content",+ ];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "1"}}+ @label={{widgetLabel}}+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label={{get labels "0"}}>+ <p data-panel-content={{get ids "0"}}>{{get contents "0"}}</p>+ </tabs.Tab>+ <tabs.Tab @key={{get ids "1"}} @label={{get labels "1"}}>+ <p data-panel-content={{get ids "1"}}>{{get contents "1"}}</p>+ </tabs.Tab>+ <tabs.Tab @key={{get ids "2"}} @label={{get labels "2"}}>+ <p data-panel-content={{get ids "2"}}>{{get contents "2"}}</p>+ </tabs.Tab>+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ assert.dom(".d-tabs").exists("the widget renders its root");+ assert.dom('[role="tablist"]').exists("the tabs render inside a tablist");+ assert+ .dom('[role="tablist"]')+ .hasAttribute(+ "aria-label",+ widgetLabel,+ "the tablist uses the required accessible name"+ );+ assert+ .dom('[role="tablist"]')+ .doesNotHaveAttribute(+ "aria-orientation",+ "horizontal is the implicit default orientation"+ );+ assert.deepEqual(+ tabs.map((tab) => tab.textContent.trim()),+ labels,+ "button order follows declaration order"+ );+ for (const tab of tabs) {+ assert.strictEqual(tab.tagName, "BUTTON", "each tab is a real button");+ assert.strictEqual(tab.type, "button", "each tab has a non-submit type");+ assert.strictEqual(+ tab.parentElement,+ find('[role="tablist"]'),+ "each tab is directly inside the tablist"+ );+ }++ assert+ .dom(`[data-panel-content="${ids[1]}"]`)+ .hasText(contents[1], "the active tab content renders in the panel");+ assert+ .dom(`[data-panel-content="${ids[0]}"]`)+ .doesNotExist("content before the active tab is absent");+ assert+ .dom(`[data-panel-content="${ids[2]}"]`)+ .doesNotExist("content after the active tab is absent");+ });++ test("preserves mixed static and keyed loop order through insertion and reorder", async function (assert) {+ const staticTabs = [+ { id: "leading", label: "Leading" },+ { id: "trailing", label: "Trailing" },+ ];+ const initialItems = [+ { id: "loop-a", label: "Loop A" },+ { id: "loop-c", label: "Loop C" },+ ];+ const insertedItem = { id: "loop-b", label: "Loop B" };+ const state = new TabsState(staticTabs[0].id, initialItems);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label="Mixed tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab+ @key={{get staticTabs "0.id"}}+ @label={{get staticTabs "0.label"}}+ >+ {{get staticTabs "0.label"}}+ </tabs.Tab>+ {{#each state.items key="id" as |item|}}+ <tabs.Tab+ @key={{item.id}}+ @label={{item.label}}+ >{{item.label}}</tabs.Tab>+ {{/each}}+ <tabs.Tab+ @key={{get staticTabs "1.id"}}+ @label={{get staticTabs "1.label"}}+ >+ {{get staticTabs "1.label"}}+ </tabs.Tab>+ </DTabs>+ </template>+ );++ let expectedLabels = [+ staticTabs[0].label,+ ...initialItems.map((item) => item.label),+ staticTabs[1].label,+ ];+ let tabs = requireTabs(assert, expectedLabels.length);+ if (!tabs) {+ return;+ }++ assert.deepEqual(+ tabs.map((tab) => tab.textContent.trim()),+ expectedLabels,+ "static and looped declarations share one strip order"+ );++ state.items = [initialItems[0], insertedItem, initialItems[1]];+ await settled();+ expectedLabels = [+ staticTabs[0].label,+ ...state.items.map((item) => item.label),+ staticTabs[1].label,+ ];+ tabs = requireTabs(assert, expectedLabels.length);+ if (!tabs) {+ return;+ }++ assert.deepEqual(+ tabs.map((tab) => tab.textContent.trim()),+ expectedLabels,+ "an inserted loop item takes its mid-list position"+ );++ state.items = [insertedItem, initialItems[1], initialItems[0]];+ await settled();+ expectedLabels = [+ staticTabs[0].label,+ ...state.items.map((item) => item.label),+ staticTabs[1].label,+ ];++ assert.deepEqual(+ findAll('[role="tab"]').map((tab) => tab.textContent.trim()),+ expectedLabels,+ "keyed loop reorder changes the button order"+ );+ });++ test("adds and removes a conditional tab declaration in place", async function (assert) {+ const ids = ["first", "conditional", "last"];+ const labels = ["First", "Conditional", "Last"];+ const state = new TabsState(ids[0]);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label="Conditional tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label={{get labels "0"}}>First panel</tabs.Tab>+ {{#if state.showExtra}}+ <tabs.Tab @key={{get ids "1"}} @label={{get labels "1"}}>Conditional+ panel</tabs.Tab>+ {{/if}}+ <tabs.Tab @key={{get ids "2"}} @label={{get labels "2"}}>Last panel</tabs.Tab>+ </DTabs>+ </template>+ );++ let tabs = requireTabs(assert, ids.length - 1);+ if (!tabs) {+ return;+ }++ assert.deepEqual(+ tabs.map((tab) => tab.textContent.trim()),+ [labels[0], labels[2]],+ "the false conditional contributes no tab"+ );++ state.showExtra = true;+ await settled();+ tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ assert.deepEqual(+ tabs.map((tab) => tab.textContent.trim()),+ labels,+ "the true conditional inserts at its declaration position"+ );++ state.showExtra = false;+ await settled();+ assert.deepEqual(+ findAll('[role="tab"]').map((tab) => tab.textContent.trim()),+ [labels[0], labels[2]],+ "turning the conditional off removes its tab"+ );+ });++ test("click requests activation without changing controlled selection", async function (assert) {+ const ids = ["alpha", "beta"];+ const state = new TabsState(ids[0]);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label="Controlled tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label="Alpha"><span+ data-panel={{get ids "0"}}+ >Alpha panel</span></tabs.Tab>+ <tabs.Tab @key={{get ids "1"}} @label="Beta"><span+ data-panel={{get ids "1"}}+ >Beta panel</span></tabs.Tab>+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ const panelBefore = requirePanel(assert);+ if (!tabs || !panelBefore) {+ return;+ }++ await click(tabs[1]);++ assert.true(+ onActivate.calledOnceWithExactly(ids[1]),+ "click requests the clicked id once"+ );+ assert+ .dom(tabs[0])+ .hasAttribute("aria-selected", "true", "selection remains controlled");+ assert+ .dom(tabs[1])+ .hasAttribute(+ "aria-selected",+ "false",+ "the request does not select itself"+ );+ assert+ .dom(`[data-panel="${ids[0]}"]`)+ .exists("the old panel content remains");++ state.active = ids[1];+ await settled();++ assert+ .dom(tabs[0])+ .hasAttribute(+ "aria-selected",+ "false",+ "the former tab becomes unselected"+ );+ assert+ .dom(tabs[1])+ .hasAttribute(+ "aria-selected",+ "true",+ "the new controlled tab becomes selected"+ );+ assert+ .dom(`[data-panel="${ids[0]}"]`)+ .doesNotExist("the former content is removed");+ assert.dom(`[data-panel="${ids[1]}"]`).exists("the new content renders");+ assert.strictEqual(+ find('[role="tabpanel"]'),+ panelBefore,+ "the panel element persists through the controlled swap"+ );+ });++ test("element click activates and preserves consumer click propagation", async function (assert) {+ const ids = ["synthesized"];+ const id = ids[0];+ const onActivate = sinon.spy();+ const consumerClick = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{id}}+ @label="Synthetic click tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab+ data-consumer-tab={{id}}+ @key={{id}}+ @label="Synthetic"+ {{on "click" consumerClick}}+ >+ Synthetic panel+ </tabs.Tab>+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ tabs[0].click();+ await settled();++ assert.true(+ onActivate.calledOnceWithExactly(id),+ "a detail-zero element click activates exactly once"+ );+ assert.true(+ consumerClick.calledOnce,+ "the consumer click modifier also runs"+ );+ assert.strictEqual(+ consumerClick.firstCall.args[0].detail,+ 0,+ "the exercised click is the browser's synthesized detail-zero form"+ );+ });++ test("disabled tabs remain focusable but never activate", async function (assert) {+ const ids = ["enabled", "disabled"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "0"}}+ @label="Disabled tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label="Enabled">Enabled panel</tabs.Tab>+ <tabs.Tab+ @disabled={{true}}+ @key={{get ids "1"}}+ @label="Disabled"+ >Disabled panel</tabs.Tab>+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ const disabledTab = tabs[1];+ assert+ .dom(disabledTab)+ .hasAttribute("aria-disabled", "true", "disabled state uses ARIA");+ assert+ .dom(disabledTab)+ .doesNotHaveAttribute("disabled", "the tab is not natively disabled");++ await focus(tabs[0]);+ await triggerKeyEvent(tabs[0], "keydown", "ArrowRight");+ assert+ .dom(disabledTab)+ .isFocused("arrow navigation can focus the disabled tab");++ disabledTab.click();+ await settled();+ assert.true(+ onActivate.notCalled,+ "a real element click does not activate the disabled tab"+ );++ await triggerKeyEvent(disabledTab, "keydown", "Enter");+ assert.true(+ onActivate.notCalled,+ "Enter does not activate the disabled tab"+ );+ });++ test("pairs every tab with the live panel and labels it from the active tab", async function (assert) {+ const ids = ["one", "two", "three"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "1"}}+ @label="Paired tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}+ <tabs.Tab @key={{id}} @label={{id}}>{{id}}</tabs.Tab>+ {{/each}}+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ const panel = requirePanel(assert);+ if (!tabs || !panel) {+ return;+ }++ assert.notStrictEqual(panel.id, "", "the panel exposes a generated id");+ assert+ .dom(panel)+ .hasAttribute("tabindex", "0", "the panel is keyboard focusable");+ for (const tab of tabs) {+ assert.notStrictEqual(tab.id, "", "each tab exposes a generated id");+ assert+ .dom(tab)+ .hasAttribute(+ "aria-controls",+ panel.id,+ "each tab controls the live panel"+ );+ assert.true(+ ["true", "false"].includes(tab.getAttribute("aria-selected")),+ "each tab has a literal boolean aria-selected value"+ );+ }++ const activeTab = tabs.find(+ (tab) => tab.getAttribute("aria-selected") === "true"+ );+ if (!activeTab) {+ assert+ .dom('[role="tab"][aria-selected="true"]')+ .exists("one live tab is active");+ return;+ }+ assert.strictEqual(+ panel.getAttribute("aria-labelledby"),+ activeTab.id,+ "the live panel is labelled by the live active tab id"+ );+ });++ test("re-keys a live tab when its id changes", async function (assert) {+ class IdState {+ @tracked id = "original";+ }++ const state = new IdState();+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.id}}+ @label="Mutable tab id"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{state.id}} @label="Mutable">Panel</tabs.Tab>+ </DTabs>+ </template>+ );++ const originalTab = find('[role="tab"]');+ const originalDomId = originalTab.id;++ state.id = "replacement";+ await settled();++ const tab = find('[role="tab"]');+ const panel = requirePanel(assert);+ assert.dom('[role="tablist"]').exists("the tablist remains exposed");+ assert+ .dom(tab)+ .hasAttribute("data-d-tab", state.id, "the registry uses the new id");+ assert.notStrictEqual(+ tab.id,+ originalDomId,+ "the new id receives a new DOM id"+ );+ assert.strictEqual(+ panel.getAttribute("aria-labelledby"),+ tab.id,+ "the panel is labelled by the re-keyed tab"+ );+ });++ test("renders an empty labelled panel for undefined and unknown active ids", async function (assert) {+ const ids = ["known-a", "known-b"];+ const label = "Possibly inactive tabs";+ const state = new TabsState(undefined);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label={{label}}+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label="Known A"><span+ data-active-content+ >Known A panel</span></tabs.Tab>+ <tabs.Tab @key={{get ids "1"}} @label="Known B"><span+ data-active-content+ >Known B panel</span></tabs.Tab>+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ const panel = requirePanel(assert);+ if (!tabs || !panel) {+ return;+ }++ assert+ .dom('[role="tab"][aria-selected="true"]')+ .doesNotExist("undefined selects no tab");+ assert.dom(panel).hasText("", "undefined renders no panel content");+ assert+ .dom(panel)+ .hasAttribute(+ "aria-label",+ label,+ "the unowned panel uses the widget label"+ );+ assert+ .dom(panel)+ .doesNotHaveAttribute(+ "aria-labelledby",+ "the unowned panel references no tab"+ );++ state.active = "unknown-id";+ await settled();++ assert+ .dom('[role="tab"][aria-selected="true"]')+ .doesNotExist("an unknown id selects no tab");+ assert.dom(panel).hasText("", "an unknown id renders no panel content");+ assert+ .dom(panel)+ .hasAttribute(+ "aria-label",+ label,+ "the unknown-id panel remains labelled"+ );+ });++ test("suppresses tab ARIA roles when there are zero tabs", async function (assert) {+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs @label="Empty tabs" @onActivate={{onActivate}} />+ </template>+ );++ if (!find(".d-tabs")) {+ assert.dom(".d-tabs").exists("the empty widget still renders its root");+ return;+ }++ assert+ .dom('[role="tablist"]')+ .doesNotExist("an empty list exposes no tablist role");+ assert+ .dom('[role="tabpanel"]')+ .doesNotExist("an empty widget exposes no tabpanel role");+ assert+ .dom(".d-tabs [tabindex]")+ .doesNotExist("an empty widget exposes no panel tab stop");+ });++ test("places tabs only inside the consumer-positioned header Tablist", async function (assert) {+ const ids = ["details", "history"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "0"}}+ @label="Header tabs"+ @onActivate={{onActivate}}+ >+ <:header as |header|>+ <div data-consumer-row>+ <header.Tablist data-consumer-tablist />+ <button data-consumer-controls type="button">Refresh</button>+ </div>+ </:header>+ <:default as |tabs|>+ <tabs.Tab @key={{get ids "0"}} @label="Details">Details panel</tabs.Tab>+ <tabs.Tab @key={{get ids "1"}} @label="History">History panel</tabs.Tab>+ </:default>+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ const tablist = find("[data-consumer-tablist]");+ if (!tabs || !tablist) {+ assert+ .dom("[data-consumer-tablist]")+ .exists("the yielded Tablist lands in the consumer row");+ return;+ }++ assert.strictEqual(+ tablist.closest(".d-overflow-controls").parentElement,+ find("[data-consumer-row]"),+ "the tablist has consumer-chosen placement"+ );+ assert+ .dom(tablist)+ .hasAttribute(+ "role",+ "tablist",+ "the placed element is the real tablist"+ );+ assert.deepEqual(+ Array.from(tablist.children),+ tabs,+ "the placed tablist contains exactly the declared tab buttons"+ );+ assert.strictEqual(+ find("[data-consumer-controls]").parentElement,+ tablist.closest(".d-overflow-controls").parentElement,+ "consumer controls are siblings of the tablist"+ );+ assert.false(+ tablist.contains(find("[data-consumer-controls]")),+ "consumer controls stay outside the tablist"+ );+ });++ test("rescues focus to the persistent panel when active content changes", async function (assert) {+ const ids = ["editable", "replacement"];+ const state = new TabsState(ids[0]);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label="Focus rescue tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label="Editable"><input+ data-panel-input+ /></tabs.Tab>+ <tabs.Tab @key={{get ids "1"}} @label="Replacement"><p>Replacement+ panel</p></tabs.Tab>+ </DTabs>+ </template>+ );++ const panel = requirePanel(assert);+ if (!panel || !find("[data-panel-input]")) {+ assert+ .dom("[data-panel-input]")+ .exists("the active content renders its focus target");+ return;+ }++ await focus("[data-panel-input]");+ assert+ .dom("[data-panel-input]")+ .isFocused("focus starts inside outgoing panel content");++ const focusSpy = sinon.spy(HTMLElement.prototype, "focus");+ focusSpy.resetHistory();++ try {+ state.active = ids[1];+ await settled();++ assert.true(+ focusSpy.calledWith({ preventScroll: true }),+ "focus rescue prevents the panel from scrolling its ancestors"+ );+ } finally {+ focusSpy.restore();+ }++ assert.strictEqual(+ find('[role="tabpanel"]'),+ panel,+ "the tabpanel element is not recreated"+ );+ assert+ .dom(panel)+ .isFocused("focus lands on the persistent panel after the swap");+ assert.notStrictEqual(+ document.activeElement,+ document.body,+ "focus is not stranded on body"+ );+ });++ test("does not rescue focus after focused panel content was already removed", async function (assert) {+ class FocusState extends TabsState {+ @tracked showInput = true;+ }++ const ids = ["editable", "replacement"];+ const state = new FocusState(ids[0]);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label="Removed focus target"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label="Editable">+ {{#if state.showInput}}<input data-panel-input />{{/if}}+ </tabs.Tab>+ <tabs.Tab+ @key={{get ids "1"}}+ @label="Replacement"+ >Replacement</tabs.Tab>+ </DTabs>+ </template>+ );++ await focus("[data-panel-input]");+ state.showInput = false;+ await settled();+ await nextFrame();+ assert.strictEqual(+ document.activeElement,+ document.body,+ "removing the focused control releases focus to body"+ );++ state.active = ids[1];+ await settled();++ assert.strictEqual(+ document.activeElement,+ document.body,+ "a later swap does not act on the stale focus flag, rescuing nothing"+ );+ });++ test("resets panel scroll position when active content changes", async function (assert) {+ const ids = ["long-a", "long-b"];+ const state = new TabsState(ids[0]);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label="Scrollable tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label="Long A"><div+ style="height: 200px;"+ >Long A panel</div></tabs.Tab>+ <tabs.Tab @key={{get ids "1"}} @label="Long B"><div+ style="height: 200px;"+ >Long B panel</div></tabs.Tab>+ </DTabs>+ </template>+ );++ const panel = requirePanel(assert);+ if (!panel) {+ return;+ }++ panel.style.height = "20px";+ panel.style.overflowY = "auto";+ panel.scrollTop = panel.scrollHeight;+ assert.true(+ panel.scrollTop > 0,+ "the fixture establishes a non-zero panel scroll offset"+ );++ state.active = ids[1];+ await settled();++ assert.strictEqual(+ panel.scrollTop,+ 0,+ "the persistent panel returns to the top after the swap"+ );+ });++ test("resets horizontal panel scroll position when active content changes", async function (assert) {+ const ids = ["wide-a", "wide-b"];+ const state = new TabsState(ids[0]);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label="Horizontally scrollable tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label="Wide A"><div+ style="width: 500px"+ >Wide A panel</div></tabs.Tab>+ <tabs.Tab @key={{get ids "1"}} @label="Wide B"><div+ style="width: 500px"+ >Wide B panel</div></tabs.Tab>+ </DTabs>+ </template>+ );++ const panel = requirePanel(assert);+ panel.style.width = "100px";+ panel.style.overflowX = "auto";+ panel.scrollLeft = panel.scrollWidth;+ assert.true(+ panel.scrollLeft > 0,+ "the fixture has a horizontal scroll offset"+ );++ state.active = ids[1];+ await settled();++ assert.strictEqual(+ panel.scrollLeft,+ 0,+ "the persistent panel returns to its horizontal start after the swap"+ );+ });++ test("uses vertical orientation and Up Down focus movement", async function (assert) {+ const ids = ["north", "middle", "south"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "1"}}+ @label="Vertical tabs"+ @onActivate={{onActivate}}+ @orientation="vertical"+ as |tabs|+ >+ {{#each ids as |id|}}<tabs.Tab+ @key={{id}}+ @label={{id}}+ >{{id}}</tabs.Tab>{{/each}}+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ assert+ .dom('[role="tablist"]')+ .hasAttribute(+ "aria-orientation",+ "vertical",+ "the tablist advertises vertical orientation"+ );+ await focus(tabs[1]);+ await triggerKeyEvent(tabs[1], "keydown", "ArrowDown");+ assert.dom(tabs[2]).isFocused("ArrowDown moves to the following tab");+ await triggerKeyEvent(tabs[2], "keydown", "ArrowUp");+ assert.dom(tabs[1]).isFocused("ArrowUp moves to the preceding tab");+ assert.true(+ onActivate.notCalled,+ "vertical arrow movement does not activate"+ );+ });++ test("contains wrapping labels in a narrow vertical tablist", async function (assert) {+ const ids = ["short", "long"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "0"}}+ @label="Narrow vertical tabs"+ @onActivate={{onActivate}}+ @orientation="vertical"+ >+ <:header as |header|><header.Tablist style="width: 120px" /></:header>+ <:default as |tabs|>+ <tabs.Tab @key={{get ids "0"}} @label="Short">Short</tabs.Tab>+ <tabs.Tab+ @key={{get ids "1"}}+ @label="A deliberately long tab label that must wrap"+ >Long panel</tabs.Tab>+ </:default>+ </DTabs>+ </template>+ );++ const tablist = find('[role="tablist"]');+ const tabs = requireTabs(assert, ids.length);+ assert.true(+ tablist.scrollWidth <= tablist.clientWidth,+ "the vertical tablist contains its labels horizontally"+ );+ assert.true(+ tabs[1].getBoundingClientRect().height >+ tabs[0].getBoundingClientRect().height,+ "the long label wraps onto additional lines"+ );+ });++ test("wraps unbroken labels inside a narrow vertical tablist", async function (assert) {+ const ids = ["short", "unbroken"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "0"}}+ @label="Narrow vertical tabs"+ @onActivate={{onActivate}}+ @orientation="vertical"+ >+ <:header as |header|><header.Tablist style="width: 120px" /></:header>+ <:default as |tabs|>+ <tabs.Tab @key={{get ids "0"}} @label="Short">Short</tabs.Tab>+ <tabs.Tab+ @key={{get ids "1"}}+ @label="unbrokenidentifierthatiswiderthanthestrip_2026"+ >Unbroken panel</tabs.Tab>+ </:default>+ </DTabs>+ </template>+ );++ const tablist = find('[role="tablist"]');+ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ assert.true(+ tablist.scrollWidth <= tablist.clientWidth,+ "the vertical tablist hides no horizontal overflow"+ );+ assert.true(+ tabs[1].scrollWidth <= tabs[1].clientWidth,+ "the unbroken label fits within its tab button after wrapping mid-token"+ );+ });++ test("renders rich label content without recreating it on activation", async function (assert) {+ const ids = ["rich", "plain"];+ const state = new TabsState(ids[0]);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label="Rich labels"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}}>+ <:label><span data-rich-label><strong>Rich</strong>+ label</span></:label>+ <:default>Rich panel</:default>+ </tabs.Tab>+ <tabs.Tab @key={{get ids "1"}} @label="Plain">Plain panel</tabs.Tab>+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ const labelBefore = find("[data-rich-label]");+ if (!tabs || !labelBefore) {+ assert+ .dom("[data-rich-label]")+ .exists("the named label block renders inside a tab");+ return;+ }++ assert.true(+ tabs[0].contains(labelBefore),+ "the arbitrary label content lives inside its button"+ );+ state.active = ids[1];+ await settled();+ assert.strictEqual(+ find("[data-rich-label]"),+ labelBefore,+ "selection changes preserve label subtree identity"+ );+ });++ test("component structural attributes override consumer splattributes", async function (assert) {+ const ids = ["safe-pair"];+ const id = ids[0];+ const suppliedId = "consumer-id";+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{id}}+ @label="Safe splats"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{! eslint-disable ember/template-no-unsupported-role-attributes }}+ <tabs.Tab+ aria-selected="false"+ data-consumer-marker={{id}}+ id={{suppliedId}}+ role="link"+ @key={{id}}+ @label="Safe tab"+ >+ Safe panel+ </tabs.Tab>+ {{! eslint-enable ember/template-no-unsupported-role-attributes }}+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ const panel = requirePanel(assert);+ if (!tabs || !panel) {+ return;+ }++ const tab = tabs[0];+ assert.notStrictEqual(+ tab.id,+ suppliedId,+ "the consumer id cannot replace the generated id"+ );+ assert+ .dom(tab)+ .hasAttribute(+ "role",+ "tab",+ "the consumer role cannot replace the tab role"+ );+ assert+ .dom(tab)+ .hasAttribute(+ "aria-selected",+ "true",+ "the consumer selection cannot replace component state"+ );+ assert+ .dom(tab)+ .hasAttribute(+ "data-consumer-marker",+ id,+ "safe consumer data attributes still splat"+ );+ assert+ .dom(tab)+ .hasAttribute(+ "aria-controls",+ panel.id,+ "splatting cannot break panel control pairing"+ );+ assert+ .dom(panel)+ .hasAttribute(+ "aria-labelledby",+ tab.id,+ "splatting cannot break panel labelling"+ );+ });++ test("consumer selection and tab focus survive looped tab removal", async function (assert) {+ const initialItems = [+ { id: "removable-active", label: "Removable active" },+ { id: "fallback", label: "Fallback" },+ { id: "removable-focus", label: "Removable focus" },+ ];+ const state = new TabsState(initialItems[0].id, initialItems);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label="Removable tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each state.items key="id" as |item|}}+ <tabs.Tab+ data-tab-id={{item.id}}+ @key={{item.id}}+ @label={{item.label}}+ >+ <span data-panel-id={{item.id}}>{{item.label}} panel</span>+ </tabs.Tab>+ {{/each}}+ </DTabs>+ </template>+ );++ let tabs = requireTabs(assert, initialItems.length);+ if (!tabs) {+ return;+ }++ state.items = initialItems.slice(1);+ state.active = initialItems[1].id;+ await settled();++ tabs = requireTabs(assert, state.items.length);+ if (!tabs) {+ return;+ }++ assert+ .dom(`[data-tab-id="${state.active}"]`)+ .hasAttribute(+ "aria-selected",+ "true",+ "the consumer-selected replacement becomes active"+ );+ assert+ .dom(`[data-panel-id="${state.active}"]`)+ .exists("the consumer-selected panel renders after active removal");++ const focusedId = initialItems[2].id;+ await focus(`[data-tab-id="${focusedId}"]`);+ state.items = state.items.filter((item) => item.id !== focusedId);+ await settled();++ tabs = findAll('[role="tab"]');+ assert.true(+ tabs.includes(document.activeElement),+ "focus moves to a remaining tab after focused-tab removal"+ );+ assert.notStrictEqual(+ document.activeElement,+ document.body,+ "focused-tab removal does not strand focus on body"+ );+ });++ test("seeds exactly one roving tab stop on the selected tab", async function (assert) {+ const ids = ["seed-a", "seed-b", "seed-c"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "1"}}+ @label="Roving seed"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}<tabs.Tab+ @key={{id}}+ @label={{id}}+ >{{id}}</tabs.Tab>{{/each}}+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ const tabStops = tabs.filter((tab) => tab.tabIndex === 0);+ const selectedTab = tabs.find(+ (tab) => tab.getAttribute("aria-selected") === "true"+ );+ assert.strictEqual(+ tabStops.length,+ 1,+ "exactly one tab participates in sequential Tab navigation"+ );+ assert.strictEqual(+ tabStops[0],+ selectedTab,+ "the selected tab seeds the roving tab stop"+ );+ for (const tab of tabs.filter((candidate) => candidate !== selectedTab)) {+ assert.strictEqual(+ tab.tabIndex,+ -1,+ "every unselected tab starts outside sequential Tab navigation"+ );+ }+ });++ test("horizontal arrows move focus without activation and wrap both ends", async function (assert) {+ const ids = ["left", "middle", "right"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "1"}}+ @label="Horizontal arrows"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}<tabs.Tab+ @key={{id}}+ @label={{id}}+ >{{id}}</tabs.Tab>{{/each}}+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ await focus(tabs[1]);+ await triggerKeyEvent(tabs[1], "keydown", "ArrowRight");+ assert.dom(tabs[2]).isFocused("ArrowRight advances focus");+ await triggerKeyEvent(tabs[2], "keydown", "ArrowRight");+ assert+ .dom(tabs[0])+ .isFocused("ArrowRight wraps from the measured end to the start");+ await triggerKeyEvent(tabs[0], "keydown", "ArrowLeft");+ assert+ .dom(tabs[2])+ .isFocused("ArrowLeft wraps from the measured start to the end");+ assert+ .dom(tabs[1])+ .hasAttribute(+ "aria-selected",+ "true",+ "focus movement leaves selection unchanged"+ );+ assert.true(+ onActivate.notCalled,+ "arrow focus movement does not request activation"+ );+ });++ test("arrow focus leaves the Tab stop on the selected tab", async function (assert) {+ const ids = ["first", "second", "third"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "0"}}+ @label="Anchored tab stop"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}<tabs.Tab+ @key={{id}}+ @label={{id}}+ >{{id}}</tabs.Tab>{{/each}}+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ await focus(tabs[0]);+ await triggerKeyEvent(tabs[0], "keydown", "ArrowRight");++ assert.dom(tabs[1]).isFocused("ArrowRight moves focus to the next tab");+ assert+ .dom(tabs[1])+ .hasAttribute(+ "aria-selected",+ "false",+ "manual activation leaves the arrowed-to tab unselected"+ );+ assert+ .dom(tabs[0])+ .hasAttribute(+ "tabindex",+ "0",+ "the selected tab keeps the Tab stop, so returning focus reopens the shown panel"+ );+ assert+ .dom(tabs[1])+ .hasAttribute(+ "tabindex",+ "-1",+ "a focused but unselected tab does not take over the Tab stop"+ );+ assert+ .dom('[role="tab"][tabindex="0"]')+ .exists({ count: 1 }, "the tablist retains exactly one Tab stop");+ });++ test("Home and End move focus to measured strip boundaries", async function (assert) {+ const ids = ["home", "middle", "end"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "1"}}+ @label="Boundary keys"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}<tabs.Tab+ @key={{id}}+ @label={{id}}+ >{{id}}</tabs.Tab>{{/each}}+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ await focus(tabs[Math.floor(tabs.length / 2)]);+ await triggerKeyEvent(document.activeElement, "keydown", "End");+ assert+ .dom(tabs[tabs.length - 1])+ .isFocused("End focuses the measured last tab");+ await triggerKeyEvent(document.activeElement, "keydown", "Home");+ assert.dom(tabs[0]).isFocused("Home focuses the measured first tab");+ assert.true(+ onActivate.notCalled,+ "boundary movement does not request activation"+ );+ });++ test("Enter and Space activate the focused tab exactly once per key", async function (assert) {+ const ids = ["selected", "focused"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "0"}}+ @label="Keyboard activation"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label="Selected">Selected panel</tabs.Tab>+ <tabs.Tab @key={{get ids "1"}} @label="Focused">Focused panel</tabs.Tab>+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ // On document, so it observes the event after the tablist's own handler+ // has had its chance to prevent it.+ const prevented = [];+ const recordPrevented = (event) => prevented.push(event.defaultPrevented);+ document.addEventListener("keydown", recordPrevented);++ await focus(tabs[1]);+ await triggerKeyEvent(tabs[1], "keydown", "Enter");+ assert.true(+ onActivate.calledOnceWithExactly(ids[1]),+ "Enter requests the focused id exactly once"+ );++ onActivate.resetHistory();+ await triggerKeyEvent(tabs[1], "keydown", " ");+ assert.true(+ onActivate.calledOnceWithExactly(ids[1]),+ "Space requests the focused id exactly once"+ );++ document.removeEventListener("keydown", recordPrevented);+ assert.deepEqual(+ prevented,+ [true, true],+ "both keys are default-prevented, so a real press synthesises no second activation from a native click"+ );+ assert+ .dom(tabs[0])+ .hasAttribute(+ "aria-selected",+ "true",+ "keyboard requests remain controlled"+ );+ assert+ .dom(tabs[1])+ .hasAttribute(+ "aria-selected",+ "false",+ "focused activation does not self-select"+ );+ });++ test("programmatic active changes reseed the tab stop while focus is outside", async function (assert) {+ const ids = ["program-a", "program-b", "program-c"];+ const state = new TabsState(ids[0]);+ const onActivate = sinon.spy();++ await render(+ <template>+ <button data-outside type="button">Outside</button>+ <DTabs+ @active={{state.active}}+ @label="Programmatic selection"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}<tabs.Tab+ @key={{id}}+ @label={{id}}+ >{{id}}</tabs.Tab>{{/each}}+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ await focus("[data-outside]");+ state.active = ids[2];+ await settled();++ assert+ .dom("[data-outside]")+ .isFocused("programmatic selection does not steal outside focus");+ assert.strictEqual(+ tabs.filter((tab) => tab.tabIndex === 0).length,+ 1,+ "the strip still has one tab stop"+ );+ assert.strictEqual(+ tabs[2].tabIndex,+ 0,+ "the newly selected tab becomes the tab stop"+ );+ assert.strictEqual(+ tabs[0].tabIndex,+ -1,+ "the previously selected tab leaves the Tab order"+ );+ });++ test("rejects duplicate tab keys", async function (assert) {+ const duplicateKey = "duplicate";+ const onActivate = sinon.spy();+ let errors = 0;+ setupOnerror((error) => {+ errors++;+ assert.true(+ guardMessageMatches(error, [/duplicate.*key|key.*unique/i]),+ "the assertion identifies duplicate keys"+ );+ });++ await render(+ <template>+ <DTabs+ @active={{duplicateKey}}+ @label="Duplicate ids"+ @onActivate={{onActivate}}+ as |tabs|+ >++ <tabs.Tab @key={{duplicateKey}} @label="First">First</tabs.Tab>+ <tabs.Tab @key={{duplicateKey}} @label="Second">Second</tabs.Tab>++ </DTabs>+ </template>+ );+ assert.strictEqual(errors, 1, "duplicate keys raise exactly one assertion");+ resetOnerror();+ });++ test("rejects a tab with both label forms", async function (assert) {+ const onActivate = sinon.spy();+ let errors = 0;+ setupOnerror((error) => {+ errors++;+ assert.true(+ guardMessageMatches(error, [/label/i, /either|both|xor/i]),+ "the assertion identifies mutually exclusive labels"+ );+ });++ await render(+ <template>+ <DTabs+ @active="both"+ @label="Invalid labels"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key="both" @label="Argument label">+ <:label><span>Block label</span></:label>+ <:default>Panel</:default>+ </tabs.Tab>+ </DTabs>+ </template>+ );+ assert.strictEqual(+ errors,+ 1,+ "both label forms raise exactly one assertion"+ );+ resetOnerror();+ });++ test("rejects a tab with no label form", async function (assert) {+ const onActivate = sinon.spy();+ let errors = 0;+ setupOnerror((error) => {+ errors++;+ assert.true(+ error.message.endsWith(+ 'd-tabs: tab "unlabelled" needs either @label or a <:label> block, and not both'+ ),+ "the assertion identifies the missing tab label"+ );+ });++ await render(+ <template>+ <DTabs+ @active="unlabelled"+ @label="Invalid labels"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key="unlabelled">Panel</tabs.Tab>+ </DTabs>+ </template>+ );+ assert.strictEqual(+ errors,+ 1,+ "a missing tab label raises exactly one assertion"+ );+ resetOnerror();+ });++ test("rejects a missing widget label", async function (assert) {+ const onActivate = sinon.spy();+ let errors = 0;+ setupOnerror((error) => {+ errors++;+ assert.true(+ guardMessageMatches(error, [/label/i, /required|missing/i]),+ "the assertion identifies the required widget label"+ );+ });++ await render(+ <template>+ <DTabs @active="tab" @onActivate={{onActivate}} as |tabs|>+ <tabs.Tab @key="tab" @label="Tab">Panel</tabs.Tab>+ </DTabs>+ </template>+ );+ assert.strictEqual(+ errors,+ 1,+ "a missing widget label raises exactly one assertion"+ );+ resetOnerror();+ });++ test("rejects a missing activation callback", async function (assert) {+ let errors = 0;+ setupOnerror((error) => {+ errors++;+ assert.true(+ guardMessageMatches(error, [+ /@?onActivate|activat/i,+ /required|missing/i,+ ]),+ "the assertion identifies the required callback"+ );+ });++ await render(+ <template>+ <DTabs @active="tab" @label="Missing callback" as |tabs|>+ <tabs.Tab @key="tab" @label="Tab">Panel</tabs.Tab>+ </DTabs>+ </template>+ );+ assert.strictEqual(+ errors,+ 1,+ "a missing activation callback raises exactly one assertion"+ );+ resetOnerror();+ });++ test("rejects a custom header that omits the yielded Tablist", async function (assert) {+ const onActivate = sinon.spy();+ let errors = 0;+ setupOnerror((error) => {+ errors++;+ assert.true(+ error.message.endsWith(+ "d-tabs: no tablist rendered — a <:header> block must place the yielded Tablist"+ ),+ "the assertion identifies the missing header Tablist"+ );+ });++ await render(+ <template>+ <DTabs+ @active="tab"+ @label="Missing placed tablist"+ @onActivate={{onActivate}}+ >+ <:header><div>Header without placement</div></:header>+ <:default as |tabs|><tabs.Tab+ @key="tab"+ @label="Tab"+ >Panel</tabs.Tab></:default>+ </DTabs>+ </template>+ );+ assert.strictEqual(+ errors,+ 1,+ "an omitted header Tablist raises exactly one assertion"+ );+ resetOnerror();+ });++ test("rejects non-tab content in the declaration block", async function (assert) {+ const onActivate = sinon.spy();+ let errors = 0;+ setupOnerror((error) => {+ errors++;+ assert.true(+ guardMessageMatches(error, [+ /tab|content|declaration/i,+ /only|invalid|unexpected/i,+ ]),+ "the assertion identifies non-tab declaration content"+ );+ });++ await render(+ <template>+ <DTabs+ @active="tab"+ @label="Invalid declaration"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key="tab" @label="Tab">Panel</tabs.Tab>+ <div data-non-tab>Not a tab declaration</div>+ </DTabs>+ </template>+ );+ assert.strictEqual(+ errors,+ 1,+ "non-tab declaration content raises exactly one assertion"+ );+ resetOnerror();+ });++ test("rejects a role tab impostor inserted after mount", async function (assert) {+ class ImpostorState {+ @tracked show = false;+ }++ const expectedMessage =+ "the declaration block may contain only tab declarations — found unexpected content in the tablist";+ const state = new ImpostorState();+ const onActivate = sinon.spy();+ let errors = 0;+ setupOnerror((error) => {+ errors++;+ assert.true(+ error.message.endsWith(expectedMessage),+ "the assertion identifies the inserted tab impostor"+ );+ });++ await render(+ <template>+ <DTabs+ @active="valid"+ @label="Late impostor"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key="valid" @label="Valid">Panel</tabs.Tab>+ {{! eslint-disable ember/template-require-context-role }}+ {{#if state.show}}<button+ role="tab"+ type="button"+ >Impostor</button>{{/if}}+ {{! eslint-enable ember/template-require-context-role }}+ </DTabs>+ </template>+ );++ state.show = true;+ await settled();++ assert.strictEqual(errors, 1, "a late tab impostor raises one assertion");+ resetOnerror();+ });++ test("a later tab change does not steal focus released before it", async function (assert) {+ const ids = ["editable", "replacement"];+ const state = new TabsState(ids[0]);+ const onActivate = sinon.spy();++ await render(+ <template>+ <button data-outside type="button">Outside</button>+ <DTabs+ @active={{state.active}}+ @label="Released panel focus"+ @onActivate={{onActivate}}+ as |tabs|+ >+ <tabs.Tab @key={{get ids "0"}} @label="Editable">+ {{#unless state.showExtra}}<input data-panel-input />{{/unless}}+ </tabs.Tab>+ <tabs.Tab @key={{get ids "1"}} @label="Replacement">Replacement panel</tabs.Tab>+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs || !find("[data-panel-input]")) {+ assert+ .dom("[data-panel-input]")+ .exists("the active content renders its measured focus target");+ return;+ }++ await focus("[data-panel-input]");+ state.showExtra = true;+ await settled();+ await focus("[data-outside]");++ state.active = ids[1];+ await settled();++ assert+ .dom("[data-outside]")+ .isFocused("a later content swap preserves focus released outside");+ });++ test("tab keys with whitespace and punctuation keep valid ARIA references", async function (assert) {+ const ids = ["account settings", "a:b.c"];+ const state = new TabsState(ids[0]);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{state.active}}+ @label="Unrestricted tab keys"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}+ <tabs.Tab @key={{id}} @label={{id}}>{{id}}</tabs.Tab>+ {{/each}}+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ const panel = requirePanel(assert);+ if (!tabs || !panel) {+ return;+ }++ for (const tab of tabs) {+ assert.false(+ /\s/.test(tab.id),+ `the generated DOM id for measured tab "${tab.dataset.dTab}" contains no whitespace`+ );+ assert.strictEqual(+ document.getElementById(tab.getAttribute("aria-controls")),+ panel,+ `the measured tab "${tab.dataset.dTab}" controls the live panel`+ );+ }++ const activeTab = tabs.find(+ (tab) => tab.getAttribute("aria-selected") === "true"+ );+ if (!activeTab) {+ assert+ .dom('[role="tab"][aria-selected="true"]')+ .exists("one measured tab is active");+ return;+ }++ assert.strictEqual(+ document.getElementById(panel.getAttribute("aria-labelledby")),+ activeTab,+ "the panel's labelledby IDREF resolves to the live active tab"+ );+ });++ test("alternating declaration branches reusing a tab id do not false-positive the duplicate guard", async function (assert) {+ class BranchState {+ @tracked flip = false;+ }++ const state = new BranchState();+ const onActivate = sinon.spy();+ let errors = 0;+ setupOnerror(() => errors++);++ await render(+ <template>+ <DTabs+ @active="same"+ @label="Alternating declaration"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#if state.flip}}+ <tabs.Tab @key="same" @label="One">1</tabs.Tab>+ {{else}}+ <tabs.Tab @key="same" @label="Two">2</tabs.Tab>+ {{/if}}+ </DTabs>+ </template>+ );++ state.flip = true;+ await settled();++ assert.strictEqual(+ errors,+ 0,+ "replacing a disconnected declaration raises no duplicate assertion"+ );+ assert+ .dom('[role="tab"]')+ .hasText("One", "the new declaration branch supplies the tab label");+ resetOnerror();+ });++ test("overflow strip: keeps the active tab inside the viewport", async function (assert) {+ const ids = ["one", "two", "three", "four", "five", "six"];+ const state = new TabsState("six");+ const onActivate = (id) => (state.active = id);++ await render(+ <template>+ <div style="width: 160px">+ <DTabs+ @active={{state.active}}+ @label="Overflowing sections"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}+ <tabs.Tab @key={{id}} @label="Section {{id}}">Panel+ {{id}}</tabs.Tab>+ {{/each}}+ </DTabs>+ </div>+ </template>+ );++ const tablist = find('[role="tablist"]');+ const tabs = requireTabs(assert, ids.length);+ if (!tablist || !tabs) {+ return;+ }++ assert.true(+ tablist.scrollWidth > tablist.clientWidth,+ "the fixture is narrow enough for the strip to overflow"+ );+ assert.true(+ tablist.scrollLeft > 0,+ "an initially active tab past the edge is scrolled into the strip"+ );+ const lastRect = tabs[5].getBoundingClientRect();+ const listRect = tablist.getBoundingClientRect();+ assert.true(+ lastRect.right <= listRect.right + 1,+ "the active tab's trailing edge lies inside the strip's viewport"+ );+ assert.true(+ lastRect.left >= listRect.left - 1,+ "the active tab's leading edge lies inside the strip's viewport"+ );++ state.active = "one";+ await settled();++ assert.strictEqual(+ tablist.scrollLeft,+ 0,+ "activating the first tab scrolls the strip back to its start"+ );+ });++ test("overflow strip: reveals a tab partially hidden at the start edge", async function (assert) {+ const ids = Array.from({ length: 8 }, (_, index) => `tab-${index + 1}`);+ const state = new TabsState(ids[ids.length - 1]);+ const onActivate = (id) => (state.active = id);++ await render(+ <template>+ <div style="width: 200px">+ <DTabs+ @active={{state.active}}+ @label="Start-edge reveal"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}+ <tabs.Tab+ style="flex: 0 0 80px"+ @key={{id}}+ @label={{id}}+ >Panel</tabs.Tab>+ {{/each}}+ </DTabs>+ </div>+ </template>+ );+ await nextFrame();++ const tablist = find('[role="tablist"]');+ const tabs = requireTabs(assert, ids.length);+ const target = tabs[3];+ const targetStart = layoutOffset(target) - layoutOffset(tablist);+ const paddingStart =+ Number.parseFloat(getComputedStyle(tablist).scrollPaddingLeft) || 0;+ tablist.scrollLeft = targetStart + target.offsetWidth / 2;+ assert.true(+ target.getBoundingClientRect().left <+ tablist.getBoundingClientRect().left,+ "the target starts partially hidden at the physical start edge"+ );++ state.active = ids[3];+ await settled();++ assert.strictEqual(+ tablist.scrollLeft,+ targetStart - paddingStart,+ "reveal aligns the measured tab start clear of measured scroll padding"+ );+ });++ test("overflow strip: exposes overflow state for the edge fades", async function (assert) {+ const ids = ["one", "two", "three", "four", "five", "six"];+ const state = new TabsState("one");+ const onActivate = (id) => (state.active = id);++ await render(+ <template>+ <div style="width: 160px">+ <DTabs+ @active={{state.active}}+ @label="Overflowing sections"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}+ <tabs.Tab @key={{id}} @label="Section {{id}}">Panel+ {{id}}</tabs.Tab>+ {{/each}}+ </DTabs>+ </div>+ </template>+ );+ await nextFrame();++ assert+ .dom('[role="tablist"]')+ .hasAttribute("data-d-scroll-overflow", "", "the strip reports overflow");+ assert+ .dom('[role="tablist"]')+ .hasAttribute("data-d-scroll-at-start", "", "it starts at the first tab");+ assert.dom('[role="tablist"]').doesNotHaveAttribute("data-d-scroll-at-end");++ state.active = "six";+ await settled();+ await nextFrame();++ assert+ .dom('[role="tablist"]')+ .hasAttribute(+ "data-d-scroll-at-end",+ "",+ "revealing the last tab rests the strip on its end"+ );+ assert+ .dom('[role="tablist"]')+ .doesNotHaveAttribute("data-d-scroll-at-start");+ });++ test("overflow strip: tab buttons follow the horizontal scroll edges", async function (assert) {+ const ids = Array.from({ length: 10 }, (_, index) => `tab-${index + 1}`);+ const state = new TabsState(ids[0]);+ const onActivate = (id) => (state.active = id);++ await render(+ <template>+ <div style="width: 200px">+ <DTabs+ @active={{state.active}}+ @label="Overflow controls"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}+ <tabs.Tab style="flex: 0 0 80px" @key={{id}} @label={{id}}>Panel+ {{id}}</tabs.Tab>+ {{/each}}+ </DTabs>+ </div>+ </template>+ );+ await nextFrame();++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ assert+ .dom(".d-tabs__strip-controls .d-overflow-controls__btn.--right")+ .exists("the trailing button appears at the first tab");+ assert+ .dom(".d-tabs__strip-controls .d-overflow-controls__btn.--left")+ .doesNotExist("the leading button is absent at the first tab");++ await click(tabs[tabs.length - 1]);++ await nextFrame();++ assert.strictEqual(+ state.active,+ ids[ids.length - 1],+ "activation is fed back into controlled state"+ );+ assert+ .dom(".d-tabs__strip-controls .d-overflow-controls__btn.--left")+ .exists("the leading button appears at the last tab");+ assert+ .dom(".d-tabs__strip-controls .d-overflow-controls__btn.--right")+ .doesNotExist("the trailing button is absent at the last tab");+ });++ test("overflow strip: a fitting tablist renders no buttons", async function (assert) {+ const ids = ["one", "two"];+ const onActivate = sinon.spy();++ await render(+ <template>+ <div style="width: 400px">+ <DTabs+ @active={{get ids "0"}}+ @label="Fitting tabs"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}+ <tabs.Tab style="flex: 0 0 80px" @key={{id}} @label={{id}}>Panel+ {{id}}</tabs.Tab>+ {{/each}}+ </DTabs>+ </div>+ </template>+ );+ await nextFrame();++ assert.true(+ find('[role="tablist"]').scrollWidth <=+ find('[role="tablist"]').clientWidth,+ "the fixture fits inside its tablist"+ );+ assert+ .dom(".d-tabs__strip-controls.d-overflow-controls.--owned-scroller")+ .exists("the fitting tablist still uses the shared strip wrapper");+ assert+ .dom(".d-tabs__strip-controls .d-overflow-controls__btn")+ .doesNotExist("a fitting tablist renders no edge buttons");+ });++ test("overflow strip: a bounded vertical tablist renders a down button", async function (assert) {+ const ids = Array.from({ length: 6 }, (_, index) => `tab-${index + 1}`);+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "0"}}+ @label="Vertical overflow"+ @onActivate={{onActivate}}+ @orientation="vertical"+ >+ <:header as |header|>+ <header.Tablist style="height: 120px" />+ </:header>+ <:default as |tabs|>+ {{#each ids as |id|}}+ <tabs.Tab style="flex: 0 0 50px" @key={{id}} @label={{id}}>Panel+ {{id}}</tabs.Tab>+ {{/each}}+ </:default>+ </DTabs>+ </template>+ );+ await nextFrame();++ const tablist = find('[role="tablist"]');+ assert.true(+ tablist.scrollHeight > tablist.clientHeight,+ "the fixture overflows its bounded height"+ );+ assert+ .dom(".d-tabs__strip-controls .d-overflow-controls__btn.--down")+ .exists("the vertical trailing button renders");+ });++ test("overflow strip: RTL reveals the last active tab inside the tablist", async function (assert) {+ const ids = Array.from({ length: 10 }, (_, index) => `tab-${index + 1}`);+ const state = new TabsState(ids[ids.length - 1]);+ const onActivate = (id) => (state.active = id);+ const pageScroll = window.scrollY;++ document.documentElement.classList.add("rtl");+ resetSiteDirForTesting();++ try {+ await render(+ <template>+ <div dir="rtl" style="width: 200px">+ <DTabs+ @active={{state.active}}+ @label="RTL overflow"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}+ <tabs.Tab style="flex: 0 0 80px" @key={{id}} @label={{id}}>Panel+ {{id}}</tabs.Tab>+ {{/each}}+ </DTabs>+ </div>+ </template>+ );++ await nextFrame();++ const tablist = find('[role="tablist"]');+ const active = find('[role="tab"][aria-selected="true"]');+ assert.deepEqual(+ {+ direction: getComputedStyle(tablist).direction,+ overflows: tablist.scrollWidth > tablist.clientWidth,+ },+ { direction: "rtl", overflows: true },+ "the fixture is an overflowing RTL scroller"+ );+ const tablistRect = tablist.getBoundingClientRect();+ const activeRect = active.getBoundingClientRect();++ assert.true(+ tablist.scrollLeft < 0,+ "the RTL tablist uses a negative offset"+ );+ assert.true(+ activeRect.left >= tablistRect.left - 1,+ "the active tab's leading edge lies inside the tablist"+ );+ assert.true(+ activeRect.right <= tablistRect.right + 1,+ "the active tab's trailing edge lies inside the tablist"+ );+ assert.strictEqual(window.scrollY, pageScroll, "the page does not move");+ } finally {+ document.documentElement.classList.remove("rtl");+ resetSiteDirForTesting();+ }+ });++ test("vertical tabs keep the height their wrapped labels need", async function (assert) {+ const ids = Array.from({ length: 6 }, (_, index) => `tab-${index + 1}`);+ const onActivate = sinon.spy();+ const longLabel = "Notifications, email and messaging preferences";++ await render(+ <template>+ <DTabs+ @active={{get ids "0"}}+ @label="Bounded vertical labels"+ @onActivate={{onActivate}}+ @orientation="vertical"+ >+ <:header as |header|>+ <header.Tablist style="width: 110px; height: 120px" />+ </:header>+ <:default as |tabs|>+ {{#each ids as |id|}}+ <tabs.Tab @key={{id}} @label={{longLabel}}>Panel {{id}}</tabs.Tab>+ {{/each}}+ </:default>+ </DTabs>+ </template>+ );+ await nextFrame();++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ const tablist = find('[role="tablist"]');+ assert.true(+ tablist.scrollHeight > tablist.clientHeight,+ "the fixture overflows its bounded height, so the strip scrolls"+ );+ for (const [index, tab] of tabs.entries()) {+ assert.true(+ tab.scrollHeight <= tab.clientHeight,+ `tab ${index + 1} is tall enough to contain its own wrapped label`+ );+ }+ });++ test("keyboard activation reports the declared id, not a stringified copy", async function (assert) {+ const ids = [1, 2, 3];+ const onActivate = sinon.spy();++ await render(+ <template>+ <DTabs+ @active={{get ids "0"}}+ @label="Numeric ids"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each ids as |id|}}<tabs.Tab @key={{id}} @label={{id}}>Panel+ {{id}}</tabs.Tab>{{/each}}+ </DTabs>+ </template>+ );++ const tabs = requireTabs(assert, ids.length);+ if (!tabs) {+ return;+ }++ await click(tabs[1]);+ assert.true(+ onActivate.calledOnceWithExactly(2),+ "clicking reports the declared numeric id"+ );++ onActivate.resetHistory();+ await focus(tabs[0]);+ await triggerKeyEvent(tabs[0], "keydown", "ArrowRight");+ await triggerKeyEvent(tabs[1], "keydown", "Enter");+ assert.true(+ onActivate.calledOnceWithExactly(2),+ "Enter reports the same declared id the click reported, not its string form"+ );+ });++ test("a later tab registering leaves the strip scrolled where the reader left it", async function (assert) {+ const state = new TabsState(+ "tab-1",+ Array.from({ length: 10 }, (_, index) => `tab-${index + 1}`)+ );+ const onActivate = sinon.spy();++ await render(+ <template>+ <div style="width: 200px">+ <DTabs+ @active={{state.active}}+ @label="Late registration"+ @onActivate={{onActivate}}+ as |tabs|+ >+ {{#each state.items key="id" as |id|}}+ <tabs.Tab style="flex: 0 0 80px" @key={{id}} @label={{id}}>Panel+ {{id}}</tabs.Tab>+ {{/each}}+ </DTabs>+ </div>+ </template>+ );+ await nextFrame();++ const tablist = find('[role="tablist"]');+ tablist.scrollLeft = tablist.scrollWidth - tablist.clientWidth;+ await nextFrame();+ const scrolledTo = tablist.scrollLeft;+ assert.true(+ scrolledTo > 0,+ "the reader scrolled the strip away from the selected tab"+ );++ state.items = [...state.items, "tab-11"];+ await settled();+ await nextFrame();++ requireTabs(assert, 11);+ assert.strictEqual(+ tablist.scrollLeft,+ scrolledTo,+ "registering an unrelated tab does not drag the strip back to the selected one"+ );+ });+});diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-control-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-control-test.gjsindex 4061c37ef46..53f8f99bfd4 100644--- a/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-control-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-control-test.gjs@@ -1,4 +1,4 @@-import { findAll, render } from "@ember/test-helpers";+import { findAll, focus, render, triggerKeyEvent } from "@ember/test-helpers";import { module, test } from "qunit";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";@@ -282,6 +282,100 @@ module(.exists({ count: 1 }, "the group retains exactly one Tab stop");});+ test("rovingControl moves the tab stop with arrow focus by default", async function (assert) {+ await render(+ <template>+ <div+ role="tablist"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=tab]"+ wrap=true+ }}+ >+ <button+ aria-selected="true"+ class="anchor-item"+ role="tab"+ >A</button>+ <button+ aria-selected="false"+ class="anchor-item"+ role="tab"+ >B</button>+ </div>+ </template>+ );++ const items = findAll(".anchor-item");+ await focus(items[0]);+ await triggerKeyEvent(items[0], "keydown", "ArrowRight");++ assert.dom(items[1]).isFocused("arrow focus reaches the unmarked item");+ assert+ .dom(items[1])+ .hasAttribute(+ "tabindex",+ "0",+ "the default anchor promotes whatever focus reaches"+ );+ assert+ .dom(items[0])+ .hasAttribute("tabindex", "-1", "the marked item yields the tab stop");+ });++ test("rovingControl tabStopAnchor='selection' keeps the tab stop on the marked item", async function (assert) {+ await render(+ <template>+ <div+ role="tablist"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=tab]"+ tabStopAnchor="selection"+ wrap=true+ }}+ >+ <button+ aria-selected="true"+ class="anchor-item"+ role="tab"+ >A</button>+ <button+ aria-selected="false"+ class="anchor-item"+ role="tab"+ >B</button>+ </div>+ </template>+ );++ const items = findAll(".anchor-item");+ await focus(items[0]);+ await triggerKeyEvent(items[0], "keydown", "ArrowRight");++ assert+ .dom(items[1])+ .isFocused("arrow focus still reaches the unmarked item");+ assert+ .dom(items[0])+ .hasAttribute(+ "tabindex",+ "0",+ "the marked item keeps the tab stop while focus is elsewhere"+ );+ assert+ .dom(items[1])+ .hasAttribute(+ "tabindex",+ "-1",+ "focus alone does not promote an unmarked item"+ );+ assert+ .dom(".anchor-item[tabindex='0']")+ .exists({ count: 1 }, "the group retains exactly one tab stop");+ });+test("rovingControl registers a frozen shared API object", async function (assert) {let api;const register = (value) => (api = value);diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-scroll-edges-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-scroll-edges-test.gjsnew file mode 100644index 00000000000..7735ef3043c--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-scroll-edges-test.gjs@@ -0,0 +1,212 @@+import { tracked } from "@glimmer/tracking";+import { find, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import dScrollEdges from "discourse/ui-kit/modifiers/d-scroll-edges";++function nextFrame() {+ return new Promise((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(resolve))+ );+}++module("Integration | ui-kit | Modifier | dScrollEdges", function (hooks) {+ setupRenderingTest(hooks);++ test("marks an overflowing horizontal strip and tracks which edge it rests on", async function (assert) {+ await render(+ <template>+ <div+ class="strip"+ style="width: 100px; overflow-x: auto; white-space: nowrap"+ {{dScrollEdges}}+ >+ <span style="display: inline-block; width: 300px">wide</span>+ </div>+ </template>+ );+ await nextFrame();++ assert+ .dom(".strip")+ .hasAttribute("data-d-scroll-overflow", "", "the strip overflows");+ assert+ .dom(".strip")+ .hasAttribute(+ "data-d-scroll-axis",+ "horizontal",+ "the strip reports its horizontal axis"+ );+ assert+ .dom(".strip")+ .hasAttribute("data-d-scroll-at-start", "", "it rests at its start");+ assert+ .dom(".strip")+ .doesNotHaveAttribute("data-d-scroll-at-end", "the end is out of view");++ const strip = find(".strip");+ strip.scrollLeft = 100;+ await nextFrame();++ assert+ .dom(".strip")+ .doesNotHaveAttribute(+ "data-d-scroll-at-start",+ "scrolling away drops the start mark"+ );+ assert+ .dom(".strip")+ .doesNotHaveAttribute(+ "data-d-scroll-at-end",+ "the middle rests on neither edge"+ );++ strip.scrollLeft = 200;+ await nextFrame();++ assert+ .dom(".strip")+ .hasAttribute("data-d-scroll-at-end", "", "reaching the end marks it");+ });++ test("leaves a strip that fits unmarked and reacts when it stops fitting", async function (assert) {+ await render(+ <template>+ <div+ class="strip"+ style="width: 400px; overflow-x: auto; white-space: nowrap"+ {{dScrollEdges}}+ >+ <span class="content" style="display: inline-block; width: 300px">+ fits+ </span>+ </div>+ </template>+ );+ await nextFrame();++ assert+ .dom(".strip")+ .doesNotHaveAttribute(+ "data-d-scroll-overflow",+ "content that fits is not overflowing"+ );+ assert+ .dom(".strip")+ .hasAttribute(+ "data-d-scroll-axis",+ "horizontal",+ "a fitting strip still reports its horizontal axis"+ );++ find(".content").style.width = "900px";+ await nextFrame();++ assert+ .dom(".strip")+ .hasAttribute(+ "data-d-scroll-overflow",+ "",+ "content growing past the strip marks it as overflowing"+ );+ });++ test("reports along the vertical axis when asked", async function (assert) {+ await render(+ <template>+ <div+ class="strip"+ style="height: 100px; overflow-y: auto"+ {{dScrollEdges axis="vertical"}}+ >+ <div style="height: 300px">tall</div>+ </div>+ </template>+ );+ await nextFrame();++ assert+ .dom(".strip")+ .hasAttribute("data-d-scroll-overflow", "", "the column overflows");+ assert+ .dom(".strip")+ .hasAttribute(+ "data-d-scroll-axis",+ "vertical",+ "the column reports its vertical axis"+ );+ assert.dom(".strip").hasAttribute("data-d-scroll-at-start", "");++ find(".strip").scrollTop = 200;+ await nextFrame();++ assert.dom(".strip").hasAttribute("data-d-scroll-at-end", "");+ assert.dom(".strip").doesNotHaveAttribute("data-d-scroll-at-start");+ });++ test("follows an axis change", async function (assert) {+ class AxisState {+ @tracked axis = "horizontal";+ }++ const state = new AxisState();++ await render(+ <template>+ <div+ class="axis-changing-strip"+ style="width: 100px; height: 100px; overflow: auto"+ {{dScrollEdges axis=state.axis}}+ >+ <div style="width: 300px; height: 300px"></div>+ </div>+ </template>+ );+ await nextFrame();++ assert+ .dom(".axis-changing-strip")+ .hasAttribute(+ "data-d-scroll-axis",+ "horizontal",+ "the initial axis is horizontal"+ );++ state.axis = "vertical";+ await settled();+ await nextFrame();++ assert+ .dom(".axis-changing-strip")+ .hasAttribute(+ "data-d-scroll-axis",+ "vertical",+ "the stamped axis follows the argument"+ );+ assert+ .dom(".axis-changing-strip")+ .hasAttribute(+ "data-d-scroll-at-start",+ "",+ "the vertical axis starts at its leading edge"+ );++ const strip = find(".axis-changing-strip");+ strip.scrollTop = strip.scrollHeight - strip.clientHeight;+ await nextFrame();++ assert+ .dom(".axis-changing-strip")+ .hasAttribute(+ "data-d-scroll-at-end",+ "",+ "the vertical axis reports its measured trailing edge"+ );+ assert+ .dom(".axis-changing-strip")+ .doesNotHaveAttribute(+ "data-d-scroll-at-start",+ "the vertical axis no longer reports its leading edge"+ );+ });+});diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/docked-composer.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/docked-composer.scssindex 5204b10a839..e29e0df7fe5 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/docked-composer.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot-conversations/docked-composer.scss@@ -145,13 +145,11 @@ body.has-ai-bot-docked-composer {// Toolbar: below input inside the bordered box, separated by a subtle line.// Edge-to-edge background with bottom corners matching the wrapper radius.-// padding-right reserves space for the absolutely-positioned send button..docked-composer.ai-bot-docked-composer .d-editor-button-bar__wrap {overflow: hidden;max-height: 4em;opacity: 1;margin: 0;- padding-right: 3em;border-top: 1px solid var(--primary-low);border-radius: 0 0 var(--d-input-border-radius) var(--d-input-border-radius);background: var(--primary-very-low);@@ -160,6 +158,14 @@ body.has-ai-bot-docked-composer {opacity 0.2s ease;}+// Reserves space for the absolutely-positioned send button on the scroller+// rather than the wrapper: the wrapper positions the overflow chevrons, so+// padding there parks them off the strip and the strip's own edge fade then+// hides toolbar buttons with nothing covering them.+.docked-composer.ai-bot-docked-composer .d-editor-button-bar {+ padding-right: 3em;+}+.docked-composer.ai-bot-docked-composer.docked-composer--toolbar-hidden.d-editor-button-bar__wrap {max-height: 0;diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/horizontal.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/horizontal.gjsnew file mode 100644index 00000000000..7a668e059ae--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/horizontal.gjs@@ -0,0 +1,26 @@+import DOverflowControls from "discourse/ui-kit/d-overflow-controls";++const SECTIONS = [+ "Overview",+ "Activity",+ "Badges",+ "Notifications",+ "Messages",+ "Invites",+ "Preferences",+ "Security",+ "Groups",+ "Bookmarks",+ "Drafts",+ "Summary",+];++export default <template>+ <div class="styleguide-overflow-controls --narrow">+ <DOverflowControls @class="styleguide-overflow-controls__strip">+ {{#each SECTIONS as |section|}}+ <span class="styleguide-overflow-controls__chip">{{section}}</span>+ {{/each}}+ </DOverflowControls>+ </div>+</template>diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/owned.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/owned.gjsnew file mode 100644index 00000000000..6d24a9588e7--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/owned.gjs@@ -0,0 +1,30 @@+import DOverflowControls from "discourse/ui-kit/d-overflow-controls";++const SECTIONS = [+ "Overview",+ "Activity",+ "Badges",+ "Notifications",+ "Messages",+ "Invites",+ "Preferences",+ "Security",+ "Groups",+ "Bookmarks",+];++export default <template>+ <div class="styleguide-overflow-controls --narrow">+ <DOverflowControls @axis="horizontal" @ownedScroller={{true}} as |strip|>+ <ul+ aria-label="Owned scroller"+ class="styleguide-overflow-controls__list"+ {{strip.scroller}}+ >+ {{#each SECTIONS as |section|}}+ <li class="styleguide-overflow-controls__chip">{{section}}</li>+ {{/each}}+ </ul>+ </DOverflowControls>+ </div>+</template>diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/reveal.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/reveal.gjsnew file mode 100644index 00000000000..3b3993d5be8--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/reveal.gjs@@ -0,0 +1,66 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { modifier } from "ember-modifier";+import DButton from "discourse/ui-kit/d-button";+import DOverflowControls from "discourse/ui-kit/d-overflow-controls";++const SECTIONS = Array.from({ length: 12 }, (_, index) => `Item ${index + 1}`);++export default class OverflowControlsRevealExample extends Component {+ /** Keeps each chip and the strip so the buttons above can call reveal. */+ registerChip = modifier((element, [index, strip]) => {+ this.#chips.set(index, element);+ this.#strip = strip;++ return () => this.#chips.delete(index);+ });++ sections = SECTIONS;++ #chips = new Map();+ #strip = null;++ @action+ revealNearest() {+ this.#reveal(8, "nearest");+ }++ @action+ revealCenter() {+ this.#reveal(3, "center");+ }++ #reveal(index, align) {+ const item = this.#chips.get(index);+ if (item && this.#strip) {+ this.#strip.reveal(item, { align });+ }+ }++ <template>+ <div class="styleguide-overflow-controls__controls">+ <DButton+ @action={{this.revealNearest}}+ @translatedLabel="Reveal item 9, nearest"+ />+ <DButton+ @action={{this.revealCenter}}+ @translatedLabel="Reveal item 4, centered"+ />+ </div>++ <div class="styleguide-overflow-controls --narrow">+ <DOverflowControls+ @class="styleguide-overflow-controls__strip"+ as |strip|+ >+ {{#each this.sections as |section index|}}+ <span+ class="styleguide-overflow-controls__chip"+ {{this.registerChip index strip}}+ >{{section}}</span>+ {{/each}}+ </DOverflowControls>+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/vertical.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/vertical.gjsnew file mode 100644index 00000000000..fa2ca13750c--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflow-controls/vertical.gjs@@ -0,0 +1,13 @@+import DOverflowControls from "discourse/ui-kit/d-overflow-controls";++const ROWS = Array.from({ length: 20 }, (_, index) => `Row ${index + 1}`);++export default <template>+ <div class="styleguide-overflow-controls --narrow">+ <DOverflowControls @class="styleguide-overflow-controls__column">+ {{#each ROWS as |row|}}+ <div class="styleguide-overflow-controls__row">{{row}}</div>+ {{/each}}+ </DOverflowControls>+ </div>+</template>diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflowing-nav.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflowing-nav.gjsnew file mode 100644index 00000000000..d28d65e73fd--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/overflowing-nav.gjs@@ -0,0 +1,27 @@+import { eq } from "discourse/truth-helpers";+import DHorizontalOverflowNav from "discourse/ui-kit/d-horizontal-overflow-nav";++const SECTIONS = [+ "Summary",+ "Activity",+ "Notifications",+ "Messages",+ "Badges",+ "Invites",+ "Preferences",+ "Security",+ "Groups",+ "Bookmarks",+];++export default <template>+ <div class="styleguide-overflow-controls --narrow">+ <DHorizontalOverflowNav @ariaLabel="Overflowing sections">+ {{#each SECTIONS as |section index|}}+ <li>+ <a class={{if (eq index 6) "active"}} href="#">{{section}}</a>+ </li>+ {{/each}}+ </DHorizontalOverflowNav>+ </div>+</template>diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/basic.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/basic.gjsnew file mode 100644index 00000000000..279e528af7f--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/basic.gjs@@ -0,0 +1,58 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import DButton from "discourse/ui-kit/d-button";+import DTabs from "discourse/ui-kit/d-tabs";+import dIcon from "discourse/ui-kit/helpers/d-icon";++export default class TabsBasicExample extends Component {+ @tracked active = "overview";++ @action+ activate(id) {+ this.active = id;+ }++ @action+ selectBadges() {+ this.active = "badges";+ }++ <template>+ <div class="styleguide-tabs__controls">+ <DButton+ @action={{this.selectBadges}}+ @translatedLabel="Select the badges tab from outside"+ />+ <span class="styleguide-tabs__status">Active tab: {{this.active}}</span>+ </div>++ <div class="styleguide-tabs">+ <DTabs+ @active={{this.active}}+ @label="Profile sections"+ @onActivate={{this.activate}}+ as |tabs|+ >+ <tabs.Tab @key="overview" @label="Overview">+ <p>The panel keeps one element for the whole group. Switching tabs+ swaps its content in place, so its id and role never change hands.</p>+ </tabs.Tab>+ <tabs.Tab @key="activity" @label="Activity">+ <p>Nothing here moved until the owner fed the id back through the+ active argument. The widget holds no selection of its own.</p>+ </tabs.Tab>+ <tabs.Tab @key="badges">+ <:label>{{dIcon "certificate"}} Badges</:label>+ <:default>+ <p>A label block accepts arbitrary content, such as an icon beside+ the text.</p>+ </:default>+ </tabs.Tab>+ <tabs.Tab @disabled={{true}} @key="admin" @label="Admin">+ <p>This content never shows: a disabled tab is focusable but inert.</p>+ </tabs.Tab>+ </DTabs>+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/header.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/header.gjsnew file mode 100644index 00000000000..b60636badd1--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/header.gjs@@ -0,0 +1,55 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import DButton from "discourse/ui-kit/d-button";+import DTabs from "discourse/ui-kit/d-tabs";++export default class TabsHeaderExample extends Component {+ @tracked active = "summary";+ @tracked refreshCount = 0;++ @action+ activate(id) {+ this.active = id;+ }++ @action+ refresh() {+ this.refreshCount += 1;+ }++ <template>+ <div class="styleguide-tabs">+ <DTabs+ @active={{this.active}}+ @label="Report sections"+ @onActivate={{this.activate}}+ >+ <:header as |header|>+ <div class="styleguide-tabs__header">+ <header.Tablist />+ <DButton+ class="btn-small"+ @action={{this.refresh}}+ @icon="arrows-rotate"+ @translatedLabel="Refresh"+ />+ </div>+ </:header>+ <:default as |tabs|>+ <tabs.Tab @key="summary" @label="Summary">+ <p>Refreshed+ {{this.refreshCount}}+ times. The refresh button shares the strip row without being a+ tab, so it stays outside the arrow key cycle and out of the+ tablist's ARIA contents.</p>+ </tabs.Tab>+ <tabs.Tab @key="details" @label="Details">+ <p>The tab buttons still render inside the placed tablist, wherever+ the header block put it.</p>+ </tabs.Tab>+ </:default>+ </DTabs>+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/overflow.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/overflow.gjsnew file mode 100644index 00000000000..ca8977615e9--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/overflow.gjs@@ -0,0 +1,69 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import DButton from "discourse/ui-kit/d-button";+import DTabs from "discourse/ui-kit/d-tabs";++const SECTIONS = [+ "Overview",+ "Activity",+ "Badges",+ "Notifications",+ "Messages",+ "Invites",+ "Preferences",+ "Security",+];++export default class TabsOverflowExample extends Component {+ @tracked active = SECTIONS[0];++ sections = SECTIONS;++ @action+ activate(id) {+ this.active = id;+ }++ @action+ selectFirst() {+ this.active = SECTIONS[0];+ }++ @action+ selectLast() {+ this.active = SECTIONS[SECTIONS.length - 1];+ }++ <template>+ <div class="styleguide-tabs__controls">+ <DButton+ @action={{this.selectFirst}}+ @translatedLabel="Select the first tab"+ />+ <DButton+ @action={{this.selectLast}}+ @translatedLabel="Select the last tab"+ />+ <span class="styleguide-tabs__status">Active tab: {{this.active}}</span>+ </div>++ <div class="styleguide-tabs --narrow">+ <DTabs+ @active={{this.active}}+ @label="Account sections"+ @onActivate={{this.activate}}+ as |tabs|+ >+ {{#each this.sections as |section|}}+ <tabs.Tab @key={{section}} @label={{section}}>+ <p>The+ {{section}}+ tab is selected. The strip scrolled only as far as it needed to+ bring this tab fully into view.</p>+ </tabs.Tab>+ {{/each}}+ </DTabs>+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/vertical.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/vertical.gjsnew file mode 100644index 00000000000..b579c9d4457--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/tabs/vertical.gjs@@ -0,0 +1,41 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import DTabs from "discourse/ui-kit/d-tabs";++export default class TabsVerticalExample extends Component {+ @tracked active = "account";++ @action+ activate(id) {+ this.active = id;+ }++ <template>+ <div class="styleguide-tabs --vertical">+ <DTabs+ @active={{this.active}}+ @label="Preference sections"+ @onActivate={{this.activate}}+ @orientation="vertical"+ as |tabs|+ >+ <tabs.Tab @key="account" @label="Account">+ <p>Up and Down move along the strip. Left and Right do nothing here,+ because a tablist has one axis.</p>+ </tabs.Tab>+ <tabs.Tab @key="notifications" @label="Notifications">+ <p>The tablist announces its vertical orientation, which assistive+ technology otherwise assumes horizontal.</p>+ </tabs.Tab>+ <tabs.Tab @key="interface" @label="Interface">+ <p>Placing the strip beside the panel is the consumer's layout; the+ widget stacks the strip and wraps long labels itself.</p>+ </tabs.Tab>+ <tabs.Tab @key="security" @label="Security">+ <p>Home and End jump to the first and last tab on either axis.</p>+ </tabs.Tab>+ </DTabs>+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/navigation-bar.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/navigation-bar.gjsindex a589ad3f6d8..c47e9c9cf42 100644--- a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/navigation-bar.gjs+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/navigation-bar.gjs@@ -3,6 +3,8 @@ import GroupNavPillsExample from "../../examples/molecules/group-nav-pills";import groupNavPillsSource from "../../examples/molecules/group-nav-pills?source=file";import NavigationBarExample from "../../examples/molecules/navigation-bar";import navigationBarSource from "../../examples/molecules/navigation-bar?source=file";+import OverflowingNavExample from "../../examples/molecules/overflowing-nav";+import overflowingNavSource from "../../examples/molecules/overflowing-nav?source=file";import UserNavPillsExample from "../../examples/molecules/user-nav-pills";import userNavPillsSource from "../../examples/molecules/user-nav-pills?source=file";@@ -24,4 +26,19 @@ export default <template>><GroupNavPillsExample @navItems={{@dummy.navItems}} /></StyleguideExample>++ <StyleguideExample+ @code={{overflowingNavSource}}+ @description="A navigation bar that outgrows its width scrolls sideways instead of wrapping. The edge with more items fades out under a chevron, a click scrolls one viewport, holding the chevron keeps scrolling, and the active item is brought into view when the bar mounts."+ @title="<DHorizontalOverflowNav> — more items than fit"+ >+ <:tryThis>+ The active item started off screen and was centered on mount. Click or+ hold a chevron, or swipe the bar, and watch the chevrons swap sides at+ each end.+ </:tryThis>+ <:default>+ <OverflowingNavExample />+ </:default>+ </StyleguideExample></template>diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/overflow-controls.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/overflow-controls.gjsnew file mode 100644index 00000000000..ad54256f4eb--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/overflow-controls.gjs@@ -0,0 +1,69 @@+import StyleguideExample from "discourse/plugins/styleguide/discourse/components/styleguide-example";+import OverflowControlsHorizontalExample from "../../examples/molecules/overflow-controls/horizontal";+import overflowControlsHorizontalSource from "../../examples/molecules/overflow-controls/horizontal?source=file";+import OverflowControlsOwnedExample from "../../examples/molecules/overflow-controls/owned";+import overflowControlsOwnedSource from "../../examples/molecules/overflow-controls/owned?source=file";+import OverflowControlsRevealExample from "../../examples/molecules/overflow-controls/reveal";+import overflowControlsRevealSource from "../../examples/molecules/overflow-controls/reveal?source=file";+import OverflowControlsVerticalExample from "../../examples/molecules/overflow-controls/vertical";+import overflowControlsVerticalSource from "../../examples/molecules/overflow-controls/vertical?source=file";++export default <template>+ <StyleguideExample+ @code={{overflowControlsHorizontalSource}}+ @description="Content wider than its container scrolls sideways with the scrollbar hidden. The edge that has more content fades out, and a chevron sits on it. A click scrolls one viewport; holding the chevron keeps scrolling until you release."+ @title="<DOverflowControls> — a horizontal strip"+ >+ <:tryThis>+ Click the right chevron once, then press and hold it. Swipe or+ Shift-scroll the strip and watch the chevrons swap sides as you reach each+ end.+ </:tryThis>+ <:default>+ <OverflowControlsHorizontalExample />+ </:default>+ </StyleguideExample>++ <StyleguideExample+ @code={{overflowControlsVerticalSource}}+ @description="The same controls follow whichever axis the content's overflow lets it scroll on, so a bounded column gets up and down chevrons with no extra arguments."+ @title="<DOverflowControls> — a vertical column"+ >+ <:tryThis>+ Scroll the column and watch the top chevron appear once the first row+ leaves view.+ </:tryThis>+ <:default>+ <OverflowControlsVerticalExample />+ </:default>+ </StyleguideExample>++ <StyleguideExample+ @code={{overflowControlsOwnedSource}}+ @description="With the owned-scroller argument the consumer renders the scrolling element itself and applies the yielded modifier to it. That keeps the element's own role and styling, which is how the navigation bar and the tab strip use it."+ @title="<DOverflowControls> — a consumer-owned scroller"+ >+ <:tryThis>+ Inspect the list: it is a plain list element with its own class and+ accessible name, and the chevrons are its siblings rather than its+ children.+ </:tryThis>+ <:default>+ <OverflowControlsOwnedExample />+ </:default>+ </StyleguideExample>++ <StyleguideExample+ @code={{overflowControlsRevealSource}}+ @description="The yielded reveal function scrolls the strip, and only the strip, until an element is inside it. Nearest moves the least distance that clears the fade band; center puts the element in the middle. The page never moves."+ @title="<DOverflowControls> — revealing an item"+ >+ <:tryThis>+ Use the buttons above the strip. Nearest brings item 9 to the trailing+ edge; centered puts item 4 in the middle of the strip.+ </:tryThis>+ <:default>+ <OverflowControlsRevealExample />+ </:default>+ </StyleguideExample>+</template>diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/tabs.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/tabs.gjsnew file mode 100644index 00000000000..f27c0f7b6d2--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/tabs.gjs@@ -0,0 +1,71 @@+import StyleguideExample from "discourse/plugins/styleguide/discourse/components/styleguide-example";+import TabsBasicExample from "../../examples/molecules/tabs/basic";+import tabsBasicSource from "../../examples/molecules/tabs/basic?source=file";+import TabsHeaderExample from "../../examples/molecules/tabs/header";+import tabsHeaderSource from "../../examples/molecules/tabs/header?source=file";+import TabsOverflowExample from "../../examples/molecules/tabs/overflow";+import tabsOverflowSource from "../../examples/molecules/tabs/overflow?source=file";+import TabsVerticalExample from "../../examples/molecules/tabs/vertical";+import tabsVerticalSource from "../../examples/molecules/tabs/vertical?source=file";++export default <template>+ <StyleguideExample+ @code={{tabsBasicSource}}+ @description="Each tab declares its strip button and its panel content together, and the widget derives the tablist, the roving tab stop, and the ARIA pairing from that. Selection is controlled: the widget reports the tab the user picks and nothing moves until the owner feeds the id back."+ @title="<DTabs> — controlled selection"+ >+ <:tryThis>+ Move through the strip with the arrow keys, which wrap at either end. The+ disabled tab still takes focus, so it stays discoverable, but Enter and+ Space leave it inert. Use the button above the strip to change the+ selection from outside and watch the tab stop follow it.+ </:tryThis>+ <:default>+ <TabsBasicExample />+ </:default>+ </StyleguideExample>++ <StyleguideExample+ @code={{tabsHeaderSource}}+ @description="A header block replaces the default strip row. The consumer lays out its own row and places the yielded Tablist part wherever it wants; the tab buttons still render inside it and the keyboard surface travels with it."+ @title="<DTabs> — a header block with extra chrome"+ >+ <:tryThis>+ Press Tab from the strip: focus lands on the refresh button, which sits on+ the same row but is not a tab. Press the button and read the count in the+ summary panel.+ </:tryThis>+ <:default>+ <TabsHeaderExample />+ </:default>+ </StyleguideExample>++ <StyleguideExample+ @code={{tabsOverflowSource}}+ @description="A strip wider than its container scrolls sideways rather than wrapping, with the scrollbar hidden. The edge with more tabs fades out under a chevron: a click scrolls one viewport and holding it keeps scrolling. Whenever the selection changes, the widget scrolls the strip just far enough to bring the selected tab fully into view, and it never scrolls the page to do so."+ @title="<DTabs> — an overflowing strip"+ >+ <:tryThis>+ Click or hold a chevron, swipe or Shift-scroll the strip, or walk to the+ hidden tabs with the arrow keys. Then use the buttons above to jump the+ selection between the first and last tab and watch the strip follow.+ </:tryThis>+ <:default>+ <TabsOverflowExample />+ </:default>+ </StyleguideExample>++ <StyleguideExample+ @code={{tabsVerticalSource}}+ @description="The orientation argument flips the arrow-key axis and announces it on the tablist. Placing the strip beside the panel is the consumer's layout; the widget stacks the strip and wraps long labels itself."+ @title="<DTabs> — vertical orientation"+ >+ <:tryThis>+ Up and Down move between tabs. Left and Right do nothing. Home and End+ still jump to the first and last tab.+ </:tryThis>+ <:default>+ <TabsVerticalExample />+ </:default>+ </StyleguideExample>+</template>diff --git a/plugins/styleguide/assets/javascripts/discourse/components/styleguide-subnav.gjs b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-subnav.gjsindex 12d06c29189..caee88cb0d8 100644--- a/plugins/styleguide/assets/javascripts/discourse/components/styleguide-subnav.gjs+++ b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-subnav.gjs@@ -13,7 +13,7 @@ import DHorizontalOverflowNav from "discourse/ui-kit/d-horizontal-overflow-nav";** `DHorizontalOverflowNav` renders the `<ul class="nav-pills">` itself, so this yields bare* `<li>` elements into it; wrapping them in another `<ul>` would break both `.nav-pills > li > a`- * styling and the component's own drag-scroll lookup.+ * styling and the component's active-item reveal lookup.** Active state is computed from `@activeId` rather than left to `<LinkTo>`: the default group* carries no `?group=` in the URL, so Ember would never mark it active. The class goes on thediff --git a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.jsindex e05d0860be6..7fa134b1cdd 100644--- a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js+++ b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js@@ -22,10 +22,12 @@ import menus from "../components/sections/molecules/menus";import multiselect from "../components/sections/molecules/multi-select";import navigationBar from "../components/sections/molecules/navigation-bar";import navigationStacked from "../components/sections/molecules/navigation-stacked";+import overflowControls from "../components/sections/molecules/overflow-controls";import postMenu from "../components/sections/molecules/post-menu";import rovingFocus from "../components/sections/molecules/roving-focus";import segmentedControl from "../components/sections/molecules/segmented-control";import signupCta from "../components/sections/molecules/signup-cta";+import tabs from "../components/sections/molecules/tabs";import toasts from "../components/sections/molecules/toasts";import tooltips from "../components/sections/molecules/tooltips";import topicListItem from "../components/sections/molecules/topic-list-item";@@ -105,6 +107,12 @@ const SECTIONS = [},{ component: topicTimerInfo, category: "molecules", id: "topic-timer-info" },{ component: virtualList, category: "molecules", id: "virtual-list" },+ { component: tabs, category: "molecules", id: "tabs" },+ {+ component: overflowControls,+ category: "molecules",+ id: "overflow-controls",+ },{ component: post, category: "organisms", id: "post", priority: 0 },{ component: postList, category: "organisms", id: "post-list", priority: 1 },{diff --git a/plugins/styleguide/assets/stylesheets/styleguide.scss b/plugins/styleguide/assets/stylesheets/styleguide.scssindex 80678db823d..63b311e7b62 100644--- a/plugins/styleguide/assets/stylesheets/styleguide.scss+++ b/plugins/styleguide/assets/stylesheets/styleguide.scss@@ -1014,6 +1014,104 @@}}+.styleguide-tabs {+ &__controls {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5em;+ align-items: center;+ margin-bottom: 0.5em;+ }++ &__status {+ color: var(--primary-medium);+ }++ &__header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2);+ border-bottom: 1px solid var(--primary-low);+ }++ .d-tabs__strip {+ border-bottom: 1px solid var(--primary-low);+ }++ .d-tabs__panel {+ padding: var(--space-3);+ }++ &.--narrow {+ max-width: 360px;+ }++ &.--vertical {+ .d-tabs {+ flex-direction: row;+ gap: var(--space-3);+ }++ .d-tabs__strip {+ align-items: flex-start;+ border-bottom: 0;+ border-right: 1px solid var(--primary-low);+ }++ .d-tabs__panel {+ flex: 1 1 auto;+ }+ }+}++.styleguide-overflow-controls {+ &.--narrow {+ max-width: 360px;+ }++ &__controls {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5em;+ margin-bottom: 0.5em;+ }++ &__strip {+ display: flex;+ gap: var(--space-2);+ overflow-x: auto;+ padding: var(--space-2) 0;+ }++ &__list {+ @include horizontal-scroll-strip;+ display: flex;+ gap: var(--space-2);+ list-style: none;+ margin: 0;+ padding: var(--space-2) 0;+ }++ &__column {+ height: 160px;+ overflow-y: auto;+ }++ &__chip {+ flex: 0 0 auto;+ padding: var(--space-1) var(--space-3);+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);+ white-space: nowrap;+ }++ &__row {+ padding: var(--space-2) var(--space-3);+ border-bottom: 1px solid var(--primary-very-low);+ }+}+.context-menu-demo {&__surface {display: flex;diff --git a/plugins/styleguide/config/locales/client.en.yml b/plugins/styleguide/config/locales/client.en.ymlindex 1b5f2ef3459..5b8993f3717 100644--- a/plugins/styleguide/config/locales/client.en.yml+++ b/plugins/styleguide/config/locales/client.en.yml@@ -447,3 +447,7 @@ en:title: "Segmented Control (Button toggle group)"virtual_list:title: "Virtual list"+ tabs:+ title: "Tabs"+ overflow_controls:+ title: "Overflow controls"diff --git a/plugins/styleguide/spec/system/smoke_test_spec.rb b/plugins/styleguide/spec/system/smoke_test_spec.rbindex af98265a635..ffe17df6ba3 100644--- a/plugins/styleguide/spec/system/smoke_test_spec.rb+++ b/plugins/styleguide/spec/system/smoke_test_spec.rb@@ -47,6 +47,8 @@ RSpec.describe "Styleguide Smoke Test" do{ href: "/molecules/topic-notifications", title: "Topic Notifications" },{ href: "/molecules/topic-timer-info", title: "Topic Timers" },{ href: "/molecules/virtual-list", title: "Virtual list" },+ { href: "/molecules/tabs", title: "Tabs" },+ { href: "/molecules/overflow-controls", title: "Overflow controls" },],"organisms" => [{ href: "/organisms/post", title: "Post" },@@ -186,6 +188,38 @@ RSpec.describe "Styleguide Smoke Test" doscreenshot_marker(label: "styleguide-drag-and-drop-dwell-open")end+ it "renders the tabs examples" do+ visit "/styleguide/molecules/tabs"++ expect(styleguide).to have_heading("Tabs")+ expect(page).to have_css(".d-tabs [role='tablist']", count: 4)+ expect(page).to have_css(".d-tabs [role='tab'][aria-selected='true']", count: 4)+ expect(page).to have_css(".styleguide-tabs.--vertical [aria-orientation='vertical']")+ expect(page).to have_css(".styleguide-tabs.--narrow .d-overflow-controls__btn.--right")+ screenshot_marker(label: "styleguide-tabs")+ end++ it "renders the overflow controls examples" do+ visit "/styleguide/molecules/overflow-controls"++ expect(styleguide).to have_heading("Overflow controls")+ expect(page).to have_css(".d-overflow-controls", count: 4)+ expect(page).to have_css(".d-overflow-controls__btn.--right", minimum: 3)+ expect(page).to have_css(".d-overflow-controls__btn.--down")+ expect(page).to have_css(".d-overflow-controls.--owned-scroller ul[data-d-scroll-overflow]")+ screenshot_marker(label: "styleguide-overflow-controls")+ end++ it "renders the overflowing navigation bar example" do+ visit "/styleguide/molecules/navigation-bar"++ expect(page).to have_css(+ ".horizontal-overflow-nav .d-overflow-controls__btn.horizontal-overflow-nav__scroll-right",+ )+ expect(page).to have_css(".horizontal-overflow-nav .nav-pills[data-d-scroll-overflow]")+ screenshot_marker(label: "styleguide-navigation-bar-overflow")+ end+it "renders the index page correctly on a site with no default color schemes" doSiteSetting.default_theme_id = Fabricate(:theme).idvisit "/styleguide"