A platform for community discussion. Free, open, simple.
DEV: Add a `DReorderableList` ui-kit component (#42618)
Sérgio Saquetime3e208d474bc
diff --git a/app/assets/stylesheets/common/ui-kit/_index.scss b/app/assets/stylesheets/common/ui-kit/_index.scssindex fb3847388fd..c141cf2dd8f 100644--- a/app/assets/stylesheets/common/ui-kit/_index.scss+++ b/app/assets/stylesheets/common/ui-kit/_index.scss@@ -3,8 +3,10 @@stylesheets not yet moved out of `common/components/` still live there; newui-kit styles belong here. */+@import "d-drag-and-drop";+@import "d-drag-handle";@import "d-pointer-drag";+@import "d-reorderable-list";@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-drag-and-drop.scss b/app/assets/stylesheets/common/ui-kit/d-drag-and-drop.scssindex a0b3fc0f3dc..a112de0bd12 100644--- a/app/assets/stylesheets/common/ui-kit/d-drag-and-drop.scss+++ b/app/assets/stylesheets/common/ui-kit/d-drag-and-drop.scss@@ -96,3 +96,57 @@@include d-drag-outline;}}++/* A table row cannot carry the line itself: a pseudo-element inside a `tr` is+ wrapped in an anonymous table cell, which hands the row a column its table has+ no width for and re-flows every other cell in it.++ The cells carry it instead, where a pseudo-element is ordinary content and+ positioning is well defined. Absolutely positioned, as on every other target:+ that paints in the positioned-descendants layer, above the collapsed border a+ table draws between its header and its first row. Anything painting with the+ cell background instead — an inset shadow, a background image — goes under+ that border, and the line vanishes exactly where a row is dropped into first+ place.++ The row's own `position` is left untouched. A consumer's row may be the+ containing block its cells position against, and resetting it here detaches+ every absolutely positioned cell in the row to some ancestor far up the page. */++:where(tr[data-drop-target] > *, tr[data-drop-target-external] > *) {+ position: relative;+}++tr[data-drop-target],+tr[data-drop-target-external] {+ &.--drag-above::before,+ &.--drag-below::after,+ &.--drag-left::before,+ &.--drag-right::after {+ content: none;+ }++ &.--drag-above > *::before {+ @include d-drag-line(horizontal);+ top: -1px;+ }++ &.--drag-below > *::after {+ @include d-drag-line(horizontal);+ bottom: -1px;+ }++ &.--drag-left > *:first-child::before {+ @include d-drag-line(vertical);++ /*! rtl:ignore */+ left: -1px;+ }++ &.--drag-right > *:last-child::after {+ @include d-drag-line(vertical);++ /*! rtl:ignore */+ right: -1px;+ }+}diff --git a/app/assets/stylesheets/common/ui-kit/d-drag-handle.scss b/app/assets/stylesheets/common/ui-kit/d-drag-handle.scssnew file mode 100644index 00000000000..f2bdde9d06a--- /dev/null+++ b/app/assets/stylesheets/common/ui-kit/d-drag-handle.scss@@ -0,0 +1,8 @@+/* The grab affordance on a draggable row. Colour and cursor only: where the+ handle sits in the row is the consumer's business, since only it knows+ whether the row is one line or many. */++.d-drag-handle {+ color: var(--primary-low-mid);+ cursor: grab;+}diff --git a/app/assets/stylesheets/common/ui-kit/d-reorderable-list.scss b/app/assets/stylesheets/common/ui-kit/d-reorderable-list.scssnew file mode 100644index 00000000000..fd4786972d9--- /dev/null+++ b/app/assets/stylesheets/common/ui-kit/d-reorderable-list.scss@@ -0,0 +1,179 @@+@use "lib/viewport";++/* The reorderable-list shell. The interaction pieces carry their own styles+ (d-drag-handle, d-drag-and-drop); what lives here is only what the list+ itself owns. */++.d-reorderable-list {+ /* The :where() tag guards carry zero specificity, so only the default+ ul/li rendering is reached and a consumer's row class overrides these at+ equal specificity. */++ &:where(ul) {+ margin: 0;+ padding: 0;+ list-style: none;+ }++ &__row:where(li) {+ display: flex;+ align-items: center;+ gap: 0.5em;+ padding-block: 0.25em;+ }++ /* An emptied group member is a live drop target with no rows to give it+ height; the min-height is what keeps it reachable by pointer. */++ &.--empty-drop-target {+ display: flex;+ align-items: center;+ justify-content: center;+ min-height: 4em;+ padding: 0.5em;+ border: 1px dashed var(--primary-low);+ border-radius: var(--d-border-radius);+ color: var(--primary-medium);+ text-align: center;+ }++ /* Sized to the grip rather than to a button, so the handle never drives a+ dense row's height. Chained with `.btn` to outrank the base button rules+ it would otherwise tie with on source order alone. The slot that holds a+ handle's place in a row without one shares the box, so the two always+ measure the same. */++ &__handle.btn,+ &__handle-slot {+ display: inline-flex;+ align-items: center;+ justify-content: center;++ /* Sized explicitly: the screen-reader description is a block, and a+ button with a block gets none of an icon-only button's spacing, leaving+ a press target smaller than the guidelines accept. */+ min-width: 24px;+ min-height: 24px;+ padding: 0;+ font-size: inherit;+ line-height: inherit;++ .d-icon {+ margin: 0;+ }+ }++ &__handle.btn {+ border: 0;+ background: none;+ color: var(--primary-low-mid);+ cursor: grab;++ .d-icon {+ color: var(--primary-low-mid);+ }++ /* A real ring: the button family's focus background is indistinguishable+ at this size, and often the handle is the row's only control. */++ &:focus-visible {+ outline: 2px solid var(--d-input-focused-color);+ outline-offset: -1px;+ border-radius: var(--d-border-radius);+ }+ }++ &__handle-slot {+ visibility: hidden;+ }++ /* Sized to match the handle, so the two controls the list places read as+ one family. */++ &__remove.btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ min-width: 24px;+ min-height: 24px;+ padding: 0;+ border: 0;+ background: none;+ font-size: inherit;+ line-height: inherit;+ color: var(--primary-low-mid);++ .d-icon {+ margin: 0;+ color: var(--primary-low-mid);+ }++ &:hover .d-icon,+ &:focus-visible .d-icon {+ color: var(--danger);+ }+ }++ /* A frozen row renders no handle, so the row itself carries the ring.+ `:focus` rather than `:focus-within` deliberately: the latter matches+ every ancestor, so a row hosting a list of its own would frame the whole+ section whenever anything inside took focus. */++ &__row:focus {+ outline: 2px solid var(--d-input-focused-color);+ outline-offset: -2px;+ }++ &__create {+ display: flex;+ align-items: center;+ gap: 0.25em;+ }++ /* Two classes to outrank the global text input rule, whose bottom margin+ would lift the input off the add button's centre line. */++ &__create &__create-input {+ margin-bottom: 0;+ }+}++/* In a table cell an inline-level box lands on the text baseline, so the+ grip would ride low against the label beside it. */++td .d-reorderable-list__handle.btn {+ vertical-align: middle;+}++.d-reorderable-list__move-item {+ justify-content: start;+}++/* Inside a menu, focus is the cursor, and a pointer press does not set+ `:focus-visible` — a highlight keyed on that alone opens onto an invisible+ cursor. Kept identical to the dropdown's `:hover` and `:focus-visible`+ declaration so the three agree. */++.d-reorderable-list__move-item:focus:not(:focus-visible) {+ background: var(--d-hover);+ color: var(--primary);+}++/* Selected above the shortcut component's own specificity, whose margin+ reset would otherwise leave the chip column ragged. */++kbd.d-shortcut.d-reorderable-list__move-shortcut {+ margin-inline-start: auto;++ @include viewport.until(sm) {+ display: none;+ }+}++/* Reorderable lists are routinely hosted inside a modal, where the default+ dropdown layer sits under the backdrop and its clicks are swallowed. This+ is the layer the scale reserves for exactly that. */++[data-identifier="reorderable-list-move"] {+ z-index: z("modal", "dropdown");+}diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex d420489d0ef..5d3a264bc29 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -398,6 +398,25 @@ en:skip_to_top: "Skip to top"skip_user_nav: "Skip to profile content"+ reorder:+ announcement: "Moved %{label} to position %{position} of %{total}"+ announcement_cross_list: "Moved %{label} to %{list}, position %{position} of %{total}"+ handle: "Reorder %{label}"+ handle_description: "Use the arrow keys to move between rows. Press Enter for move options."+ handle_description_drag_only: "Drag to move this row."+ remove: "Remove %{label}"+ removed: "Removed %{label}"+ move_up: "Move up"+ move_down: "Move down"+ move_to_top: "Move to top"+ move_to_bottom: "Move to bottom"+ move_to_list: "Move to %{list}"+ position: "%{position} of %{total}"+ at_start: "%{label} is already first"+ at_end: "%{label} is already last"+ move_refused: "Could not move %{label}"+ add_item: "Add an item"+emails_are_disabled: "All outgoing email has been globally disabled by an administrator. No email notifications of any kind will be sent."emails_are_disabled_no_smtp: "All outgoing email is disabled because no SMTP server has been configured. No emails of any kind can be sent."emails_are_disabled_non_staff: "Outgoing email has been disabled for non-staff users."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 a0fc164786b..43442fc8c9d 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@@ -202,7 +202,7 @@ Use the buckets that apply; a two-file split needs only `types.ts`. What goes wh- **`-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>/` (`scroll-strip`, for example, which the overflow controls and the tab strip share), 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. [Private modules](32-private-modules.md) covers where a shared mechanism goes and how to move one out of a single owner.# Blast radius and backward compatibility@@ -237,3 +237,4 @@ A section should be designed, with multiple examples that each isolate one capab- [Designing for devices](28-designing-for-devices.md) and [responsive widths](29-designing-for-responsive-widths.md).- [Drag, resize, and gesture primitives](30-drag-and-gesture-primitives.md) for the modifiers that handle input.- [Types](27-types.md) for the Glint and TypeScript conventions the kit follows.+- [Private modules](32-private-modules.md) for where `-internals` code goes.diff --git a/docs/developer-guides/docs/03-code-internals/32-private-modules.md b/docs/developer-guides/docs/03-code-internals/32-private-modules.mdnew file mode 100644index 00000000000..75fc0badcf3--- /dev/null+++ b/docs/developer-guides/docs/03-code-internals/32-private-modules.md@@ -0,0 +1,51 @@+---+title: Private modules and the `-internals` convention+short_title: Private modules+id: private-modules+---++<div data-theme-toc="true"> </div>++# What `-internals` means++A folder named `-internals` holds code that is **not public API**. It may be renamed, reshaped or deleted without notice or a deprecation cycle. Plugins and themes must never depend on it.++Only the folder's owner imports from it. Everything else, including core code that uses a primitive, imports the owner's public entry instead. The [UI kit guide](02-ui-kit.md) states the same rule for the kit's primitives. Nothing lints this, so the folder name is the only signal.++# Where it goes++Put `-internals` immediately inside the unit that **owns the concept**. Ownership decides placement, not who imports it.++**One named owner.** A component or module owns the concept, so its internals sit inside it, and only that owner imports them:++```text+ui-kit/d-reorderable-list/-internals/ owned by DReorderableList+lib/blocks/-internals/ owned by the blocks module+```++The UI kit guide's "Splitting a large primitive" section describes how a primitive lays out its own `-internals` folder.++**No single owner.** Several members share the mechanism, so it goes in the `-internals` of the smallest namespace that contains every consumer, under a folder named for the mechanism. The owner is then that namespace, and any member of it may import the folder:++```text+ui-kit/-internals/cursor/ shared by dRovingFocus and DReorderableList,+ both ui-kit members+lib/-internals/drag-and-drop/ shared by ui-kit modifiers and a service, so no+ namespace narrower than the app contains them+```++`lib/` is the app-wide root, which is why a mechanism whose consumers span several namespaces lands there. Reach for it only when nothing narrower fits. A mechanism used only within `ui-kit` belongs to `ui-kit`.++# Choosing++1. Does one component or module own the concept? Then `<owner>/-internals/`.+2. Otherwise, list every consumer and take the smallest namespace containing all of them. Then `<namespace>/-internals/<mechanism>/`.+3. If that namespace is the app itself, it is `lib/-internals/<mechanism>/`.++Do not nest `-internals` under a namespace-scoped `lib/`. A namespace `lib/` (as in `form-kit/lib/`) holds flat, supported helpers. `-internals` already says the code is private, so the extra level adds nothing.++# Splitting a shared mechanism out++When a second consumer appears for something inside one owner's `-internals`, move the shared part up rather than importing across. Keep the move behaviour-neutral and let the existing suite prove it. `ItemScope` and the stepping helpers were lifted out of `ui-kit/modifiers/d-roving-focus/` into `ui-kit/-internals/cursor/` this way, with the modifier's own tests as the gate.++A shared mechanism folder keeps its types next to the code that uses them. Add a `types.ts` only when several files in the folder read from it.diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/item-scope.ts b/frontend/discourse/app/ui-kit/-internals/cursor/item-scope.tssimilarity index 89%rename from frontend/discourse/app/ui-kit/modifiers/d-roving-focus/item-scope.tsrename to frontend/discourse/app/ui-kit/-internals/cursor/item-scope.tsindex 9c7747a739a..960522b90a7 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/item-scope.ts+++ b/frontend/discourse/app/ui-kit/-internals/cursor/item-scope.ts@@ -1,11 +1,15 @@-import type { DRovingFocusDisabledItems } from "./types";+/**+ * Whether an `aria-disabled` item is a cursor target. Named for the two behaviours rather than+ * spelled as a boolean, because the call site should say which one it wants.+ */+export type DisabledItems = "skip" | "focusable";/** Queries an item group and applies its navigation eligibility rules. */export default class ItemScope {constructor(readonly container: HTMLElement,readonly selector: string,- readonly disabledItems: DRovingFocusDisabledItems+ readonly disabledItems: DisabledItems) {}/** Returns every selector-matched item in DOM order. */diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/navigation.ts b/frontend/discourse/app/ui-kit/-internals/cursor/navigation.tssimilarity index 97%rename from frontend/discourse/app/ui-kit/modifiers/d-roving-focus/navigation.tsrename to frontend/discourse/app/ui-kit/-internals/cursor/navigation.tsindex 6f15dd47dd5..560d9fa48bc 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/navigation.ts+++ b/frontend/discourse/app/ui-kit/-internals/cursor/navigation.ts@@ -1,4 +1,5 @@-import type { Orientation } from "./types";+/** The axes a cursor may travel. `"grid"` allows both; the other two allow one each. */+export type Orientation = "grid" | "horizontal" | "vertical";/*** The result of one navigation step. A row edge consumes the key without leaving the group;diff --git a/frontend/discourse/app/ui-kit/d-drag-handle.gts b/frontend/discourse/app/ui-kit/d-drag-handle.gtsnew file mode 100644index 00000000000..6181e3292ee--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-drag-handle.gts@@ -0,0 +1,43 @@+import type { TemplateOnlyComponent } from "@ember/component/template-only";+import dIcon from "discourse/ui-kit/helpers/d-icon";++interface DDragHandleSignature {+ Args: {+ /**+ * Translated name of what the handle drags, shown as its tooltip. Required+ * because a bare grip icon says nothing about which row it belongs to.+ */+ label: string;+ };+ Element: HTMLSpanElement;+}++/**+ * The grab affordance on a draggable row.+ *+ * Deliberately decorative: `aria-hidden` with no tab stop, because a drag is+ * unreachable by keyboard and exposing the handle would offer assistive+ * technology a control it cannot operate. Pair it with a keyboard path that+ * reaches the same outcome, or the surface has none.+ *+ * This is NOT the right component for a handle that is itself an operable+ * control — one that takes focus and can be driven by keyboard. Use a real+ * button there and give it its own accessible name, the way+ * `DReorderableList` does.+ *+ * @example+ * ```hbs+ * <DDragHandle @label={{this.dragLabel}} class="my-block__handle" />+ * ```+ */+const DDragHandle: TemplateOnlyComponent<DDragHandleSignature> = <template>+ <span+ aria-hidden="true"+ class="d-drag-handle"+ tabindex="-1"+ title={{@label}}+ ...attributes+ >{{dIcon "grip-vertical"}}</span>+</template>;++export default DDragHandle;diff --git a/frontend/discourse/app/ui-kit/d-dropdown-menu.gjs b/frontend/discourse/app/ui-kit/d-dropdown-menu.gjsdeleted file mode 100644index ed29ba0a930..00000000000--- a/frontend/discourse/app/ui-kit/d-dropdown-menu.gjs+++ /dev/null@@ -1,25 +0,0 @@-import { hash } from "@ember/helper";--const DropdownItem = <template>- <li class="dropdown-menu__item" ...attributes>{{yield}}</li>-</template>;--const DropdownDivider = <template>- <li ...attributes><hr class="dropdown-menu__divider" /></li>-</template>;--const DropdownSubheader = <template>- <li class="dropdown-menu__subheader" ...attributes>{{yield}}</li>-</template>;--const DDropdownMenu = <template>- <ul class="dropdown-menu" ...attributes>- {{yield- (hash- item=DropdownItem divider=DropdownDivider subheader=DropdownSubheader- )- }}- </ul>-</template>;--export default DDropdownMenu;diff --git a/frontend/discourse/app/ui-kit/d-dropdown-menu.gts b/frontend/discourse/app/ui-kit/d-dropdown-menu.gtsnew file mode 100644index 00000000000..08d5a4230e0--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-dropdown-menu.gts@@ -0,0 +1,68 @@+import type { TOC } from "@ember/component/template-only";+import { hash } from "@ember/helper";++interface DropdownItemSignature {+ Element: HTMLLIElement;+ Blocks: {+ /** The item's content, usually a button or link. */+ default: [];+ };+}++interface DropdownDividerSignature {+ Element: HTMLLIElement;+}++interface DropdownSubheaderSignature {+ Element: HTMLLIElement;+ Blocks: {+ /** The heading text for the group of items that follows. */+ default: [];+ };+}++const DropdownItem: TOC<DropdownItemSignature> = <template>+ <li class="dropdown-menu__item" ...attributes>{{yield}}</li>+</template>;++const DropdownDivider: TOC<DropdownDividerSignature> = <template>+ <li ...attributes><hr class="dropdown-menu__divider" /></li>+</template>;++const DropdownSubheader: TOC<DropdownSubheaderSignature> = <template>+ <li class="dropdown-menu__subheader" ...attributes>{{yield}}</li>+</template>;++interface DDropdownMenuSignature {+ Element: HTMLUListElement;+ Blocks: {+ /** The menu's entries, built from the yielded parts. */+ default: [+ /** The parts a menu is built from, each rendering one list item. */+ dropdown: {+ /** A list item holding one entry of the menu. */+ item: typeof DropdownItem;+ /** A list item holding a horizontal rule between groups of items. */+ divider: typeof DropdownDivider;+ /** A list item holding a heading for the items that follow it. */+ subheader: typeof DropdownSubheader;+ },+ ];+ };+}++/**+ * A list-shaped dropdown menu. It yields the parts its entries are built from,+ * so the markup a menu is made of stays consistent across consumers.+ */+const DDropdownMenu: TOC<DDropdownMenuSignature> = <template>+ <ul class="dropdown-menu" ...attributes>+ {{yield+ (hash+ item=DropdownItem divider=DropdownDivider subheader=DropdownSubheader+ )+ }}+ </ul>+</template>;++export default DDropdownMenu;diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list-group.gts b/frontend/discourse/app/ui-kit/d-reorderable-list-group.gtsnew file mode 100644index 00000000000..06e06e9fbd0--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list-group.gts@@ -0,0 +1,174 @@+import Component from "@glimmer/component";+import { DEBUG } from "@glimmer/env";+import { tracked } from "@glimmer/tracking";+import { assert } from "@ember/debug";+import { isDestroying } from "@ember/destroyable";+import { guidFor } from "@ember/object/internals";+import { schedule } from "@ember/runloop";+import type {+ ReorderableGroupApi,+ ReorderableGroupMember,+ ReorderableMove,+} from "discourse/ui-kit/d-reorderable-list";++/**+ * Aliased to keep the masked expression below on one line. Spelled out it wraps,+ * which puts the `&` a line further down than the disable directive reaches, and+ * an unused directive is deleted by `--fix` while the error it covered stays.+ */+const FOLLOWING = Node.DOCUMENT_POSITION_FOLLOWING;++/**+ * Whether one element comes after another in the document.+ * `compareDocumentPosition` answers with a bitmask whose bits can combine, so+ * the one bit being asked about is masked out rather than compared against+ * the whole result.+ *+ * @param left - The element to look out from.+ * @param right - The element to place relative to it.+ */+function follows(left: HTMLElement, right: HTMLElement): boolean {+ // eslint-disable-next-line no-bitwise+ return Boolean(left.compareDocumentPosition(right) & FOLLOWING);+}++interface DReorderableListGroupSignature<T> {+ Args: {+ /**+ * The single move callback for every member list: in-list moves and+ * cross-list moves alike arrive here, already normalized. Return `false`+ * to veto the announcement. The item type it takes is the one every+ * member list's `@items` must hold.+ */+ onMove: (move: ReorderableMove<T>) => void | false;+ };+ Blocks: {+ /** The member lists, each receiving the yielded API as `@group`. */+ default: [group: ReorderableGroupApi<T>];+ };+}++/**+ * Connects several reorderable lists into one drag surface.+ *+ * The group is renderless: it inserts no element of its own, and its only+ * output is the API it yields. Member lists that receive it as `@group` share+ * one drag token — which is what lets a row dragged out of one member land in+ * another — and route every move through the group's single `@onMove`. Every+ * enabled member that carries a `@listLabel` also appears as a destination in+ * the other members' move menus, which is how a cross-list move is reachable+ * without a pointer.+ *+ * Members register themselves on construction and deregister on destruction,+ * so a drop whose source member has since been torn down resolves to nothing+ * and is refused silently.+ *+ * @example+ * ```gjs+ * <DReorderableListGroup @onMove={{this.applyMove}} as |group|>+ * <DReorderableList @group={{group}} @listId="primary" ... />+ * <DReorderableList @group={{group}} @listId="secondary" ... />+ * </DReorderableListGroup>+ * ```+ */+export default class DReorderableListGroup<T> extends Component<+ DReorderableListGroupSignature<T>+> {+ /** Keeps registry writes out of the member-construction render pass. */+ @tracked generation = 0;++ /**+ * The yielded API. Built once — members hold onto it across their whole+ * life, so its identity must not churn with renders.+ */+ api: ReorderableGroupApi<T> = {+ token: `d-reorderable-list-group:${guidFor(this)}`,+ generation: () => this.generation,+ registerMember: (member: ReorderableGroupMember) => {+ const displaced = this.#members.get(member.listId);+ this.#members.set(member.listId, member);+ schedule("afterRender", () => {+ if (!isDestroying(this)) {+ this.generation++;+ }+ });++ // A re-render builds the replacement before tearing down what it+ // replaces, so a collision here is usually churn, and churn leaves a+ // detached element once the render settles where distinct lists do not.+ // Guarded with DEBUG because `assert` compiles away in production while+ // the scheduling around it would not.+ if (DEBUG && displaced && displaced !== member) {+ schedule("afterRender", () => {+ if (isDestroying(this)) {+ return;+ }+ assert(+ `d-reorderable-list-group: duplicate listId "${member.listId}" — every member needs a unique listId`,+ !displaced.element()?.isConnected+ );+ });+ }++ return () => {+ // Identity-checked so a departing member cannot evict the one that took+ // its place.+ if (this.#members.get(member.listId) === member) {+ this.#members.delete(member.listId);+ schedule("afterRender", () => {+ if (!isDestroying(this)) {+ this.generation++;+ }+ });+ }+ };+ },+ lookupMember: (listId: string) => this.#members.get(listId),+ siblings: (listId: string) =>+ this.#ordered()+ .filter(+ (member) =>+ member.listId !== listId &&+ !member.disabled() &&+ member.listLabel() !== undefined+ )+ .map((member) => ({+ listId: member.listId,+ listLabel: member.listLabel()!,+ })),+ neighbour: (listId: string, direction: "previous" | "next") => {+ const ordered = this.#ordered().filter((member) => !member.disabled());+ const index = ordered.findIndex((member) => member.listId === listId);+ if (index === -1) {+ return undefined;+ }+ return ordered[direction === "next" ? index + 1 : index - 1];+ },+ onMove: (move: ReorderableMove<T>) => this.args.onMove(move),+ };++ /**+ * The registered members, by listId.+ *+ * Deliberately NOT tracked. Members register during construction, so a+ * reactive write here could follow another member's render-time read in the+ * same pass. The separately tracked generation changes only after render.+ */+ #members = new Map<string, ReorderableGroupMember>();++ /**+ * The registered members in document order, never registration order, which+ * stops matching the page as soon as the members themselves are reordered.+ * Members that have not rendered yet are dropped, having no position to+ * sort on.+ */+ #ordered(): ReorderableGroupMember[] {+ return [...this.#members.values()]+ .filter((member) => member.element())+ .sort((left, right) =>+ follows(left.element()!, right.element()!) ? -1 : 1+ );+ }++ <template>{{yield this.api}}</template>+}diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list.gts b/frontend/discourse/app/ui-kit/d-reorderable-list.gtsnew file mode 100644index 00000000000..23d11ddc847--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list.gts@@ -0,0 +1,1174 @@+import Component from "@glimmer/component";+import { DEBUG } from "@glimmer/env";+import { assert } from "@ember/debug";+import {+ associateDestroyableChild,+ isDestroying,+ registerDestructor,+} from "@ember/destroyable";+import { fn, hash } from "@ember/helper";+import { action, get } from "@ember/object";+import { guidFor } from "@ember/object/internals";+import type Owner from "@ember/owner";+import { next, schedule } from "@ember/runloop";+import { service } from "@ember/service";+import { modifier } from "ember-modifier";+import type MenuService from "discourse/float-kit/services/menu";+import type A11yService from "discourse/services/a11y";+import { and, eq, not } from "discourse/truth-helpers";+import ItemScope from "discourse/ui-kit/-internals/cursor/item-scope";+import { step } from "discourse/ui-kit/-internals/cursor/navigation";+import {+ CHORD_TARGETS,+ MENU_CONTENT_SELECTOR,+} from "discourse/ui-kit/d-reorderable-list/-internals/constants";+import MoveMenuCoordinator from "discourse/ui-kit/d-reorderable-list/-internals/coordinators/move-menu-coordinator";+import ReorderAnnouncer from "discourse/ui-kit/d-reorderable-list/-internals/coordinators/reorder-announcer";+import MoveEngine from "discourse/ui-kit/d-reorderable-list/-internals/engine/move-engine";+import CreateRow from "discourse/ui-kit/d-reorderable-list/-internals/parts/create-row";+import HandlePart from "discourse/ui-kit/d-reorderable-list/-internals/parts/handle";+import HandleSlotPart from "discourse/ui-kit/d-reorderable-list/-internals/parts/handle-slot";+import RemovePart from "discourse/ui-kit/d-reorderable-list/-internals/parts/remove";+import type {+ DReorderableListSignature,+ MoveTarget,+ Row,+} from "discourse/ui-kit/d-reorderable-list/types";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import dElement from "discourse/ui-kit/helpers/d-element";+import dDragAndDropSource, {+ type DragPreviewRenderer,+} from "discourse/ui-kit/modifiers/d-drag-and-drop-source";+import dDragAndDropTarget, {+ DropTargetEvent,+ registerDragAndDropTarget,+} from "discourse/ui-kit/modifiers/d-drag-and-drop-target";+import { i18n } from "discourse-i18n";++export type {+ ReorderableGroupApi,+ ReorderableGroupMember,+ ReorderableMove,+ ReorderableRowApi,+} from "discourse/ui-kit/d-reorderable-list/types";++/**+ * What the arrow cursor may land on: one per row, its handle where it renders+ * one and the row itself where it does not. A frozen row still belongs to the+ * list the reader is walking, so leaving it out would make the cursor cover a+ * fraction of what is on screen.+ */+const CURSOR_TARGET = ".d-reorderable-list__handle, [data-reorderable-cursor]";++/**+ * The list root, for telling this list's own rows and controls from those of+ * a nested list. Every DOM lookup below has to say which list it means: a+ * bare `querySelector` from the outer root reaches straight through the inner+ * one and answers with its rows.+ */+const LIST_ROOT = ".d-reorderable-list";++/**+ * Controls that demonstrably do nothing with Up and Down, so a press on one+ * can step the cursor from the row it sits in rather than dying there.+ *+ * An allow-list rather than a list of controls to avoid, so the failure+ * direction is safe: a caret, a radio in its group, a slider, a listbox, and+ * anything this does not recognise all keep their keys. A button that opens a+ * popup is excluded because the arrows may open it, which is also what keeps+ * the row's own handle out.+ */+const ARROW_INERT =+ '[role="switch"], [role="checkbox"], button:not([role]):not([aria-haspopup])';++/**+ * A reorderable list: the standard shell for any surface where the user+ * changes the order of visible rows.+ *+ * The component owns the whole interaction — keyed iteration, the drag+ * handle, the move menu, the keyboard path, boundary state, drop+ * normalization, no-op suppression, focus restoration, and the screen-reader+ * announcement — so a consumer supplies only its row content and one+ * `@onMove` that projects the proposed visible order into its own store.+ * Every input method converges on a single commit: one callback and one+ * announcement per real move, and neither for a move that lands where it+ * started.+ *+ * The handle inside each row is the pointer affordance: the drag source and+ * the move menu's trigger at once. It is also an ordinary tab stop. The list+ * is not a composite widget, since its rows are content carrying their own+ * controls rather than alternatives to choose between, so nothing here manages+ * the tab sequence and every focusable thing in a row is reached in document+ * order.+ *+ * - **Pointer**: drag the handle, or click it and choose a destination. The+ * menu is the single-pointer path WCAG 2.5.1 and 2.5.7 require, since a+ * drag alone leaves anyone who cannot perform one with nothing.+ * - **Keyboard**: Tab reaches every handle and every control a row renders.+ * Enter or Space on a handle opens its move menu through ordinary button+ * activation, and Escape closes it. There is no mode to enter or leave.+ * - **Accelerators**: on a focused handle, a bare arrow moves focus to the+ * neighbouring handle, stepping over the rows' own controls. Alt with an+ * arrow moves the row one step, and Alt with Home/End sends it to an end.+ * Every accelerator is refused anywhere but a handle, so a row's own field+ * keeps its arrows and its chords, and none of them is ever the only path:+ * assistive software that swallows one costs speed rather than access.+ *+ * A move at either end is refused, and the accelerator announces the refusal+ * rather than doing nothing: reaching an end is something the reader should be+ * told, and the silent boundary no-op is one of the failures this component+ * exists to stop surfaces from reinventing. The menu holds only the+ * destinations the row can reach, so the set it publishes to assistive+ * software is the set the cursor can land on. A row that can reach none of+ * them renders no handle rather than one that opens onto nothing. A grouped+ * row keeps its handle as a cross-list drag source but advertises no popup+ * when the menu has no destinations.+ *+ * The list and row elements stay stylable and semantically flexible through+ * `@tag` / `@itemTag` / `@role` / `@itemRole`, which is what lets one+ * component serve plain lists and ARIA table shapes alike.+ *+ * @example+ * ```gjs+ * <DReorderableList+ * @items={{this.sections}}+ * @key="id"+ * @label={{this.sectionLabel}}+ * @onMove={{this.applyMove}}+ * class="my-sections"+ * >+ * <:row as |section|>+ * <span>{{section.name}}</span>+ * </:row>+ * </DReorderableList>+ * ```+ */+export default class DReorderableList<T> extends Component<+ DReorderableListSignature<T>+> {+ @service declare a11y: A11yService;+ @service declare menu: MenuService;++ rowClassFor = (row: Row<T>): string | undefined => {+ const { rowClass } = this.args;+ if (typeof rowClass === "function") {+ return rowClass(row.item, { index: row.index, movable: row.movable });+ }+ return rowClass;+ };++ /**+ * Applied by the handle wherever it renders, so the component knows the row+ * kept its one control regardless of where a manual placement put it.+ */+ registerHandle = modifier((element: Element, [key]: [string]) => {+ this.#handles.set(key, element as HTMLElement);+ return () => {+ if (this.#handles.get(key) === element) {+ this.#handles.delete(key);+ }+ };+ });++ /**+ * Guards the manual-placement contract: a movable row under+ * `@controls="manual"` must place the yielded handle. It is the drag source,+ * the keyboard path and the single-pointer path at once, so a row that omits+ * it has no way to reorder at all. Checked once per row element, after its+ * first render — a consumer that conditionally removes its placed handle+ * later is beyond this guard's reach.+ */+ verifyKeyboardPath = modifier((element: Element) => {+ // The key is read from the element, not taken as an argument: an+ // argument's tracking tag would tear this down and re-run it on every+ // rows recompute instead of once per element.+ if (!DEBUG || !this.isManual) {+ return;+ }+ const key = element.getAttribute("data-reorderable-key") ?? "";+ schedule("afterRender", () => {+ if (isDestroying(this)) {+ return;+ }+ // A row with nowhere to go is yielded no handle to place, so it has+ // none to be missing.+ if (!this.rowFor(key)?.rendersHandle) {+ return;+ }+ assert(+ `d-reorderable-list: the manual row "${key}" renders no handle — place the yielded handle, which is its only drag, keyboard and single-pointer path`,+ this.#handles.has(key)+ );+ });+ });++ /**+ * Registers the list's root element as a drop target while the list is an+ * empty group member — the one state with no rows to land on. Applied+ * statically and registered imperatively: a conditionally curried modifier+ * breaks on the classic-component element wrapper the shell falls back to+ * for non-shortcut tags. Deliberately consumes `acceptsRootDrops`, so it+ * re-registers exactly when the items or group change — never mid-drag.+ */+ rootDropTarget = modifier((element: Element) => {+ if (!this.acceptsRootDrops) {+ return;+ }+ return registerDragAndDropTarget(element, () => ({+ accepts: this.dragType,+ position: "inside" as const,+ onDrop: this.onEmptyRootDrop,+ }));+ });++ /** Dismisses a move menu whose row no longer belongs to the list. */+ reconcileMenu = modifier(+ (_element: Element, [rows, openKey]: [Row<T>[], string | null]) => {+ if (!openKey || rows.some((row) => row.key === openKey)) {+ return;+ }+ schedule("afterRender", () => {+ if (+ !isDestroying(this) &&+ this.menuCoordinator.openKey === openKey &&+ !this.rowFor(openKey)+ ) {+ this.menuCoordinator.closeMenu(false);+ }+ });+ }+ );++ /**+ * The keyboard accelerators, plus the focus bookkeeping the menu needs.+ *+ * Deliberately not `dRovingFocus`: its composite strategy stamps+ * `tabindex="-1"` on every item and makes the arrows the only way between+ * them, and no ARIA role announces a single tab stop that Tab descends+ * into. Here every handle stays an ordinary tab stop, document order is the+ * tab order, and the arrows are a redundant accelerator over it — never the+ * only path, so software that swallows one costs speed rather than access.+ * Only `ItemScope` and `step` are shared with that modifier.+ *+ * Consumes nothing reactive: the row is resolved at event time.+ */+ moveKeys = modifier((element: Element) => {+ this.#listElement = element;++ const onKeydown = (event: Event) => {+ const { key, altKey, ctrlKey, metaKey, shiftKey, target } =+ event as KeyboardEvent;+ if (!(target instanceof HTMLElement)) {+ return;+ }+ const onCursorTarget = target.matches(CURSOR_TARGET);+ // A control the row renders answers for the arrows only when it has no+ // use for them itself. Everything else keeps its keys, so a caret is+ // safe by construction rather than by the list guessing at types.+ const onInertControl = !onCursorTarget && target.matches(ARROW_INERT);+ if (!onCursorTarget && !onInertControl) {+ return;+ }+ // The listener runs in the capture phase, so an outer list sees a+ // nested list's keys first; without this ownership gate it would answer+ // them, and the chord path below stops propagation.+ if (target.closest(LIST_ROOT) !== element) {+ return;+ }+ if (!altKey) {+ // Modified arrows retain their browser and platform shortcuts.+ if (ctrlKey || metaKey || shiftKey) {+ return;+ }+ const delta = key === "ArrowDown" ? 1 : key === "ArrowUp" ? -1 : 0;+ if (!delta) {+ return;+ }+ event.preventDefault();+ const scope = new ItemScope(+ element as HTMLElement,+ CURSOR_TARGET,+ "skip"+ );+ // A nested list's handles are inside this query too; without the+ // filter the cursor walks into rows belonging to another list.+ const targets = scope+ .all()+ .filter((candidate) => candidate.closest(LIST_ROOT) === element);+ // Resolved through the owning row, so a manual placement nested+ // anywhere in the row still resolves to this list's own target.+ const row = target.closest("[data-reorderable-key]");+ const from = onCursorTarget+ ? targets.indexOf(target)+ : targets.findIndex(+ (candidate) => candidate.closest("[data-reorderable-key]") === row+ );+ const outcome = step(+ from,+ delta,+ targets,+ 1,+ "vertical",+ false,+ (item) => scope.isNavigable(item)+ );+ if (outcome.kind === "move") {+ targets[outcome.index].focus();+ }+ return;+ }+ // The chord moves a row, so it belongs to the handle. A cursor row that+ // renders none has nothing to move.+ if (!target.matches(".d-reorderable-list__handle")) {+ return;+ }+ // An Alt chord pressed in a row's own control belongs to that control,+ // and Alt+Arrow is a live shortcut in a text field on several platforms.+ const destination = CHORD_TARGETS[key];+ if (!destination) {+ return;+ }+ const rowKey = target+ .closest("[data-reorderable-key]")+ ?.getAttribute("data-reorderable-key");+ if (!rowKey) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ this.#engine.move(rowKey, destination, "keyboard");+ };++ const onFocusIn = (event: Event) => {+ if (!(event.target instanceof Element)) {+ return;+ }+ // A non-portaled menu renders inside the list; its focus must not read+ // as leaving the row, which would close it before a choice was made.+ if (event.target.closest(MENU_CONTENT_SELECTOR)) {+ return;+ }+ // Any focus inside the row counts as being on the row — including in a+ // nested list, so this walks out to the row this list owns.+ const key = this.#ownRowFor(event.target)?.getAttribute(+ "data-reorderable-key"+ );+ if (this.#focusedKey !== (key ?? null)) {+ this.#focusedKey = key ?? null;+ // The menu is anchored to one row, so focus that has moved on would+ // otherwise leave it floating over a row it no longer describes.+ if (+ this.menuCoordinator.openKey &&+ this.menuCoordinator.openKey !== this.#focusedKey+ ) {+ this.menuCoordinator.closeMenu(false);+ }+ }+ };++ const onFocusOut = () => {+ // Deferred past the render that may be moving the row, so only focus+ // that has settled outside the list clears the record.+ next(() => {+ if (+ isDestroying(this) ||+ this.#listElement?.contains(document.activeElement) ||+ document.activeElement?.closest(MENU_CONTENT_SELECTOR)+ ) {+ return;+ }+ this.#focusedKey = null;+ });+ };++ const onRowClick = (event: Event) => {+ if (!(event.target instanceof Element)) {+ return;+ }+ // Interactive content owns its clicks, and the handle is already the+ // menu trigger, so only the row's dead space reaches the focus below.+ if (+ event.target.closest(+ "button, a, input, select, textarea, [tabindex], [contenteditable='true']"+ )+ ) {+ return;+ }+ // A drag-select of row text is not a request to move focus.+ const selection = window.getSelection();+ if (selection && !selection.isCollapsed) {+ return;+ }+ const row = event.target.closest("[data-reorderable-key]");+ // Ownership rather than containment: a nested list's row is contained by+ // this one too, and its dead space belongs to the list it is in.+ if (!row || row.closest(LIST_ROOT) !== element) {+ return;+ }+ this.handleFor(row.getAttribute("data-reorderable-key") ?? "")?.focus();+ };++ element.addEventListener("keydown", onKeydown, { capture: true });+ element.addEventListener("click", onRowClick);+ element.addEventListener("focusin", onFocusIn);+ element.addEventListener("focusout", onFocusOut);+ return () => {+ element.removeEventListener("keydown", onKeydown, { capture: true });+ element.removeEventListener("click", onRowClick);+ element.removeEventListener("focusin", onFocusIn);+ element.removeEventListener("focusout", onFocusOut);+ this.#listElement = null;+ };+ });++ /**+ * A row's handle element, for the row's drag registration to point at.+ *+ * Deliberately untracked: modifiers install children-first, so a row's own+ * handle is in the map before the row's drag registration reads it. Making+ * it reactive only reintroduced the write-after-read this ordering avoids.+ *+ * @param key - The row key.+ */+ handleFor = (key: string): HTMLElement | undefined => this.#handles.get(key);++ /** The list's one move menu. Public: the template reads its state. */+ menuCoordinator: MoveMenuCoordinator;++ /** The list's root element, held for post-move focus restoration. */+ #listElement: Element | null = null;++ /** The private drag discriminator used when the list stands alone. */+ #ownDragType = `d-reorderable-list:${guidFor(this)}`;++ /**+ * Each row's handle element, by key. Serves the manual-placement guard and+ * gives the shared menu something to anchor against when a row asks to open+ * it.+ */+ #handles = new Map<string, HTMLElement>();++ /**+ * The row focus is in, read only by the focus handler that decides whether+ * an open menu has been left behind.+ *+ * Deliberately untracked: the focus indicator is CSS on real DOM focus, so+ * nothing rendered consumes this. Tracking it means a `focusin` fired by the+ * after-render refocus writes a value the same computation has already read,+ * which is a backtracking-rerender assertion.+ */+ #focusedKey: string | null = null;++ /**+ * Everything this list says out loud. Holds the chord-run state, so it also+ * holds the timer that state needs, and cancels it from its own destructor.+ */+ #announcer: ReorderAnnouncer<T>;++ /** Every committed reorder, in-list and cross-list alike. */+ #engine: MoveEngine<T>;++ constructor(owner: Owner, args: DReorderableListSignature<T>["Args"]) {+ super(owner, args);++ this.#announcer = new ReorderAnnouncer<T>({+ a11y: this.a11y,+ getArgs: () => this.args,+ rows: () => this.rows,+ });+ // Without this the announcer is never destroyed, so its destructor never+ // runs and `isDestroying` inside it stays false for the process's life.+ associateDestroyableChild(this, this.#announcer);++ this.#engine = new MoveEngine<T>({+ args: () => this.args,+ rows: () => this.rows,+ listId: () => this.listIdOrDefault,+ announcer: this.#announcer,+ // Stays on the component: it resolves against the list element the+ // keyboard modifier installs on, which does not exist yet here.+ refocusIndex: (index: number) => this.#refocusIndex(index),+ });++ this.menuCoordinator = new MoveMenuCoordinator({+ menu: this.menu,+ args: () => this.args,+ listId: () => this.listIdOrDefault,+ handleFor: (key: string) => this.handleFor(key),+ rowFor: (key: string) => this.rowFor(key),+ siblings: () => this.siblings(),+ move: (key: string, target: MoveTarget) =>+ this.#engine.move(key, target, "menu"),+ canSpill: (target: MoveTarget) => !!this.#engine.spillTarget(target),+ onRefusedMove: (key: string) => this.#engine.announceRefusal(key),+ });+ // Without this the coordinator is never destroyed, so a menu left open at+ // teardown stays registered with the service for the app's lifetime.+ associateDestroyableChild(this, this.menuCoordinator);++ const { group } = this.args;+ if (group && !this.args.listId) {+ // Reported after render rather than thrown here: an exception unwinding+ // a half-built render corrupts it. The list simply stays unregistered,+ // in production too, so the guard covers only the reporting.+ if (DEBUG) {+ schedule("afterRender", () => {+ if (isDestroying(this)) {+ return;+ }+ assert(+ "d-reorderable-list: @listId is required when the list joins a group",+ false+ );+ });+ }+ } else if (group) {+ const unregister = group.registerMember({+ listId: this.args.listId!,+ disabled: () => !!this.args.disabled,+ listLabel: () => this.args.listLabel,+ getItems: () => this.args.items,+ element: () => (this.#listElement as HTMLElement | null) ?? undefined,+ acceptMove: (+ sourceListId: string,+ key: string,+ toIndex: number,+ method: "menu" | "keyboard"+ ) => {+ const move = this.#engine.commitCrossMove(+ sourceListId,+ key,+ toIndex,+ method+ );+ // Focus follows the item across: only the destination can put+ // focus back on the rebuilt row, and only by landing slot.+ if (move) {+ this.#refocusIndex(move.toIndex);+ }+ return move;+ },+ removalProjection: (key: string) => this.#engine.removalProjection(key),+ });+ registerDestructor(this, unregister);+ }++ if (DEBUG && !group && !this.args.onMove) {+ schedule("afterRender", () => {+ if (isDestroying(this)) {+ return;+ }+ assert(+ "d-reorderable-list: @onMove is required when the list does not join a group",+ !!this.args.onMove+ );+ });+ }+ }++ /**+ * The drag discriminator in force: the group's shared token when the list+ * is a member — which is what lets drags travel between members — and a+ * private per-instance one otherwise, so unrelated lists on one page can+ * never accept each other's drags.+ */+ get dragType(): string {+ return this.args.group?.token ?? this.#ownDragType;+ }++ /**+ * The drag preview for a table row. A `tr` photographed alone collapses:+ * its cells take their widths from columns that belong to the table, so the+ * clone is rebuilt inside a table of its own at the measured widths.+ * Undefined for every other row shape, which leaves the browser's own+ * picture in place.+ */+ get rowDragPreview(): DragPreviewRenderer | undefined {+ if (this.itemTag !== "tr") {+ return undefined;+ }+ return ({ container, element }) => {+ const width = element.getBoundingClientRect().width;+ const cellWidths = Array.from(element.children).map(+ (cell) => cell.getBoundingClientRect().width+ );+ const table = document.createElement("table");+ // The original's classes, so the stylesheet reaches the clone the same way+ // it reaches the row: table styling is written from the table down.+ table.className = element.closest("table")?.className ?? "";+ table.style.width = `${width}px`;+ table.style.tableLayout = "fixed";+ const body = document.createElement("tbody");+ const clone = element.cloneNode(true) as HTMLElement;+ Array.from(clone.children).forEach((cell, index) => {+ (cell as HTMLElement).style.width = `${cellWidths[index]}px`;+ });+ body.append(clone);+ table.append(body);+ container.append(table);+ return () => table.remove();+ };+ }++ get listTag(): string {+ return this.args.tag ?? "ul";+ }++ get itemTag(): string {+ return this.args.itemTag ?? "li";+ }++ get removeIcon(): string {+ return this.args.removeIcon ?? "xmark";+ }++ /** The remove control's button weight, flat by default for dense rows. */+ get removeButtonClass(): string {+ return this.args.removeButtonClass ?? "btn-flat";+ }++ /** Whether the list places the remove control itself. */+ get rendersRemove(): boolean {+ return !!this.args.onRemove && !this.isManual;+ }++ /** Whether the remove control is the consumer's to place. */+ get rendersRemoveManually(): boolean {+ return !!this.args.onRemove && this.isManual;+ }++ get isManual(): boolean {+ return this.args.controls === "manual";+ }++ /**+ * Whether a row without a handle keeps the handle's space, so every row's+ * content starts at the same edge. Only when the list places the handles+ * and at least one row has one; a manual layout spaces its own rows.+ */+ get reservesHandleSlot(): boolean {+ return !this.isManual && this.rows.some((row) => row.rendersHandle);+ }++ /** This list's move-payload identity: its group listId, or `"default"`. */+ get listIdOrDefault(): string {+ return this.args.listId ?? "default";+ }++ /**+ * Whether the list's root element accepts drops: only as an empty group+ * member, where there are no rows to land on. Reads `@items` directly+ * rather than `rows`, so the conditional target below re-curries only when+ * the items themselves change — never on drag-state churn.+ */+ get acceptsRootDrops(): boolean {+ return (+ !!this.args.group && this.args.items.length === 0 && !this.args.disabled+ );+ }++ /**+ * The per-row view models: identity, movability, boundary state, and the+ * translated control labels, computed in one pass so the template and the+ * event handlers read one consistent projection of `@items`.+ */+ get rows(): Row<T>[] {+ const { disabled, items, label, movable, removable } = this.args;+ const seen = new Set<string>();++ const rows = items.map((item, index) => {+ const key = this.#keyFor(item, index);+ if (DEBUG) {+ assert(+ `d-reorderable-list: duplicate row key "${key}" — every item needs a unique key`,+ !seen.has(key)+ );+ seen.add(key);+ }++ const itemLabel = label(item);+ const rowMovable = !disabled && (movable ? movable(item) : true);+ return {+ item,+ key,+ index,+ movable: rowMovable,+ isFirst: false,+ isLast: false,+ canMoveUp: false,+ canMoveDown: false,+ hasDestinations: false,+ rendersHandle: false,+ label: itemLabel,+ handleLabel: i18n("reorder.handle", { label: itemLabel }),+ // The element carrying the description lives inside the handle's+ // button: a bare `span` is not a legal child of `ul` or `tbody`.+ descriptionId: `${guidFor(this)}-move-${index}`,+ removable: !disabled && (removable ? removable(item) : true),+ removeLabel: i18n("reorder.remove", { label: itemLabel }),+ yieldControls: rowMovable && this.isManual,+ };+ });++ const movableRows = rows.filter((row) => row.movable);+ const alone = movableRows.length < 2;+ const { group } = this.args;+ const inGroup = !!group;+ // The generation invalidates this after construction-time registry writes+ // without making the registry itself reactive during member construction.+ const groupGeneration = group?.generation();+ const hasGroupDestinations =+ !!group &&+ groupGeneration !== undefined &&+ (group.siblings(this.listIdOrDefault).length > 0 ||+ (!!this.args.spill &&+ (!!group.neighbour(this.listIdOrDefault, "previous") ||+ !!group.neighbour(this.listIdOrDefault, "next"))));+ for (const [seqIndex, row] of movableRows.entries()) {+ row.isFirst = seqIndex === 0;+ row.isLast = seqIndex === movableRows.length - 1;+ row.canMoveUp = !alone && !row.isFirst;+ row.canMoveDown = !alone && !row.isLast;+ row.hasDestinations =+ row.canMoveUp || row.canMoveDown || hasGroupDestinations;+ // A grouped handle remains the cross-list drag source without a menu.+ row.rendersHandle = row.hasDestinations || inGroup;+ row.yieldControls &&= row.rendersHandle;+ }++ return rows;+ }++ /**+ * The cross-list destinations this list's move menus offer: the group's+ * other named members. Empty for a standalone list, which is what makes the+ * menu collapse to its four in-list destinations without a conditional at+ * the call site.+ *+ * Handed to the handle as a function rather than an array, so the group is+ * consulted when a menu opens rather than while the row renders — members+ * are still registering at that point.+ */+ @action+ siblings(): { listId: string; listLabel: string }[] {+ return this.args.group?.siblings(this.listIdOrDefault) ?? [];+ }++ /**+ * Removes a row on the reader's behalf: hand the item to the consumer, wait+ * for the removal to actually happen, then say so and leave focus somewhere+ * the reader can act again.+ *+ * Awaited and then verified, rather than assumed. A consumer with a+ * confirmation in front of the removal returns before the reader has+ * answered, so announcing on the call would speak over a row still on+ * screen, and checking the count covers a handler that declined without+ * returning a promise.+ *+ * @param key - The row to remove.+ */+ @action+ async onRemove(key: string) {+ const row = this.rows.find((candidate) => candidate.key === key);+ if (!row?.removable) {+ return;+ }+ const index = row.index;+ const keyUsesIndex = this.args.key === "@index";+ const beforeOccurrences = keyUsesIndex+ ? this.args.items.filter((item) => Object.is(item, row.item)).length+ : 0;+ const controlIndex = this.#removeControls().findIndex(+ (control) =>+ control+ .closest("[data-reorderable-key]")+ ?.getAttribute("data-reorderable-key") === key+ );+ // Captured before the handler runs: whatever it puts in front of the+ // reader takes focus away, and this is where they were.+ const asked = document.activeElement as HTMLElement | null;+ await this.args.onRemove?.(row.item, index);+ if (isDestroying(this)) {+ return;+ }+ const rowRemains = keyUsesIndex+ ? this.args.items.filter((item) => Object.is(item, row.item)).length >=+ beforeOccurrences+ : !!this.rowFor(key);+ if (rowRemains) {+ // Declined: nothing is announced, but a confirmation hands focus back+ // to an element it already detached, so put the reader back.+ this.#restoreLostFocus(() => asked);+ return;+ }+ this.a11y.announce(i18n("reorder.removed", { label: row.label }));+ schedule("afterRender", () => {+ if (isDestroying(this)) {+ return;+ }+ this.#removalFocusTarget(controlIndex)?.focus();+ });+ // Re-asserted once everything else has settled, in case the handler put+ // something in front of the reader that returns focus after this.+ this.#restoreLostFocus(() => this.#removalFocusTarget(controlIndex));+ }++ /**+ * The row a key names, for the menu to read boundary state from while open.+ *+ * @param key - The row key.+ */+ rowFor(key: string): Row<T> | undefined {+ return this.rows.find((row) => row.key === key);+ }++ /**+ * Refuses a row's own in-list drag as a drop candidate, which is what keeps+ * the drop indicator from offering a row a position relative to itself. A+ * same-valued key arriving from another group member is a different item+ * and stays droppable.+ *+ * @param rowKey - This row's key.+ * @param feedback - The target modifier's gate payload.+ */+ @action+ canDropOnRow(+ rowKey: string,+ { source }: { source: { data: Record<string, unknown> } }+ ) {+ return (+ source.data.key !== rowKey || source.data.listId !== this.listIdOrDefault+ );+ }++ /**+ * The drop path for one row target. The payload carries only the dragged+ * row's key; the item and both indices are resolved against the current+ * rows here, so a host that replaced its items mid-drag still lands the+ * drop on the right thing — or refuses it when the key is gone.+ *+ * @param targetKey - The key of the row the drop landed on.+ * @param event - The target modifier's drop payload.+ */+ @action+ onRowDrop(targetKey: string, { position, source }: DropTargetEvent) {+ const rows = this.rows;+ const targetRow = rows.find((candidate) => candidate.key === targetKey);+ if (!targetRow?.movable) {+ return;+ }++ const sourceListId = source.data.listId as string | undefined;+ if (this.args.group && sourceListId !== this.listIdOrDefault) {+ const toIndex = targetRow.index + (position === "after" ? 1 : 0);+ this.#engine.commitCrossMove(+ sourceListId,+ source.data.key as string,+ toIndex,+ "drag"+ );+ return;+ }++ const sourceRow = rows.find(+ (candidate) => candidate.key === source.data.key+ );+ if (!sourceRow?.movable) {+ return;+ }++ const seq = rows.filter((candidate) => candidate.movable);+ const from = seq.indexOf(sourceRow);+ let to = seq.indexOf(targetRow);+ if (position === "after") {+ to += 1;+ }+ if (from < to) {+ to -= 1;+ }++ this.#engine.commitSeqMove("drag", rows, seq, from, to);+ }++ /**+ * The drop path for the list's own root element, registered only while the+ * list is an empty group member — the one state with no rows to land on.+ *+ * @param event - The target modifier's drop payload.+ */+ @action+ onEmptyRootDrop({ source }: DropTargetEvent) {+ if (!this.acceptsRootDrops || this.rows.length > 0) {+ return;+ }+ this.#engine.commitCrossMove(+ source.data.listId as string | undefined,+ source.data.key as string,+ 0,+ "drag"+ );+ }++ #keyFor(item: T, index: number): string {+ const { key } = this.args;+ if (key === "@index") {+ return String(index);+ }+ if (key) {+ return String(get(item as object, key));+ }+ return guidFor(item);+ }++ /**+ * The remove control at the departing control's place, or the final one when+ * the departing control was last.+ *+ * @param index - The removed control's index among rendered controls.+ */+ #successorControl(index: number): HTMLElement | undefined {+ const controls = this.#removeControls();+ return controls[index] ?? controls.at(-1);+ }++ #removeControls(): HTMLElement[] {+ return Array.from(+ this.#listElement?.querySelectorAll<HTMLElement>(+ ".d-reorderable-list__remove"+ ) ?? []+ ).filter((control) => control.closest(LIST_ROOT) === this.#listElement);+ }++ /** Finds the next useful control, or makes the list root focusable. */+ #removalFocusTarget(index: number): HTMLElement | undefined {+ const successor = this.#successorControl(index);+ if (successor) {+ return successor;+ }+ const createInput = Array.from(+ this.#listElement?.querySelectorAll<HTMLElement>(+ ".d-reorderable-list__create-input"+ ) ?? []+ ).find((input) => input.closest(LIST_ROOT) === this.#listElement);+ if (createInput) {+ return createInput;+ }+ const list = this.#listElement as HTMLElement | null;+ if (list && !list.hasAttribute("tabindex")) {+ list.setAttribute("tabindex", "-1");+ }+ return list ?? undefined;+ }++ /**+ * Puts focus back only if it was lost, once the runloop has drained.+ *+ * Deferred rather than set directly, because whatever took focus away is+ * still tearing itself down and would land after. Resolved late for the same+ * reason: the element to focus may not exist until that teardown is over.+ *+ * @param candidate - Where focus should go, resolved when this runs.+ */+ #restoreLostFocus(candidate: () => HTMLElement | null | undefined) {+ next(() => {+ if (isDestroying(this)) {+ return;+ }+ const active = document.activeElement;+ if (active && active !== document.body && active.isConnected) {+ return;+ }+ candidate()?.focus();+ });+ }++ /**+ * Takes focus back onto a handle after its row moved in the DOM, which+ * blurs it. Without this a keyboard user lands on the body after one move+ * and cannot make a second.+ *+ * Addressed by visible index rather than by key, and resolved against the+ * projection as it stands after the render. A list keyed by position hands+ * the vacated key to whichever row filled the slot, so a key captured before+ * the move names the wrong row by the time this runs.+ *+ * @param index - The moved row's visible index after the move.+ */+ #refocusIndex(index: number) {+ schedule("afterRender", () => {+ if (isDestroying(this)) {+ return;+ }+ const row = this.rows[index];+ if (!row) {+ return;+ }+ // The registry rather than a query: the handles this list registered are+ // its own by construction, where a descendant selector from the root+ // reaches a nested list's handles as readily as this row's.+ this.handleFor(row.key)?.focus();+ });+ }++ /**+ * The row THIS list owns that contains an element, if any.+ *+ * Rows nest: a list rendered inside a row puts its own rows inside that one,+ * so the innermost `[data-reorderable-key]` above an element frequently+ * belongs to a different list. Walking outwards past those is what makes the+ * answer this list's own row.+ *+ * @param element - Anything inside the list.+ */+ #ownRowFor(element: Element): Element | null {+ let candidate = element.closest("[data-reorderable-key]");+ while (candidate && candidate.closest(LIST_ROOT) !== this.#listElement) {+ candidate =+ candidate.parentElement?.closest("[data-reorderable-key]") ?? null;+ }+ return candidate;+ }++ <template>+ {{#let (dElement this.listTag) as |List|}}+ <List+ class={{dConcatClass+ "d-reorderable-list"+ (if this.acceptsRootDrops "--empty-drop-target")+ }}+ role={{@role}}+ ...attributes+ {{this.rootDropTarget}}+ {{this.moveKeys}}+ {{this.reconcileMenu this.rows this.menuCoordinator.openKey}}+ >+ {{yield to="hint"}}+ {{yield to="header"}}+ {{#if this.rows.length}}+ {{#let+ (dElement this.itemTag) this.reservesHandleSlot+ as |Item reservesHandleSlot|+ }}+ {{#each this.rows key="key" as |row|}}+ {{! Two whole-row branches rather than a conditionally curried+ modifier: that is re-created on every rows recompute, and+ re-installing the drop target mid-drag leaves a dead+ registration. }}+ {{#if row.movable}}+ <Item+ class={{dConcatClass+ "d-reorderable-list__row"+ (this.rowClassFor row)+ }}+ data-reorderable-cursor={{unless row.rendersHandle "true"}}+ data-reorderable-key={{row.key}}+ role={{@itemRole}}+ tabindex={{unless row.rendersHandle "-1"}}+ {{dDragAndDropSource+ type=this.dragType+ data=(hash key=row.key listId=this.listIdOrDefault)+ dragHandle=(this.handleFor row.key)+ dragPreview=this.rowDragPreview+ disabled=(not row.rendersHandle)+ }}+ {{dDragAndDropTarget+ accepts=this.dragType+ canDrop=(fn this.canDropOnRow row.key)+ onDrop=(fn this.onRowDrop row.key)+ }}+ {{this.verifyKeyboardPath}}+ >+ {{#if (and (not this.isManual) row.rendersHandle)}}+ <HandlePart+ @isOpen={{eq this.menuCoordinator.openKey row.key}}+ @onOpen={{this.menuCoordinator.openMenu}}+ @register={{this.registerHandle}}+ @row={{row}}+ />+ {{else if reservesHandleSlot}}+ <HandleSlotPart />+ {{/if}}+ {{yield+ row.item+ (hash+ index=row.index+ isFirst=row.isFirst+ isLast=row.isLast+ movable=row.movable+ handle=(if+ row.yieldControls+ (component+ HandlePart+ row=row+ onOpen=this.menuCoordinator.openMenu+ isOpen=(eq this.menuCoordinator.openKey row.key)+ register=this.registerHandle+ )+ )+ remove=(if+ (and this.rendersRemoveManually row.removable)+ (component+ RemovePart+ row=row+ icon=this.removeIcon+ buttonClass=this.removeButtonClass+ onRemove=this.onRemove+ )+ )+ )+ to="row"+ }}+ {{#if (and this.rendersRemove row.removable)}}+ <RemovePart+ @buttonClass={{this.removeButtonClass}}+ @icon={{this.removeIcon}}+ @onRemove={{this.onRemove}}+ @row={{row}}+ />+ {{/if}}+ </Item>+ {{else}}+ {{! A frozen row renders no handle, so the row itself is what the+ arrow cursor lands on. Out of the tab sequence: Tab reaches+ the controls the row renders, not the row. }}+ <Item+ class={{dConcatClass+ "d-reorderable-list__row"+ (this.rowClassFor row)+ }}+ data-reorderable-cursor="true"+ data-reorderable-key={{row.key}}+ role={{@itemRole}}+ tabindex="-1"+ >+ {{#if reservesHandleSlot}}+ <HandleSlotPart />+ {{/if}}+ {{yield+ row.item+ (hash+ index=row.index+ isFirst=row.isFirst+ isLast=row.isLast+ movable=row.movable+ )+ to="row"+ }}+ </Item>+ {{/if}}+ {{/each}}+ {{/let}}+ {{else}}+ {{yield to="empty"}}+ {{/if}}+ {{#if @allowCreate}}+ {{#if (has-block "create")}}+ {{yield to="create"}}+ {{else}}+ <CreateRow @itemTag={{this.itemTag}} @onCreate={{@onCreate}} />+ {{/if}}+ {{/if}}+ </List>+ {{/let}}+ </template>+}diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/constants.ts b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/constants.tsnew file mode 100644index 00000000000..8345568ed00--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/constants.ts@@ -0,0 +1,39 @@+import type { MoveTarget } from "discourse/ui-kit/d-reorderable-list/types";++/**+ * How long after the last chord move the full announcement lands. Long enough+ * that a held key reads as one run rather than a stream of sentences, short+ * enough that a deliberate single press still speaks it as a single press.+ */+export const RUN_SETTLE_MS = 400;++/**+ * The handle's grip. Shared with the slot a handle-less row reserves, which is+ * sized by the same icon so the two stay the same width.+ */+export const HANDLE_ICON = "grip-vertical";++/** A table create row spans every real column without measuring the table. */+export const TABLE_CREATE_COLSPAN = 1000;++/** The list's move menu, identified by the attribute float-kit stamps on it. */+export const MENU_IDENTIFIER = "reorderable-list-move";+export const MENU_CONTENT_SELECTOR = `[data-identifier="${MENU_IDENTIFIER}"]`;++/** The destination each accelerator chord asks for. */+export const CHORD_TARGETS: Record<string, MoveTarget | undefined> = {+ ArrowUp: "up",+ ArrowDown: "down",+ Home: "top",+ End: "bottom",+};++/**+ * The accelerator each destination answers to, derived rather than restated so+ * a chord added above appears in the menu without a second table to keep in+ * step. A destination absent here has no accelerator, which is what the menu+ * reads to decide whether to advertise one.+ */+export const TARGET_CHORDS = Object.fromEntries(+ Object.entries(CHORD_TARGETS).map(([key, target]) => [target, key])+) as Partial<Record<MoveTarget, string>>;diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/coordinators/move-menu-coordinator.ts b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/coordinators/move-menu-coordinator.tsnew file mode 100644index 00000000000..8d13b0d7531--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/coordinators/move-menu-coordinator.ts@@ -0,0 +1,275 @@+import { tracked } from "@glimmer/tracking";+import { isDestroying, registerDestructor } from "@ember/destroyable";+import { action } from "@ember/object";+import type DMenuInstance from "discourse/float-kit/lib/d-menu-instance";+import type MenuService from "discourse/float-kit/services/menu";+import {+ MENU_CONTENT_SELECTOR,+ MENU_IDENTIFIER,+} from "discourse/ui-kit/d-reorderable-list/-internals/constants";+import MoveMenu from "discourse/ui-kit/d-reorderable-list/-internals/parts/move-menu";+import type {+ MoveTarget,+ ReorderableGroupApi,+ Row,+} from "discourse/ui-kit/d-reorderable-list/types";++/** The arguments the menu reads, resolved per call rather than captured. */+interface MoveMenuArgs {+ group?: Pick<ReorderableGroupApi, "lookupMember">;+}++interface MoveMenuCoordinatorOptions {+ /** The service that owns every menu's lifecycle and renders its content. */+ menu: MenuService;++ /** The list's current arguments; never a snapshot. */+ args: () => MoveMenuArgs;++ /** The list's group id, or its standalone default. */+ listId: () => string;++ /** The handle element a row's menu anchors to. */+ handleFor: (key: string) => HTMLElement | undefined;++ /**+ * The row a menu item acts on, called while the menu renders rather than+ * when it opens, so boundary marks reflect the list as it currently stands.+ */+ rowFor: (key: string) => Row<unknown> | undefined;++ /** The other group members this list can send a row to. */+ siblings: () => { listId: string; listLabel: string }[];++ /** Commits an in-list move chosen from the menu. */+ move: (key: string, target: MoveTarget) => void;++ /**+ * Whether a step in this direction, refused at the list's own end, would+ * carry the row into the adjacent group member instead. The menu offers the+ * direction when it would, so what it shows and what the accelerator does+ * stay the same answer.+ */+ canSpill: (target: MoveTarget) => boolean;++ /** Announces that an explicit cross-list command was refused. */+ onRefusedMove: (key: string) => void;+}++/**+ * The list's move menu, shown through the `menu` service against whichever+ * row's handle was activated.+ *+ * The menu belongs here rather than to the handle: a list is arbitrarily long,+ * and a menu per row is a cost that scales with the wrong thing. The handle+ * carries only the ARIA saying which row is open. The service owns the+ * instance's lifecycle and renders its content at the app root, so this holds+ * no instance of its own beyond the one needed to close on its own terms.+ */+export default class MoveMenuCoordinator {+ /** The row whose menu is open, and the list's only record of it. */+ @tracked openKey: string | null = null;++ #menuService: MenuService;+ #args: () => MoveMenuArgs;+ #listId: () => string;+ #handleFor: (key: string) => HTMLElement | undefined;+ #rowFor: (key: string) => Row<unknown> | undefined;+ #siblings: () => { listId: string; listLabel: string }[];+ #move: (key: string, target: MoveTarget) => void;+ #canSpill: (target: MoveTarget) => boolean;+ #onRefusedMove: (key: string) => void;+ #ownership: symbol | null = null;++ /**+ * The menu the service last opened for this list, held only so a close can+ * ask for the trigger not to be refocused. The service's own `close` takes+ * no such option.+ */+ #instance: DMenuInstance | null = null;++ constructor({+ menu,+ args,+ listId,+ handleFor,+ rowFor,+ siblings,+ move,+ canSpill,+ onRefusedMove,+ }: MoveMenuCoordinatorOptions) {+ this.#menuService = menu;+ this.#args = args;+ this.#listId = listId;+ this.#handleFor = handleFor;+ this.#rowFor = rowFor;+ this.#siblings = siblings;+ this.#move = move;+ this.#canSpill = canSpill;+ this.#onRefusedMove = onRefusedMove;++ // The content is rendered by the app-root host, not by this list, so a+ // list torn down while open would otherwise leave a menu anchored to a+ // removed trigger and registered with the service for the app's lifetime.+ registerDestructor(this, () => this.#instance?.destroy());+ }++ /**+ * Opens the move menu against a row's handle.+ *+ * Every row shares one identifier, which is what makes opening a second row's+ * menu close the first: the service enforces one open menu per identifier,+ * across sibling lists as well as within one.+ *+ * @param key - The row whose handle was activated.+ */+ @action+ async openMenu(key: string) {+ const trigger = this.#handleFor(key);+ if (!trigger) {+ return;+ }++ if (this.openKey === key) {+ await this.closeMenu();+ return;+ }++ const row = this.#rowFor(key);+ if (+ row &&+ !row.canMoveUp &&+ !row.canMoveDown &&+ this.#siblings().length === 0 &&+ !this.#canSpill("up") &&+ !this.#canSpill("down")+ ) {+ return;+ }++ const ownership = Symbol("move-menu");+ this.#ownership = ownership;+ this.openKey = key;+ const instance =+ (await this.#menuService.show(trigger, {+ identifier: MENU_IDENTIFIER,+ placement: "bottom-start",+ component: MoveMenu,+ autoUpdate: true,+ // The panel holds only the menu itself, so the float element steps+ // out of the way rather than announcing itself as a dialog around it.+ contentRole: "none",+ // Not the tab trap: nothing shows the reader that Tab has stopped+ // meaning "move on", so Tab instead dismisses the menu and resumes+ // the page's sequence from the handle it was opened at.+ inlineTabOrder: true,+ data: { list: this.#menuData(), key },+ onClose: () => {+ if (this.#ownership === ownership) {+ this.#ownership = null;+ this.openKey = null;+ }+ },+ })) ?? null;++ if (isDestroying(this) || this.#ownership !== ownership) {+ if (this.#ownership === ownership) {+ this.#ownership = null;+ }+ instance?.destroy();+ return;+ }+ this.#instance = instance;++ this.#focusFirstDestination();+ }++ /**+ * Closes the list's menu, if it is open.+ *+ * @param focusTrigger - Whether to hand focus back to the handle the menu+ * was opened from. False when focus has already moved elsewhere: the+ * menu's own habit of refocusing its trigger would otherwise drag focus+ * back to the row the reader just left.+ */+ @action+ async closeMenu(focusTrigger = true) {+ this.#ownership = null;+ this.openKey = null;+ if (this.#instance?.expanded) {+ // Closed through the instance rather than the service, which offers no+ // say over the trigger refocus.+ await this.#instance.close({ focusTrigger });+ }+ }++ /**+ * A move chosen from the menu: close first, then commit. The close skips+ * the trigger refocus, so the move's own refocus is what places focus — on+ * the handle of the row that actually moved.+ *+ * @param key - The row to move.+ * @param target - Where to move it.+ */+ @action+ onMenuMove(key: string, target: MoveTarget) {+ this.closeMenu(false);+ this.#move(key, target);+ }++ /**+ * A cross-list move chosen from the menu, which is the only way to reach+ * another member without a pointer.+ *+ * @param key - The row to move.+ * @param listId - The destination member.+ * @param close - Closes the menu the item was chosen from.+ */+ @action+ onMenuMoveToList(key: string, listId: string, close: () => void) {+ close();+ const member = this.#args().group?.lookupMember(listId);+ if (+ !member ||+ !member.acceptMove(this.#listId(), key, member.getItems().length, "menu")+ ) {+ this.#onRefusedMove(key);+ return;+ }+ }++ /**+ * Puts focus on the first destination, which is always a legitimate landing+ * spot: the menu renders only destinations the row can take.+ *+ * Focused without scrolling: the float is placed asynchronously and can+ * still be sitting at the document origin, so asking the browser to reveal+ * it would throw the reader to the top of the page.+ */+ #focusFirstDestination() {+ const content = document.querySelector(MENU_CONTENT_SELECTOR);+ if (!content) {+ return;+ }+ content+ .querySelector<HTMLElement>(".d-reorderable-list__move-item")+ ?.focus({ preventScroll: true });+ }++ /** What the menu part is handed as its list. Row and spill state stay live. */+ #menuData() {+ const siblings = this.#siblings();+ return {+ rowFor: (key: string) => this.#rowFor(key),+ // A destination is revalidated when chosen, so retaining the opened+ // menu's choices makes a membership race an announced refusal.+ siblings: () => siblings,+ canSpill: (target: MoveTarget) => this.#canSpill(target),+ onMenuMove: (key: string, target: MoveTarget) =>+ this.onMenuMove(key, target),+ onMenuMoveToList: (key: string, listId: string, close: () => void) =>+ this.onMenuMoveToList(key, listId, close),+ };+ }+}diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/coordinators/reorder-announcer.ts b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/coordinators/reorder-announcer.tsnew file mode 100644index 00000000000..42e7df824c4--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/coordinators/reorder-announcer.ts@@ -0,0 +1,208 @@+import { isDestroying, registerDestructor } from "@ember/destroyable";+import { cancel, type Timer } from "@ember/runloop";+import discourseLater from "discourse/lib/later";+import type A11yService from "discourse/services/a11y";+import { RUN_SETTLE_MS } from "discourse/ui-kit/d-reorderable-list/-internals/constants";+import type {+ MoveTarget,+ ReorderableMove,+ Row,+} from "discourse/ui-kit/d-reorderable-list/types";+import { i18n } from "discourse-i18n";++/** The arguments the announcements read, resolved per call rather than captured. */+interface AnnouncerArgs<T> {+ label: (item: T) => string;+ announceMove?: (move: ReorderableMove<T>) => string | false;+ listLabel?: string;+}++interface ReorderAnnouncerOptions<T> {+ a11y: A11yService;++ /** The list's current arguments; never a snapshot. */+ getArgs: () => AnnouncerArgs<T>;++ /** The list's current row projection, read only when a run settles. */+ rows: () => Row<T>[];+}++/**+ * Everything a reorderable list says out loud. Owns the chord-run state and+ * therefore its timer, cancelled from its own destructor — which requires the+ * component to call `associateDestroyableChild`, or nothing here is ever+ * destroyed and `isDestroying` stays false forever.+ */+export default class ReorderAnnouncer<T> {+ #a11y: A11yService;+ #getArgs: () => AnnouncerArgs<T>;+ #rows: () => Row<T>[];++ /**+ * The run of consecutive chord moves in flight, if any. A held Alt+arrow+ * would otherwise speak a full sentence per step into a live region that+ * re-announces even an unchanged string, so a run says only where the row+ * now is and the full sentence waits for the run to settle.+ */+ #run: {+ index: number;+ move?: ReorderableMove<T>;+ timer: Timer;+ } | null = null;++ constructor({ a11y, getArgs, rows }: ReorderAnnouncerOptions<T>) {+ this.#a11y = a11y;+ this.#getArgs = getArgs;+ this.#rows = rows;+ registerDestructor(this, () => this.cancelRun());+ }++ /**+ * Speaks one committed move, honoring the `@announceMove` override and the+ * cross-list variant. Reached only after the move's callback owner declined+ * to veto it — the gate lives with the dispatch, not here.+ *+ * @param move - The normalized move to speak.+ */+ announceMove(move: ReorderableMove<T>) {+ const args = this.#getArgs();++ if (args.announceMove) {+ const custom = args.announceMove(move);+ if (custom !== false) {+ this.#a11y.announce(custom);+ }+ return;+ }++ const label = args.label(move.item);+ const position = move.toIndex + 1;+ const total = move.proposedToItems.length;++ // Mid-run, position only; the full sentence lands when the run settles.+ if (this.#run) {+ this.#a11y.announce(i18n("reorder.position", { position, total }));+ return;+ }++ if (move.fromList !== move.toList && args.listLabel) {+ this.#a11y.announce(+ i18n("reorder.announcement_cross_list", {+ label,+ list: args.listLabel,+ position,+ total,+ })+ );+ return;+ }++ this.#announceMoved(move.item, move.toIndex, total);+ }++ /**+ * Marks a chord move as part of a run. A menu move is always deliberate and+ * single, so it ends any run rather than joining one.+ *+ * @param key - The row being moved.+ * @param method - Which input method asked.+ */+ noteRun(key: string, method: "menu" | "keyboard") {+ this.cancelRun();+ if (method !== "keyboard") {+ return;+ }+ // A custom announcer owns its full message and throttling for every move.+ if (this.#getArgs().announceMove) {+ return;+ }+ const index = this.#rows().find((row) => row.key === key)?.index;+ if (index === undefined) {+ return;+ }+ this.#run = {+ index,+ timer: discourseLater(() => {+ if (isDestroying(this)) {+ return;+ }+ const run = this.#run;+ this.#run = null;+ const rows = this.#rows();+ const row = run ? rows[run.index] : undefined;+ if (row && run?.move && Object.is(row.item, run.move.item)) {+ // Counted from the list as it stands, not from the order the move was+ // committed against, which the settle delay may have left behind.+ this.announceMove({+ ...run.move,+ item: row.item,+ toIndex: row.index,+ proposedToItems: rows.map((candidate) => candidate.item),+ });+ }+ }, RUN_SETTLE_MS),+ };+ }++ /** Points the armed chord run at the row's committed landing slot. */+ updateRun(move: ReorderableMove<T>) {+ if (this.#run) {+ this.#run.index = move.toIndex;+ this.#run.move = move;+ }+ }++ /** Ends an armed chord run without speaking for it. */+ cancelRun() {+ if (this.#run) {+ cancel(this.#run.timer);+ this.#run = null;+ }+ }++ /**+ * Speaks a refused move at either end of the list. The refusal is+ * information rather than an error: it is how a reader learns they have+ * arrived, which a silent no-op never tells them.+ *+ * Deliberately does not end an in-flight run: a chord that walks into the+ * boundary still settles into its full sentence afterwards.+ *+ * @param row - The row that could not move.+ * @param target - The direction that was refused.+ */+ announceBoundary(row: Row<T>, target: MoveTarget) {+ // Built from the direction, so neither key appears as a literal anywhere.+ // `reorder.at_start` and `reorder.at_end` are live; a grep will not say so.+ const key = target === "up" || target === "top" ? "at_start" : "at_end";+ this.#a11y.announce(+ i18n(`reorder.${key}`, { label: this.#getArgs().label(row.item) })+ );+ }++ /** Speaks when an explicit destination disappeared or refused the move. */+ announceRefusal(row: Row<T>) {+ this.#a11y.announce(+ i18n("reorder.move_refused", {+ label: this.#getArgs().label(row.item),+ })+ );+ }++ /**+ * Speaks a committed move in the standard form.+ *+ * @param item - The item that moved.+ * @param index - Its visible index afterwards.+ * @param total - The visible list length afterwards.+ */+ #announceMoved(item: T, index: number, total: number) {+ this.#a11y.announce(+ i18n("reorder.announcement", {+ label: this.#getArgs().label(item),+ position: index + 1,+ total,+ })+ );+ }+}diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/engine/move-engine.ts b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/engine/move-engine.tsnew file mode 100644index 00000000000..f5dc63b384a--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/engine/move-engine.ts@@ -0,0 +1,403 @@+import type ReorderAnnouncer from "discourse/ui-kit/d-reorderable-list/-internals/coordinators/reorder-announcer";+import type {+ MoveTarget,+ ReorderableGroupApi,+ ReorderableGroupMember,+ ReorderableMove,+ Row,+} from "discourse/ui-kit/d-reorderable-list/types";++/** The arguments a move reads, resolved per call rather than captured. */+interface MoveEngineArgs<T> {+ items: readonly T[];+ disabled?: boolean;+ group?: ReorderableGroupApi<T>;+ onMove?: (move: ReorderableMove<T>) => void | false;+ listLabel?: string;+ spill?: boolean;+}++interface MoveEngineOptions<T> {+ /** The list's current arguments; never a snapshot. */+ args: () => MoveEngineArgs<T>;++ /** The list's current row projection, resolved at commit time. */+ rows: () => Row<T>[];++ /** The list's group id, or its standalone default. */+ listId: () => string;++ /** What speaks the result. */+ announcer: ReorderAnnouncer<T>;++ /**+ * Returns focus to a row's handle after a commit moved it in the DOM. Owned+ * by the component rather than here, because it resolves against the list+ * element the keyboard modifier installed on.+ */+ refocusIndex: (index: number) => void;+}++/**+ * The move algebra: every committed reorder, in-list and cross-list alike.+ *+ * Owns the single commit chokepoint. Both input methods and both drag paths+ * funnel into `commitSeqMove`, which calls the consumer back once and+ * announces once, and neither for a move that lands where it started.+ */+export default class MoveEngine<T> {+ #args: () => MoveEngineArgs<T>;+ #rows: () => Row<T>[];+ #listId: () => string;+ #announcer: ReorderAnnouncer<T>;+ #refocusIndex: (index: number) => void;++ constructor({+ args,+ rows,+ listId,+ announcer,+ refocusIndex,+ }: MoveEngineOptions<T>) {+ this.#args = args;+ this.#rows = rows;+ this.#listId = listId;+ this.#announcer = announcer;+ this.#refocusIndex = refocusIndex;+ }++ /**+ * The in-list move both the menu and the chord funnel into: one step or one+ * jump within the movable subsequence, then focus back onto the handle the+ * move just displaced.+ *+ * Resolved fresh by key rather than acting on the row object the render+ * captured, because a move commits against the list as it stands now.+ *+ * A move that would leave the list past either end is refused, and the+ * refusal is announced. Reaching an end is information, and a silent no-op is+ * the failure this component exists to stop repeating. With `spill` the menu+ * offers the boundary step too, so both paths arrive here at an end; only+ * the spoken refusal is accelerator-only, the menu never offering a+ * destination that goes nowhere.+ *+ * @param key - The row to move.+ * @param target - Where to move it.+ * @param method - Which input method asked.+ */+ move(key: string, target: MoveTarget, method: "menu" | "keyboard") {+ const rows = this.#rows();+ const row = rows.find((candidate) => candidate.key === key);+ if (!row?.movable) {+ return;+ }++ const seq = rows.filter((candidate) => candidate.movable);+ const from = seq.indexOf(row);+ const to = {+ up: from - 1,+ down: from + 1,+ top: 0,+ bottom: seq.length - 1,+ }[target];++ if (to < 0 || to >= seq.length || to === from) {+ if (!this.#spill(key, target, method)) {+ this.#announcer.announceBoundary(row, target);+ }+ return;+ }++ this.#announcer.noteRun(key, method);+ const committed = this.commitSeqMove(method, rows, seq, from, to);+ // By landing index, not key: on a position-keyed list the old key now+ // names whichever row took the vacated slot.+ if (committed) {+ this.#announcer.updateRun(committed);+ this.#refocusIndex(committed.toIndex);+ }+ }++ /**+ * The member a row leaving this list in a direction would travel into, if+ * this list spills at all and there is a member that way.+ *+ * Read by the menu as well as by the move, so the destination it offers and+ * the destination a chord reaches are the same question asked once.+ *+ * @param target - Where the row was asked to go.+ */+ spillTarget(target: MoveTarget): ReorderableGroupMember | undefined {+ const { group, spill } = this.#args();+ // Only the two steps spill. "To top" and "to bottom" name this list's own+ // ends by definition, so there is no sense in which they overshoot.+ if (!spill || !group || (target !== "up" && target !== "down")) {+ return undefined;+ }+ // Between members "up" and "down" are not fixed directions, so the+ // crossing is asked for in reading order; `spill` says the two coincide.+ return group.neighbour(+ this.#listId(),+ target === "down" ? "next" : "previous"+ );+ }++ /**+ * The single commit both input methods funnel into: splices the move within+ * the movable subsequence, re-interleaves it with the frozen rows (which+ * keep their exact visible indices), suppresses no-ops, calls `@onMove`+ * once, and announces once. Returns the committed move, or `null` for a+ * no-op, so a caller can address the row by where it landed.+ *+ * @param method - Which input method asked for the move.+ * @param rows - The current row projection.+ * @param seq - The movable rows, in visible order.+ * @param from - The item's index within `seq`.+ * @param to - The destination index within `seq`.+ */+ commitSeqMove(+ method: ReorderableMove<T>["method"],+ rows: Row<T>[],+ seq: Row<T>[],+ from: number,+ to: number+ ): ReorderableMove<T> | null {+ const move = this.#buildSeqMove(method, rows, seq, from, to);+ if (move) {+ this.#finalize(move);+ }+ return move;+ }++ /**+ * The destination half of a cross-list move: resolves the source member+ * through the group, asks it for its removal projection, splices the item+ * into this list's visible order, and finalizes. A source member that+ * unregistered mid-drag, or a key that no longer resolves there, refuses+ * the drop. A disabled destination refuses every path at this chokepoint.+ *+ * @param sourceListId - The group listId the payload named as its origin.+ * @param key - The dragged row's key in the source member.+ * @param toIndex - The visible landing index in this list.+ * @param method - Which input method asked for the move.+ */+ commitCrossMove(+ sourceListId: string | undefined,+ key: string,+ toIndex: number,+ method: ReorderableMove<T>["method"]+ ): ReorderableMove<T> | null {+ const { disabled, group, items: toItems } = this.#args();+ if (disabled || !group || !sourceListId) {+ return null;+ }+ const member = group.lookupMember(sourceListId);+ const removal = member?.removalProjection(key);+ if (!member || !removal) {+ return null;+ }++ // The same slot model as everywhere else: frozen destination rows keep+ // their exact visible indices while the list grows by one slot, and the+ // arriving item joins the movable subsequence at the requested position.+ const rows = this.#rows();+ const item = removal.item as T;+ const size = rows.length + 1;+ const empty = Symbol("empty");+ const proposedTo: (T | typeof empty)[] = new Array(size).fill(empty);+ for (const row of rows) {+ if (!row.movable) {+ proposedTo[row.index] = row.item;+ }+ }+ const seqInsert = rows.filter(+ (row) => row.movable && row.index < toIndex+ ).length;+ const queue = rows.filter((row) => row.movable).map((row) => row.item);+ queue.splice(seqInsert, 0, item);+ let cursor = 0;+ let landingIndex = -1;+ for (let index = 0; index < size; index++) {+ if (proposedTo[index] === empty) {+ if (cursor === seqInsert) {+ landingIndex = index;+ }+ proposedTo[index] = queue[cursor++]!;+ }+ }++ const move: ReorderableMove<T> = {+ method,+ item,+ fromList: sourceListId,+ toList: this.#listId(),+ fromIndex: removal.fromIndex,+ toIndex: landingIndex,+ fromItems: member.getItems() as readonly T[],+ toItems,+ proposedFromItems: removal.proposedFromItems as readonly T[],+ proposedToItems: proposedTo as readonly T[],+ };+ this.#finalize(move);+ return move;+ }++ /** Speaks when an explicit cross-list destination can no longer accept. */+ announceRefusal(key: string) {+ const row = this.#rows().find((candidate) => candidate.key === key);+ if (row) {+ this.#announcer.announceRefusal(row);+ }+ }++ /**+ * What this list would look like with one row taken out of it, handed to the+ * group so a destination member can resolve a cross-list drop against the+ * source as it stands at drop time rather than a snapshot.+ *+ * @param key - The row leaving this list.+ * @returns The projection, or `undefined` when the row cannot leave.+ */+ removalProjection(key: string) {+ const rows = this.#rows();+ const moved = rows.find((candidate) => candidate.key === key);+ if (!moved?.movable) {+ return undefined;+ }+ // The same slot model as an in-list move: frozen rows keep their visible+ // indices, the list shrinks by its last slot, and a frozen row that sat+ // on that slot joins the end of the refill queue.+ const size = rows.length - 1;+ const empty = Symbol("empty");+ const proposed: (T | typeof empty)[] = new Array(size).fill(empty);+ const overflow: T[] = [];+ for (const row of rows) {+ if (!row.movable) {+ if (row.index < size) {+ proposed[row.index] = row.item;+ } else {+ overflow.push(row.item);+ }+ }+ }+ const queue = rows+ .filter((row) => row.movable && row.key !== key)+ .map((row) => row.item)+ .concat(overflow);+ let cursor = 0;+ for (let index = 0; index < size; index++) {+ if (proposed[index] === empty) {+ proposed[index] = queue[cursor++]!;+ }+ }+ return {+ item: moved.item,+ fromIndex: moved.index,+ proposedFromItems: proposed as readonly T[],+ };+ }++ /**+ * Hands a row refused at this list's end to the adjacent member.+ *+ * @param key - The row that ran out of room.+ * @param target - The direction it was pushed.+ * @param method - Which input method asked, carried across so the consumer+ * is told what the reader actually did.+ * @returns Whether it went, which is what decides whether the refusal is+ * spoken instead.+ */+ #spill(+ key: string,+ target: MoveTarget,+ method: "menu" | "keyboard"+ ): boolean {+ const member = this.spillTarget(target);+ if (!member) {+ return false;+ }+ // Entering from above lands first and entering from below lands last, so a+ // row keeps travelling the way it was pushed once it has crossed.+ const toIndex = target === "down" ? 0 : member.getItems().length;+ return !!member.acceptMove(this.#listId(), key, toIndex, method);+ }++ /**+ * Builds the normalized move for one step within the movable subsequence,+ * or `null` for a no-op.+ *+ * @param method - Which input method asked for the move.+ * @param rows - The current row projection.+ * @param seq - The movable rows, in visible order.+ * @param from - The item's index within `seq`.+ * @param to - The destination index within `seq`.+ */+ #buildSeqMove(+ method: ReorderableMove<T>["method"],+ rows: Row<T>[],+ seq: Row<T>[],+ from: number,+ to: number+ ): ReorderableMove<T> | null {+ if (to === from) {+ return null;+ }++ const moved = seq[from]!;+ const nextSeq = [...seq];+ nextSeq.splice(from, 1);+ nextSeq.splice(to, 0, moved);++ // Frozen rows keep their visible slots; the movable slots are refilled in+ // the new subsequence order.+ let cursor = 0;+ const proposed = rows.map((row) =>+ row.movable ? nextSeq[cursor++]!.item : row.item+ );+ const toIndex = seq[to]!.index;++ const { items } = this.#args();+ const listId = this.#listId();+ return {+ method,+ item: moved.item,+ fromList: listId,+ toList: listId,+ fromIndex: moved.index,+ toIndex,+ fromItems: items,+ toItems: items,+ proposedFromItems: proposed,+ proposedToItems: proposed,+ };+ }++ /**+ * The single exit for every committed move: routes the callback to the+ * group when the list is a member (its own `@onMove` otherwise), honors the+ * veto and the `@announceMove` override, and speaks exactly one+ * announcement — the cross-list variant when an item landed here from+ * another member and this list carries a `@listLabel`.+ *+ * @param move - The normalized move to report.+ */+ #finalize(move: ReorderableMove<T>) {+ if (!this.#dispatch(move)) {+ this.#announcer.cancelRun();+ return;+ }+ this.#announcer.announceMove(move);+ }++ /**+ * Reports a move to its callback owner — the group when the list is a+ * member, its own `@onMove` otherwise.+ *+ * @param move - The normalized move.+ * @returns Whether the move may be announced (`false` when vetoed).+ */+ #dispatch(move: ReorderableMove<T>): boolean {+ const handler = this.#args().group?.onMove ?? this.#args().onMove;+ return !!handler && handler(move) !== false;+ }+}diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/create-row.gts b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/create-row.gtsnew file mode 100644index 00000000000..091a0904e8b--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/create-row.gts@@ -0,0 +1,116 @@+import Component from "@glimmer/component";+import type { TemplateOnlyComponent } from "@ember/component/template-only";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import type { ModifierLike } from "@glint/template";+import { modifier } from "ember-modifier";+import DButton from "discourse/ui-kit/d-button";+import { TABLE_CREATE_COLSPAN } from "discourse/ui-kit/d-reorderable-list/-internals/constants";+import dElement from "discourse/ui-kit/helpers/d-element";+import { i18n } from "discourse-i18n";++interface CreateRowSignature {+ Args: {+ itemTag: string;+ onCreate?: (value: string) => void;+ };+}++interface CreateControlsSignature {+ Args: {+ captureInput: ModifierLike<{ Element: HTMLInputElement }>;+ onKeydown: (event: KeyboardEvent) => void;+ submit: () => void;+ };+}++const CreateControls: TemplateOnlyComponent<CreateControlsSignature> =+ <template>+ <input+ aria-label={{i18n "reorder.add_item"}}+ class="d-reorderable-list__create-input"+ type="text"+ {{@captureInput}}+ {{on "keydown" @onKeydown}}+ />+ <DButton+ class="btn-flat d-reorderable-list__create-button"+ @action={{@submit}}+ @icon="plus"+ @translatedAriaLabel={{i18n "reorder.add_item"}}+ @translatedTitle={{i18n "reorder.add_item"}}+ />+ </template>;++/**+ * The default create affordance: a text input and an add button rendered as+ * one extra row. Submitting via Enter or the button reports the trimmed value+ * and clears the input; an empty or whitespace-only value reports nothing.+ */+export default class CreateRow extends Component<CreateRowSignature> {+ captureInput = modifier((element: HTMLInputElement) => {+ this.#input = element;+ return () => (this.#input = undefined);+ });++ /**+ * The live input element. Read directly at submit time instead of mirroring+ * keystrokes into tracked state: the value only matters at that moment, and+ * clearing must reach the element's property — resetting a bound attribute+ * would not clear what the user typed.+ */+ #input?: HTMLInputElement;++ get isTableRow(): boolean {+ return this.args.itemTag === "tr";+ }++ @action+ onKeydown(event: KeyboardEvent) {+ // A keydown arriving mid-IME-composition belongs to the candidate window,+ // not to this control.+ if (event.key === "Enter" && !event.isComposing) {+ event.preventDefault();+ this.#submit();+ }+ }++ @action+ submit() {+ this.#submit();+ }++ #submit() {+ const element = this.#input;+ const value = element?.value.trim();+ // Without a handler the value has nowhere to go, so it stays in the input+ // instead of being silently discarded.+ if (!element || !value || !this.args.onCreate) {+ return;+ }+ this.args.onCreate(value);+ element.value = "";+ }++ <template>+ {{#let (dElement @itemTag) as |Wrapper|}}+ <Wrapper class="d-reorderable-list__create">+ {{#if this.isTableRow}}+ <td colspan={{TABLE_CREATE_COLSPAN}}>+ <CreateControls+ @captureInput={{this.captureInput}}+ @onKeydown={{this.onKeydown}}+ @submit={{this.submit}}+ />+ </td>+ {{else}}+ <CreateControls+ @captureInput={{this.captureInput}}+ @onKeydown={{this.onKeydown}}+ @submit={{this.submit}}+ />+ {{/if}}+ </Wrapper>+ {{/let}}+ </template>+}diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/handle-slot.gts b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/handle-slot.gtsnew file mode 100644index 00000000000..89bab3b60a6--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/handle-slot.gts@@ -0,0 +1,19 @@+import type { TOC } from "@ember/component/template-only";+import { HANDLE_ICON } from "discourse/ui-kit/d-reorderable-list/-internals/constants";+import dIcon from "discourse/ui-kit/helpers/d-icon";++/**+ * Holds a handle's place in a row that renders none, so the row's content+ * starts where its neighbours' does. It carries the handle's own icon,+ * invisible, so the two stay the same width at any font size. Hidden from+ * assistive technology: it is spacing, not a control.+ */+const HandleSlotPart: TOC<{ Element: HTMLSpanElement }> = <template>+ <span+ aria-hidden="true"+ class="d-reorderable-list__handle-slot"+ ...attributes+ >{{dIcon HANDLE_ICON}}</span>+</template>;++export default HandleSlotPart;diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/handle.gts b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/handle.gtsnew file mode 100644index 00000000000..eb60810497a--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/handle.gts@@ -0,0 +1,74 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import type { ModifierLike } from "@glint/template";+import DButton from "discourse/ui-kit/d-button";+import { HANDLE_ICON } from "discourse/ui-kit/d-reorderable-list/-internals/constants";+import type { Row } from "discourse/ui-kit/d-reorderable-list/types";+import { i18n } from "discourse-i18n";++interface HandlePartSignature {+ Args: {+ /** The row this handle moves. */+ row: Row<unknown>;++ /** Opens the list's shared menu against this row. */+ onOpen: (key: string) => void;++ /** Whether the shared menu is currently open on this row. */+ isOpen: boolean;++ /**+ * Records the handle's element against the row's key, so the list can+ * find the row's one control wherever it was placed.+ */+ register: ModifierLike<{+ Element: Element;+ Args: { Positional: [string] };+ }>;+ };+ Element: HTMLElement;+}++/**+ * The one control a movable row renders: a real button that is the drag+ * source and the move menu's trigger at once, so a pointer drags or clicks it+ * and a keyboard activates it, with nothing intercepting a plain button.+ *+ * The menu itself belongs to the list, not to this button; the button carries+ * only the menu's ARIA, driven by the list's single record of which row is+ * open.+ *+ * The drag registration belongs to the row: the registered element is what+ * the browser photographs for the drag preview, and registered here a drag+ * would show the grip rather than the row. The row registers instead and+ * names this button as its `dragHandle`.+ */+export default class HandlePart extends Component<HandlePartSignature> {+ @action+ open() {+ this.args.onOpen(this.args.row.key);+ }++ <template>+ <DButton+ aria-describedby={{@row.descriptionId}}+ aria-haspopup={{if @row.hasDestinations "menu"}}+ class="btn-flat d-reorderable-list__handle"+ ...attributes+ @action={{this.open}}+ @ariaExpanded={{if @row.hasDestinations @isOpen}}+ @icon={{HANDLE_ICON}}+ @translatedAriaLabel={{@row.handleLabel}}+ @translatedTitle={{@row.handleLabel}}+ {{@register @row.key}}+ >+ <span class="sr-only" id={{@row.descriptionId}}>+ {{if+ @row.hasDestinations+ (i18n "reorder.handle_description")+ (i18n "reorder.handle_description_drag_only")+ }}+ </span>+ </DButton>+ </template>+}diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/move-menu.gts b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/move-menu.gtsnew file mode 100644index 00000000000..01af9d6226b--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/move-menu.gts@@ -0,0 +1,282 @@+import Component from "@glimmer/component";+import type { TOC } from "@ember/component/template-only";+import { concat, fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import DButton from "discourse/ui-kit/d-button";+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";+import {+ CHORD_TARGETS,+ TARGET_CHORDS,+} from "discourse/ui-kit/d-reorderable-list/-internals/constants";+import type {+ MoveTarget,+ Row,+} from "discourse/ui-kit/d-reorderable-list/types";+import DShortcut from "discourse/ui-kit/d-shortcut";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";+import { i18n } from "discourse-i18n";++interface MoveItemSignature {+ Args: {+ target: string;+ icon: string;+ label: string;+ move: () => void;+ };+}++/**+ * The accelerator a destination answers to, in binding spelling; undefined+ * for a destination with no accelerator, which the shortcut component renders+ * as nothing at all.+ *+ * @param target - The destination, as its own argument names it.+ */+function chordFor(target: string) {+ const key = TARGET_CHORDS[target as MoveTarget];+ return key ? `Alt+${key}` : undefined;+}++/**+ * One destination in the move menu.+ *+ * Only reachable destinations are rendered: an unavailable one would still+ * count in the set the menu publishes to assistive software. The accelerator+ * still reaches the boundary and speaks the refusal in the menu's place.+ *+ * Each destination carries its own modifier class, so a test or page object+ * can name the destination it wants rather than counting menu positions that+ * shift as soon as a group adds a cross-list entry.+ */+const MoveItem: TOC<MoveItemSignature> = <template>+ <DShortcut @keys={{chordFor @target}} as |shortcut|>+ {{! The block form renders no element of its own, so the item is still the+ menu's own child at runtime and the rule is reading the source rather+ than the output. }}+ {{! eslint-disable ember/template-require-context-role }}+ <DButton+ aria-keyshortcuts={{shortcut.aria}}+ class={{dConcatClass+ "btn-transparent d-reorderable-list__move-item"+ (concat "--" @target)+ }}+ role="menuitem"+ @action={{@move}}+ @icon={{@icon}}+ @translatedLabel={{@label}}+ >+ {{! The drawn keys stay out of the accessible name, which the+ keyshortcuts attribute already carries in its own spelling. }}+ <shortcut.Kbd class="d-reorderable-list__move-shortcut" />+ </DButton>+ </DShortcut>+</template>;++/** What the shared move menu is told to act on. */+interface MoveMenuData {+ /** The list that owns the menu, asked for live row state as it renders. */+ list: {+ rowFor: (key: string) => Row<unknown> | undefined;+ siblings: () => { listId: string; listLabel: string }[];+ canSpill: (target: MoveTarget) => boolean;+ onMenuMove: (key: string, target: MoveTarget) => void;+ onMenuMoveToList: (key: string, listId: string, close: () => void) => void;+ };++ /** The row the menu was opened from. */+ key: string;+}++interface MoveMenuSignature {+ Args: {+ /**+ * The list's `MoveMenuData` for the row the menu was opened from. Typed+ * `unknown` because the menu service delivers `@data` untyped.+ */+ data?: unknown;++ /** Closes the menu, supplied by the menu service. */+ close?: () => void;+ };+}++/**+ * The destinations behind one handle.+ *+ * Rendered by the list's single menu instance rather than per row, so it reads+ * the row it was opened for out of `@data` and asks the list for that row's+ * live state. Boundary marks therefore reflect the list as it stands while the+ * menu is open, not as it stood when the row last rendered.+ *+ * A real menu, so the arrows that move between destinations are a pattern+ * assistive software already names rather than one this list invented. The+ * role goes on the list element here, not through the float's `contentRole`,+ * which reaches only the float's outer wrapper — too far out to own these+ * buttons as items.+ */+export default class MoveMenu extends Component<MoveMenuSignature> {+ get row(): Row<unknown> | undefined {+ return this.#data?.list.rowFor(this.#data.key);+ }++ /**+ * Whether a step is offered at all, which is not the same question as+ * whether it stays inside this list: a row at its own end still moves when+ * the list spills, and the destination is simply the next member.+ */+ get canMoveUp(): boolean {+ return !!this.row?.canMoveUp || this.#canSpill("up");+ }++ get canMoveDown(): boolean {+ return !!this.row?.canMoveDown || this.#canSpill("down");+ }++ /** Whether any direction survived, which is what a divider divides. */+ get hasDirections(): boolean {+ return this.canMoveUp || this.canMoveDown;+ }++ get siblings(): { listId: string; listLabel: string }[] {+ return this.#data?.list.siblings() ?? [];+ }++ /**+ * `@data`, narrowed to what the list passes.+ *+ * TODO(typescript-pending): the menu service types a content component's+ * `@data` as `unknown`, so a component that needs a narrower type cannot say+ * so. Drop this cast once that option is generic over its data.+ */+ get #data(): MoveMenuData | undefined {+ return this.args.data as MoveMenuData | undefined;+ }++ /**+ * An accelerator pressed inside the menu, routed to the same place choosing+ * the destination goes. Handled on the list element rather than on each+ * destination: a chord aimed at a boundary has no destination in the menu+ * to receive it, and the refusal still has to be spoken.+ *+ * @param event - The keydown that may carry a chord.+ */+ @action+ onKeydown(event: KeyboardEvent) {+ if (!event.altKey) {+ return;+ }+ const target = CHORD_TARGETS[event.key];+ const data = this.#data;+ if (!target || !data) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ data.list.onMenuMove(data.key, target);+ }++ @action+ move(target: MoveTarget) {+ const data = this.#data;+ data?.list.onMenuMove(data.key, target);+ }++ @action+ moveToList(listId: string) {+ const data = this.#data;+ const { close } = this.args;+ data?.list.onMenuMoveToList(data.key, listId, close ?? (() => {}));+ }++ /**+ * Whether the list would carry a row off its own end in this direction.+ *+ * @param target - The step being considered.+ */+ #canSpill(target: MoveTarget): boolean {+ return this.#data?.list.canSpill(target) ?? false;+ }++ <template>+ <DDropdownMenu+ aria-label={{this.row.handleLabel}}+ role="menu"+ {{on "keydown" this.onKeydown}}+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".d-reorderable-list__move-item"+ wrap=true+ tabStop=false+ itemsKey=this.siblings.length+ }}+ as |dropdown|+ >+ {{! The ends are this list's own by definition, so they are offered only+ while there is somewhere inside it left to go. The steps are offered+ more widely, since a spilling list answers them past its own edge. }}+ {{#if this.row.canMoveUp}}+ <dropdown.item role="none">+ <MoveItem+ @icon="angles-up"+ @label={{i18n "reorder.move_to_top"}}+ @move={{fn this.move "top"}}+ @target="top"+ />+ </dropdown.item>+ {{/if}}+ {{#if this.canMoveUp}}+ <dropdown.item role="none">+ <MoveItem+ @icon="arrow-up"+ @label={{i18n "reorder.move_up"}}+ @move={{fn this.move "up"}}+ @target="up"+ />+ </dropdown.item>+ {{/if}}+ {{#if this.canMoveDown}}+ <dropdown.item role="none">+ <MoveItem+ @icon="arrow-down"+ @label={{i18n "reorder.move_down"}}+ @move={{fn this.move "down"}}+ @target="down"+ />+ </dropdown.item>+ {{/if}}+ {{#if this.row.canMoveDown}}+ <dropdown.item role="none">+ <MoveItem+ @icon="angles-down"+ @label={{i18n "reorder.move_to_bottom"}}+ @move={{fn this.move "bottom"}}+ @target="bottom"+ />+ </dropdown.item>+ {{/if}}+ {{#if this.siblings.length}}+ {{#if this.hasDirections}}+ {{! Not role="separator": the attribute lands on the list item, and+ the rule it wraps is already one, so naming it here would nest a+ separator inside a separator. }}+ <dropdown.divider role="none" />+ {{/if}}+ {{#each this.siblings key="listId" as |sibling|}}+ <dropdown.item role="none">+ <MoveItem+ {{! Deliberately not a directional arrow: the list has no idea+ where a sibling sits on the page, so an arrow would point the+ wrong way as often as not. }}+ @icon="right-left"+ @label={{i18n "reorder.move_to_list" list=sibling.listLabel}}+ @move={{fn this.moveToList sibling.listId}}+ @target="list"+ />+ </dropdown.item>+ {{/each}}+ {{/if}}+ </DDropdownMenu>+ </template>+}diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/remove.gts b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/remove.gtsnew file mode 100644index 00000000000..d60e24c252b--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/-internals/parts/remove.gts@@ -0,0 +1,44 @@+import type { TOC } from "@ember/component/template-only";+import { fn } from "@ember/helper";+import { or } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import type { Row } from "discourse/ui-kit/d-reorderable-list/types";++interface RemovePartSignature {+ Args: {+ row: Row<unknown>;++ /** The icon to render, from the list's `@removeIcon`. */+ icon: string;++ /** The button weight, from the list's `removeButtonClass`. */+ buttonClass?: string;++ /** Reports the row the reader asked to remove. */+ onRemove: (key: string) => void;+ };+ Element: HTMLElement;+}++/**+ * The standard remove control for one row.+ *+ * Only its contract is fixed: an accessible name built from the row's own+ * label, so an icon-only control still says which row it removes. The visuals+ * are the consumer's, through `@icon` and `@buttonClass`. Reach for+ * `@buttonClass` rather than a `class` attribute: `class` merges with the one+ * set here rather than replacing it, so two competing button weights would+ * both land on the element.+ */+const RemovePart: TOC<RemovePartSignature> = <template>+ <DButton+ class="{{or @buttonClass 'btn-flat'}} d-reorderable-list__remove"+ ...attributes+ @action={{fn @onRemove @row.key}}+ @icon={{@icon}}+ @translatedAriaLabel={{@row.removeLabel}}+ @translatedTitle={{@row.removeLabel}}+ />+</template>;++export default RemovePart;diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/README.md b/frontend/discourse/app/ui-kit/d-reorderable-list/README.mdnew file mode 100644index 00000000000..cc8a9274589--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/README.md@@ -0,0 +1,95 @@+# DReorderableList++Maintainer notes. They describe how the component is split across files, the+invariants those files share, and why some code lives where it does. For usage,+see the `Args` block in `types.ts` and the styleguide examples under Molecules.++`d-reorderable-list.gts` is the entry, and `d-reorderable-list-group.gts` joins+several lists. Those two are the only import paths. This directory holds the+collaborators the entry renders with. Outside this directory, only the entry and+the internals' own unit tests import from `-internals/`.++The component owns the whole interaction: keyed iteration, the drag handle, the+move menu, the keyboard path, drop normalization, focus restoration and the+announcement. A surface supplies row content and one `@onMove` that projects the+proposed order into its own store.++| File | Owns |+| --- | --- |+| `types.ts` | Every interface, including the four the entry re-exports as public API. The group imports them through that re-export. |+| `-internals/engine/move-engine.ts` | The move algebra. Every input method funnels into `commitSeqMove`, so one place calls the consumer back and one place announces. Also `removalProjection`, which a sibling list resolves a cross-list drop against. |+| `-internals/coordinators/reorder-announcer.ts` | Everything the list says out loud, including the chord-run state and its settle timer. |+| `-internals/coordinators/move-menu-coordinator.ts` | The single menu instance, re-anchored per row, and the moves made from it. |+| `-internals/parts/` | The rendering subcomponents: `handle`, `handle-slot`, `remove`, `create-row` and `move-menu`. |+| `-internals/constants.ts` | Values that more than one file must agree on. |++## Invariants that cross these files++**Collaborators are destroyable children of the component.** They are plain+classes, built once in the constructor. `isDestroying` only reports `true` for+an object linked into Ember's destroyable tree, so the announcer and the menu+coordinator are passed to `associateDestroyableChild`. Without that link, their+destroyed-guards never trip and their `registerDestructor` callbacks never run.++**Collaborators read arguments through thunks.** Each one receives+`() => this.args` and reads it at the moment it needs a value. Copying an+argument at construction would still pass a first render, then go stale when the+consumer changes it. The group registration is the most exposed case: a copied+`listLabel` would leave a renamed list under its old name in its siblings' move+menus.++**A removal is confirmed before it is announced.** `onRemove` awaits the+consumer's handler, then checks that the row actually left. A consumer may put a+confirmation in front of the removal. Announcing straight away would speak over+a row that is still on screen, and would be wrong if the reader cancels.++**The menu identifier comes from `constants.ts`.** The coordinator opens the menu+under it, and the entry uses it to recognize focus inside the open menu. A copy+that drifts makes the list treat the menu's own focus as focus leaving, which+closes the menu.++## Nesting++Lists can nest, and two mechanisms reach past their own list unless told not to.++The keyboard listener runs in the **capture** phase, so an outer list sees an+inner list's keys first. A gate at the top of the handler ignores keys from any+other list's rows. Without it the outer list would answer them, and because the+chord path stops propagation, the inner list would never see them.++`ItemScope` queries from the list root, so it also finds a nested list's+handles. Anything that walks the DOM filters to elements whose nearest+`.d-reorderable-list` ancestor is this list's root. `#refocusIndex` avoids the+question by reading the handle registry, which only holds this list's handles.++## Spill++`@spill` lets a row refused at one list's end continue into the adjacent list.+`MoveEngine.spillTarget` decides whether there is one, and the menu asks it the+same question, so the menu and the keyboard always offer the same step.++The group resolves "adjacent" in **document order**, not screen position. It+does not lay out its members, and a wrapped group can be side by side at one+width and stacked at another. That is why `neighbour` takes `"previous"` and+`"next"` rather than `"up"` and `"down"`. It is also why `@spill` is opt-in:+turning it on asserts that the lists run top to bottom in reading order.++## Deliberately kept on the component++`#keyFor` and the `rows` projection stay on the component, because the engine+does not call them. `rows` has no `@cached`.++`#refocusIndex` stays because it resolves against the element the keyboard+modifier installs on. That element does not exist yet when the engine is built,+so an engine holding it would fall back to a document-wide query. That query+finds the wrong list as soon as two index-keyed lists share a key.++The dispatch decides whether to announce, not the announcer. An engine that+always announced would speak a move that `@onMove` vetoed by returning `false`.++## Announcements++`reorder.at_start` and `reorder.at_end` are built from the refused direction, so+neither key appears as a literal in the code. A search for them only finds the+comment in `reorder-announcer.ts` that marks them as live. Do not delete them as+unused.diff --git a/frontend/discourse/app/ui-kit/d-reorderable-list/types.ts b/frontend/discourse/app/ui-kit/d-reorderable-list/types.tsnew file mode 100644index 00000000000..f94455e4c53--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-reorderable-list/types.ts@@ -0,0 +1,485 @@+import type { ComponentLike } from "@glint/template";++/**+ * One normalized move, as both input methods report it. The indices and item+ * arrays all describe the VISIBLE list — the `items` the consumer passed —+ * never a backing store the consumer may keep behind it.+ */+export interface ReorderableMove<T = unknown> {+ /** How the user asked for the move. */+ method: "drag" | "menu" | "keyboard";++ /** The item that moved, resolved against the current items at commit time. */+ item: T;++ /** The list the item left. Always `"default"` for a standalone list. */+ fromList: string;++ /** The list the item entered. Always `"default"` for a standalone list. */+ toList: string;++ /** The item's visible index before the move. */+ fromIndex: number;++ /** The item's visible index after the move. */+ toIndex: number;++ /** The source list's visible items before the move. */+ fromItems: readonly T[];++ /**+ * The destination list's visible items before the move. The same array as+ * `fromItems` for an in-list move.+ */+ toItems: readonly T[];++ /** The source list's proposed visible order after the move. */+ proposedFromItems: readonly T[];++ /**+ * The destination list's proposed visible order after the move. The same+ * array as `proposedFromItems` for an in-list move.+ */+ proposedToItems: readonly T[];+}++/**+ * The row's own position and its pre-wired controls, yielded to `<:row>`+ * beside the item. Conventionally bound as `controls`, matching the+ * `@controls` argument that decides whether the list places them or the+ * consumer does.+ */+export interface ReorderableRowApi {+ /** The row's index in the visible list. */+ index: number;++ /** Whether the row occupies the first movable slot. */+ isFirst: boolean;++ /** Whether the row occupies the last movable slot. */+ isLast: boolean;++ /** Whether the row can be reordered at all. */+ movable: boolean;++ /**+ * The pre-wired handle for this row. Yielded only under `@controls="manual"`+ * on a movable row that renders a handle: one with a reachable destination,+ * or any grouped row, whose handle stays the cross-list drag source. It is+ * the drag source and the move menu's trigger at once, so a row yielded one+ * must place it; a development assertion fires when one does not.+ */+ handle?: ComponentLike<{ Element: HTMLElement }>;++ /**+ * The pre-wired remove control. Yielded only under `@controls="manual"` on a+ * movable, removable row when `onRemove` is set; a frozen row yields no+ * controls at all. Carries its own accessible name; everything visual passes+ * through.+ */+ remove?: ComponentLike<{+ Args: { buttonClass?: string };+ Element: HTMLElement;+ }>;+}++/** The context handed to a `@rowClass` function. */+export interface RowClassContext {+ index: number;+ movable: boolean;+}++/**+ * What a member list registers with its group: identity, the optional+ * translated list name for cross-list announcements, and closures reading the+ * member's live state — closures rather than snapshots, so a drop resolves+ * against the source list as it stands at drop time.+ */+export interface ReorderableGroupMember {+ listId: string;++ /** Whether the member currently refuses every move. */+ disabled: () => boolean;++ /** The member's current translated name. */+ listLabel: () => string | undefined;++ /** The member's current visible items. */+ getItems: () => readonly unknown[];++ /**+ * The member's root element, for resolving which member sits next to which+ * in document order. Undefined before the member has rendered.+ */+ element: () => HTMLElement | undefined;++ /**+ * The source half of a cross-list move: resolves the dragged key against+ * the member's current rows and returns the item, its visible index, and+ * the member's proposed order without it — or `undefined` when the key no+ * longer resolves to a movable row.+ */+ removalProjection: (key: string) =>+ | {+ item: unknown;+ fromIndex: number;+ proposedFromItems: readonly unknown[];+ }+ | undefined;++ /**+ * The destination half of a cross-list move, as the menu path calls it. A+ * drop already runs on the destination, but a menu item runs on the source,+ * so the source reaches across to the member that owns the projections and+ * the announcement for where the item is landing.+ *+ * @param sourceListId - The member the item is leaving.+ * @param key - The moved row's key in that member.+ * @param toIndex - The visible landing index in this member.+ * @param method - Which input method asked, carried across so a spilled+ * accelerator is not reported to the consumer as a menu choice.+ */+ acceptMove: (+ sourceListId: string,+ key: string,+ toIndex: number,+ method: "menu" | "keyboard"+ ) => ReorderableMove | null;+}++/**+ * The API a `DReorderableListGroup` yields to its block. Member lists receive+ * it as `@group`; everything on it is wiring between the group and its+ * members rather than a consumer surface. `T` is the item type the group's+ * `@onMove` takes, which every member list's items must match.+ */+export interface ReorderableGroupApi<T = unknown> {+ /**+ * The shared drag discriminator. Members adopt it in place of their own, so+ * drags travel freely inside the group and nowhere else.+ */+ token: string;++ /** Lets projections react without tracking the construction-time registry. */+ generation: () => number;++ /** Adds a member; returns its deregistration. Duplicate listIds assert. */+ registerMember: (member: ReorderableGroupMember) => () => void;++ /** The member registered under a listId, if it still exists. */+ lookupMember: (listId: string) => ReorderableGroupMember | undefined;++ /**+ * The other members registered right now, in document order, as the move+ * menu's cross-list destinations. Only enabled members carrying a+ * `listLabel` are returned: an unnamed destination has nothing to put in the+ * menu item, so it stays pointer-only rather than offering "Move to+ * undefined".+ */+ siblings: (listId: string) => { listId: string; listLabel: string }[];++ /**+ * The member immediately before or after another **in reading order**, which+ * is what a row spilling past its own list's end travels into. Disabled+ * members are skipped because they cannot accept the spill.+ *+ * Reading order, not screen position or registration order: the group cannot+ * see where its members landed, and registration order stops matching the+ * document as soon as the members themselves are reordered. `spill` is+ * opt-in because "next in the document" meaning "next on screen" is the+ * consumer's claim to make.+ *+ * @param listId - The member to look out from.+ * @param direction - Which way along the document to look.+ */+ neighbour: (+ listId: string,+ direction: "previous" | "next"+ ) => ReorderableGroupMember | undefined;++ /** The group's single move callback, shared by every member. */+ onMove: (move: ReorderableMove<T>) => void | false;+}++/**+ * The internal per-row view model the component renders from. Rows are+ * recomputed from `@items` on every relevant change, so anything an event+ * handler needs later is re-resolved by `key` rather than captured.+ */+export interface Row<T> {+ item: T;+ key: string;+ index: number;+ movable: boolean;+ isFirst: boolean;+ isLast: boolean;+ /** Whether stepping in this direction lands anywhere the row is not already. */+ canMoveUp: boolean;+ canMoveDown: boolean;++ /**+ * Whether the move menu has a reachable destination. A grouped row may still+ * render a handle as its cross-list drag source when this is false.+ */+ hasDestinations: boolean;++ /**+ * Whether the row renders a handle. What the arrow cursor lands on: the+ * handle where this is true, the row element itself where it is not.+ */+ rendersHandle: boolean;++ /** The row's own accessible name: what the reader is moving. */+ label: string;+ handleLabel: string;++ /** Shared by the row's `aria-describedby` and its handle's description. */+ descriptionId: string;++ /** Whether this row may be removed at all. */+ removable: boolean;++ /** The remove control's accessible name. */+ removeLabel: string;+ yieldControls: boolean;+}++export interface DReorderableListSignature<T> {+ Args: {+ /**+ * The visible items in display order. The component reasons, indexes, and+ * announces only in this list; projecting a reorder onto hidden backing+ * storage stays with the consumer. Never mutated by the component.+ */+ items: readonly T[];++ /**+ * Property path resolving each item's stable identity, used for keyed+ * rendering and for resolving drag payloads at drop time. The literal+ * value `"@index"` opts into index-based identity for primitive+ * collections whose values may repeat. Omitted, object identity is used,+ * which is only safe when the same objects are passed on every render.+ *+ * Index identity is positional by definition: after a move, rows keep+ * their positions while items flow through them, so focus and drag state+ * stay with a position rather than following the moved item. That is how+ * position-addressed value lists already behave, and is the trade-off+ * accepted when items carry no identity of their own.+ */+ key?: string;++ /**+ * Translated display name for an item. It names the drag handle, the+ * remove control, and the announcements, so every control stays+ * distinguishable when read out of context.+ */+ label: (item: T) => string;++ /**+ * The single move callback. Pointer drops and arrow presses both arrive+ * here, already normalized and no-op-suppressed. Return `false` to veto+ * the announcement; the consumer then owns whatever feedback replaces it.+ * Required for a standalone list; a grouped member omits it — the group's+ * own callback receives every member move instead.+ */+ onMove?: (move: ReorderableMove<T>) => void | false;++ /**+ * The API yielded by a surrounding `DReorderableListGroup`. Joining a+ * group makes cross-list moves between members possible and routes every+ * move through the group's callback. Requires `@listId`. Fixed at+ * construction: a list that must change groups is re-created, not+ * re-pointed. Every member carrying a `@listLabel` also becomes a+ * destination in the other members' move menus, which is how a cross-list+ * move is reachable without a pointer. The group's item type must match+ * `@items`, since the group's `@onMove` receives this list's moves.+ */+ group?: ReorderableGroupApi<NoInfer<T>>;++ /**+ * This member's identity inside its group. Required with `@group`, and+ * fixed at construction like the group itself.+ */+ listId?: string;++ /**+ * Translated name for this list, spoken in cross-list announcements when+ * an item lands here from another member, and shown as this list's+ * "Move to …" entry in every other member's move menu. Without it the+ * standard announcement is used and the list stays a pointer-only+ * destination.+ */+ listLabel?: string;++ /**+ * Whether a row refused at this list's own end carries on into the+ * adjacent group member instead. Requires `@group`; ignored without one.+ *+ * For members that read as one continuous run: moving down enters the next+ * member at the top and moving up enters the previous one at the bottom,+ * so the row keeps travelling the way it was pushed. The ends of the+ * outermost members still refuse and still announce it.+ *+ * **Setting this asserts that the group runs top to bottom in reading+ * order** — the only order the group can resolve. In a group laid out side+ * by side, Down would carry a row into the list beside it.+ *+ * Off by default, and not only for that reason: members that are genuinely+ * separate lists should stop at their own edges, with "Move to …" in the+ * menu as the deliberate way across.+ */+ spill?: boolean;++ /**+ * Rows failing this predicate are frozen: they render no controls, are+ * not drag sources, refuse drops, and keep their exact visible index in+ * every proposed order. Arrow moves hop over them. Defaults to every row+ * being movable.+ */+ movable?: (item: T) => boolean;++ /** Tag name for the list element. Defaults to `"ul"`. */+ tag?: string;++ /** Tag name for each row element. Defaults to `"li"`. */+ itemTag?: string;++ /** Optional ARIA role for the list element. */+ role?: string;++ /**+ * Optional ARIA role for each row element. Use roles that permit+ * interactive descendants (such as `row`): a role whose children are+ * presentational (`option`, `menuitem`, `tab`) flattens the rendered+ * controls out of the accessibility tree.+ */+ itemRole?: string;++ /**+ * Extra class(es) for the row element: a static string, or a function of+ * the item and its `{ index, movable }` state.+ */+ rowClass?: string | ((item: T, context: RowClassContext) => string);++ /**+ * Who places the row's handle. `"auto"` (the default) renders it ahead of+ * the row's block content; `"manual"` renders none and instead yields a+ * pre-wired `handle` component on the row API, for layouts where it must+ * occupy a specific cell, grid track, or position.+ *+ * There is deliberately no automatic "at the end": a handle is focusable,+ * so where it sits in the DOM is its position in the reading and focus+ * order, not decoration. A row that wants it last says so by placing it+ * last.+ */+ controls?: "auto" | "manual";++ /**+ * Read-only mode: rows render without controls and without any drag+ * wiring, as if every row were frozen.+ */+ disabled?: boolean;++ /**+ * Overrides the announcement for a committed move. Return the text to+ * announce, or `false` to suppress the announcement entirely. `onMove`+ * has already run either way.+ */+ announceMove?: (move: ReorderableMove<T>) => string | false;++ /**+ * Renders a create affordance after the rows: a text input and an add+ * button by default, or the `<:create>` block when one is given. The+ * default row is list-shaped (it renders as one extra item element), and+ * wraps its controls in a spanning cell when `@itemTag="tr"`. A table that+ * needs richer cell markup can supply its own `<:create>` block.+ */+ allowCreate?: boolean;++ /**+ * Reports that the reader asked to remove an item. Supplying it is what+ * renders the remove control: trailing the row's own content by default,+ * or wherever `controls.remove` is placed under `@controls="manual"`.+ *+ * The visible index comes with it, because an index-keyed list may hold+ * the same value twice and the item alone would not say which row went.+ *+ * The list announces the removal and puts focus somewhere sensible+ * afterwards; the handler's only job is to drop the item from its store.+ *+ * Return a promise to hold both back until the removal has actually+ * happened — what a confirmation in front of it needs, since the handler+ * is otherwise back long before the reader has answered. Either way the+ * list checks that an item really went before speaking, so a handler that+ * declines is not reported as a removal.+ */+ onRemove?: (item: T, index: number) => void | Promise<void>;++ /**+ * Whether an item may be removed, defaulting to all of them.+ *+ * Mirrors `@movable`, which renders no handle on a row that cannot move:+ * a row that cannot be removed renders no remove control either. A+ * permanently protected row would otherwise carry a dead tab stop that+ * announces itself as unavailable on every pass.+ */+ removable?: (item: T) => boolean;++ /**+ * The remove control's icon. One list-level argument rather than a+ * per-row one, because the control is placed by the list in every mode+ * except manual.+ */+ removeIcon?: string;++ /**+ * The remove control's button weight, defaulting to `btn-flat`. List-level+ * for the same reason as `removeIcon`: the control is placed by the list in+ * every mode except manual, where `controls.remove` takes its own+ * `@buttonClass` to override this.+ */+ removeButtonClass?: string;++ /**+ * Called with the trimmed value when the default create affordance is+ * submitted. Never called for an empty or whitespace-only value.+ */+ onCreate?: (value: string) => void;+ };+ Blocks: {+ /**+ * The contents of one row, rendered inside the row element the component+ * owns. Named rather than the implicit block because what it fills is not+ * obvious: a table shell yields `td`s into a `tr` the consumer never+ * writes, and `<:default>` gave no way to tell that from replacing the+ * row outright.+ */+ row: [item: T, row: ReorderableRowApi];++ /** Rendered inside the list element, before every row. */+ header: [];++ /**+ * Rendered before the header, for the visible sentence that teaches the+ * interaction ("Drag the handle, or press Enter for move options"). The+ * component never renders one of its own: a dense table wants no such+ * paragraph, and where it belongs on the page is the surface's call. The+ * screen-reader description on each handle is separate and always+ * present.+ */+ hint: [];++ /** Rendered in the rows' position when `@items` is empty. */+ empty: [];++ /**+ * Replaces the default create affordance when `@allowCreate` is set,+ * rendered after the rows.+ */+ create: [];+ };+ Element: HTMLElement;+}++/** Where a menu-driven move sends the row. */+export type MoveTarget = "up" | "down" | "top" | "bottom";diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.tsindex 3aea68e1a02..bd8a133d2e9 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.ts@@ -4,6 +4,7 @@ import { registerDestructor } from "@ember/destroyable";import { guidFor } from "@ember/object/internals";import type Owner from "@ember/owner";import Modifier, { type ArgsFor } from "ember-modifier";+import ItemScope from "discourse/ui-kit/-internals/cursor/item-scope";import { createRovingFocusApi } from "./d-roving-focus/api";import { apiStep } from "./d-roving-focus/api-navigation";import {@@ -11,7 +12,6 @@ import {normalizeConfig,} from "./d-roving-focus/config";import createRovingFocusDiagnostics from "./d-roving-focus/diagnostics";-import ItemScope from "./d-roving-focus/item-scope";import KeyboardRouter from "./d-roving-focus/keyboard";import ActiveDescendantStrategy from "./d-roving-focus/strategies/active-descendant";import RovingTabindexStrategy from "./d-roving-focus/strategies/roving-tabindex";@@ -25,7 +25,6 @@ import type {export type {DRovingFocusApi,DRovingFocusAxis,- DRovingFocusDisabledItems,DRovingFocusEntry,DRovingFocusStepResult,DRovingFocusStrategy,diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/api-navigation.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/api-navigation.tsindex 46fcd88291d..fea42dce9bd 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/api-navigation.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/api-navigation.ts@@ -1,6 +1,11 @@+import ItemScope from "discourse/ui-kit/-internals/cursor/item-scope";+import {+ scan,+ step,+ type StepOutcome,+ stepRow,+} from "discourse/ui-kit/-internals/cursor/navigation";import type { DRovingFocusConfig } from "./config";-import ItemScope from "./item-scope";-import { scan, step, type StepOutcome, stepRow } from "./navigation";import type { DRovingFocusAxis, DRovingFocusStepResult } from "./types";/** Operations and state needed to step the cursor from the public API. */diff --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 2795cdf4a2e..95a844e4d26 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@@ -1,10 +1,10 @@+import type { DisabledItems } from "discourse/ui-kit/-internals/cursor/item-scope";+import type { Orientation } from "discourse/ui-kit/-internals/cursor/navigation";import type {DRovingFocusArgs,- DRovingFocusDisabledItems,DRovingFocusEntry,DRovingFocusStrategy,DRovingFocusTabStopAnchor,- Orientation,} from "./types";/**@@ -31,7 +31,7 @@ export interface DRovingFocusConfig {controllerElement: HTMLElement | string | null | undefined;entryFocus: DRovingFocusEntry;fallbackSkipsMarked: boolean;- disabledItems: DRovingFocusDisabledItems;+ disabledItems: DisabledItems;onCrossAxis: DRovingFocusArgs["onCrossAxis"];typeAhead: boolean;}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/keyboard.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/keyboard.tsindex ebb46179432..9704c26ab5a 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/keyboard.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/keyboard.ts@@ -1,6 +1,11 @@+import type ItemScope from "discourse/ui-kit/-internals/cursor/item-scope";+import {+ scan,+ step,+ type StepOutcome,+ stepRow,+} from "discourse/ui-kit/-internals/cursor/navigation";import type { DRovingFocusConfig } from "./config";-import type ItemScope from "./item-scope";-import { scan, step, type StepOutcome, stepRow } from "./navigation";import TypeAhead from "./type-ahead";import type { DRovingFocusApi, DRovingFocusAxis } from "./types";diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/active-descendant.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/active-descendant.tsindex 9556b5d393a..3d6f425b6a5 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/active-descendant.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/active-descendant.ts@@ -1,7 +1,7 @@import { cancel, next as nextRunloop } from "@ember/runloop";+import ItemScope from "discourse/ui-kit/-internals/cursor/item-scope";import type { DRovingFocusConfig } from "../config";import { activeSeed } from "../entry-policy";-import ItemScope from "../item-scope";/** The state transition requested by active-descendant reconciliation. */export type ActiveReconcileResult =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 1316aad79a9..a39cf67d1c8 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,3 +1,4 @@+import ItemScope from "discourse/ui-kit/-internals/cursor/item-scope";import type { DRovingFocusConfig } from "../config";import {anchorsToSelection,@@ -6,7 +7,6 @@ import {isMarked,prefersSelected,} from "../entry-policy";-import ItemScope from "../item-scope";/** Maintains the single-tab-stop strategy and focus restoration state. */export default class RovingTabindexStrategy {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 87719ace275..5d669ad0dab 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@@ -1,3 +1,6 @@+import type { DisabledItems } from "discourse/ui-kit/-internals/cursor/item-scope";+import type { Orientation } from "discourse/ui-kit/-internals/cursor/navigation";+/*** Which of the practice page's two focus-management strategies the group uses:* a roving tabindex that moves DOM focus, or `aria-activedescendant` on a controller that keeps@@ -6,13 +9,6 @@*/export type DRovingFocusStrategy = "roving-tabindex" | "active-descendant";-/**- * Whether an `aria-disabled` item is a cursor target. Named for the two behaviours rather than- * spelled as a boolean, because the call site should say which one it wants.- */-export type DRovingFocusDisabledItems = "skip" | "focusable";-export type Orientation = "grid" | "horizontal" | "vertical";-/*** Controls for moving the cursor to a live item in the roving-focus group.*@@ -378,7 +374,7 @@ export interface DRovingFocusArgs {** Shape dictated by: Focusability of disabled controls.*/- disabledItems?: DRovingFocusDisabledItems;+ disabledItems?: DisabledItems;/*** Called for an arrow press on the axis this group does NOT navigate, so the keys a* single-axis composite leaves unused become available without every consumer re-derivingdiff --git a/frontend/discourse/tests/helpers/ui-kit/drag-and-drop-helper.ts b/frontend/discourse/tests/helpers/ui-kit/drag-and-drop-helper.tsindex c262c0762b4..819e7aca2eb 100644--- a/frontend/discourse/tests/helpers/ui-kit/drag-and-drop-helper.ts+++ b/frontend/discourse/tests/helpers/ui-kit/drag-and-drop-helper.ts@@ -242,10 +242,13 @@ export async function simulateDrag(assertDragRegistered(sourceSelector, targetSelector);const source = { ...centerOf(sourceSelector), ...sourceCoordinates };const target = { ...centerOf(targetSelector), ...targetCoordinates };+ // Resolved before the drop, because a consumer that applies a cross-list+ // move destroys the source row and `dragend` still belongs to that element.+ const registered = registeredElementFor(sourceSelector);await startDrag(sourceSelector, { dataTransfer, coordinates: source });await dragOver(targetSelector, { dataTransfer, coordinates: target });await dragEvent(targetSelector, "drop", { dataTransfer, ...target });- await dragEvent(registeredElementFor(sourceSelector), "dragend", {+ await dragEvent(registered, "dragend", {dataTransfer,...source,});@@ -259,7 +262,12 @@ export async function simulateDrag(* `draggable`, so a synthetic `dragstart` aimed anywhere else does nothing.*/function registeredElementFor(rowSelector: string) {- const row = document.querySelector(rowSelector) as Element;+ const row = document.querySelector(rowSelector);+ if (!row) {+ throw new Error(+ `drag-and-drop-helper: no element matches ${rowSelector}; resolve the drag source before the drop removes it`+ );+ }if (row.matches('[draggable="true"]')) {return row;}@@ -267,7 +275,7 @@ function registeredElementFor(rowSelector: string) {}/**- * Drives a browser-started drag from page content no source registered.+ * Drives a browser-started drag from page content with no source registered.** The event sequence matches an element drag. The guards prove the source is* unsourced and the destination is an element target, so this cannot quietly@@ -312,6 +320,59 @@ export async function simulateUnsourcedDrag(await dragEvent(sourceSelector, "dragend", { dataTransfer, ...source });}+/**+ * Drives a registered drag and releases it over an element that is NOT a drop+ * target, the mirror of {@link simulateUnsourcedDrag}.+ *+ * The event sequence is {@link simulateDrag}'s, whose guard refuses this case+ * outright. A caller here is asserting a refusal, and a refusal looks exactly+ * like a drag that never reached anything. So the guards run the other way+ * round: the source must be registered and the destination must not be. A+ * destination that quietly becomes a drop target then fails here, rather than+ * passing as the no-op the test was trying to prove.+ *+ * @param sourceSelector - CSS selector for the registered element to drag.+ * @param targetSelector - CSS selector for the non-target to release over.+ * @param options - The shared payload and any coordinate overrides.+ */+export async function simulateUntargetedDrag(+ sourceSelector: string,+ targetSelector: string,+ {+ dataTransfer,+ sourceCoordinates,+ targetCoordinates,+ }: {+ dataTransfer: DataTransfer;+ sourceCoordinates?: Partial<ClientPoint>;+ targetCoordinates?: Partial<ClientPoint>;+ }+) {+ const sourceElement = document.querySelector(sourceSelector);+ if (!sourceElement?.hasAttribute("data-drag-source")) {+ throw new Error(+ `${sourceSelector} is not a registered drag source, so this drag would prove nothing about the destination`+ );+ }++ const targetElement = document.querySelector(targetSelector);+ if (targetElement?.hasAttribute("data-drop-target")) {+ throw new Error(+ `${targetSelector} IS a registered drop target, so this would exercise the ordinary drop path — use simulateDrag`+ );+ }++ const source = { ...centerOf(sourceSelector), ...sourceCoordinates };+ const target = { ...centerOf(targetSelector), ...targetCoordinates };+ await startDrag(sourceSelector, { dataTransfer, coordinates: source });+ await dragOver(targetSelector, { dataTransfer, coordinates: target });+ await dragEvent(targetSelector, "drop", { dataTransfer, ...target });+ await dragEvent(registeredElementFor(sourceSelector), "dragend", {+ dataTransfer,+ ...source,+ });+}+/*** Brings an external drag over a target and leaves it hovering there, without* dropping.diff --git a/frontend/discourse/tests/helpers/ui-kit/reorderable-list-fixtures.gjs b/frontend/discourse/tests/helpers/ui-kit/reorderable-list-fixtures.gjsnew file mode 100644index 00000000000..bec0432d18d--- /dev/null+++ b/frontend/discourse/tests/helpers/ui-kit/reorderable-list-fixtures.gjs@@ -0,0 +1,99 @@+import { find, findAll } from "@ember/test-helpers";+import DMenus from "discourse/float-kit/components/d-menus";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";++/**+ * Shared fixtures for the `DReorderableList` suites.+ *+ * The suite is split across several files by concern, and they describe the+ * same list, so the rows, the shell and the drag assertions live here rather+ * than once per file.+ */++export const noop = () => {};+export const INDEX_KEY = "@index";+export const label = (item) => item.name ?? String(item);++/** Two movable rows above two that are frozen, as a grouped catalogue renders. */+export function mixedItems() {+ return [+ { id: "alpha", name: "Alpha" },+ { id: "bravo", name: "Bravo" },+ { id: "charlie", name: "Charlie" },+ { id: "delta", name: "Delta" },+ ];+}++export const isMovable = (item) => item.id === "alpha" || item.id === "bravo";++export function objectItems() {+ return [+ { id: "alpha", identity: { value: "alpha-key" }, name: "Alpha" },+ { id: "bravo", identity: { value: "bravo-key" }, name: "Bravo" },+ { id: "charlie", identity: { value: "charlie-key" }, name: "Charlie" },+ ];+}++/**+ * The plain list most tests exercise: object rows keyed by id, one span each.+ *+ * Only the collection and the move handler vary, so a test that cares about+ * neither the markup nor the arguments says so by using this instead of+ * repeating the shell.+ */+export const List = <template>+ <DMenus />+ <DReorderableList+ @items={{@items}}+ @key="id"+ @label={{label}}+ @onMove={{@onMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+</template>;++export const MENU_SELECTOR =+ '[data-identifier="reorderable-list-move"] .dropdown-menu';++export function renderedItemOrder(root = "") {+ const prefix = root ? `${root} ` : "";+ return findAll(`${prefix}[data-test-item]`).map(+ (element) => element.dataset.testItem+ );+}++export function dropCoordinates(targetSelector, position) {+ const rect = find(targetSelector).getBoundingClientRect();+ const fraction = position === "before" ? 0.25 : 0.75;+ return {+ clientX: rect.left + rect.width / 2,+ clientY: rect.top + rect.height * fraction,+ };+}++export function assertDragReady(assert, source, target) {+ assert+ .dom(source)+ .hasAttribute(+ "data-drag-source",+ "",+ "the row is the registered drag source, so it is what a drop receives and what the preview photographs"+ );+ assert+ .dom(`${source} .d-reorderable-list__handle`)+ .hasAttribute(+ "draggable",+ "true",+ "and the handle is where the drag may begin"+ );+ assert+ .dom(target)+ .hasAttribute(+ "data-drop-target",+ "",+ "the destination row is registered for drops"+ );+}diff --git a/frontend/discourse/tests/helpers/ui-kit/reorderable-list-helper.js b/frontend/discourse/tests/helpers/ui-kit/reorderable-list-helper.jsnew file mode 100644index 00000000000..b352b53e41f--- /dev/null+++ b/frontend/discourse/tests/helpers/ui-kit/reorderable-list-helper.js@@ -0,0 +1,74 @@+import { click, find, triggerKeyEvent } from "@ember/test-helpers";++/**+ * Test helpers for driving a `DReorderableList`.+ *+ * A move is two interactions rather than one — open the row's menu, choose a+ * destination — so every surface that tests reordering would otherwise repeat+ * the same pair. Naming the destination also keeps a test readable when a+ * group adds cross-list entries and the menu's positions shift.+ */++/** One row: what a move commits against. */+export function rowSelector(key, root = "") {+ const prefix = root ? `${root} ` : "";+ return `${prefix}[data-reorderable-key="${key}"]`;+}++/** The handle inside one row: its drag source and its pointer menu trigger. */+export function handleSelector(key, root = "") {+ return `${rowSelector(key, root)} .d-reorderable-list__handle`;+}++/**+ * One destination inside an open move menu.+ *+ * @param target - `"top"`, `"up"`, `"down"`, `"bottom"`, or `"list"`.+ */+export function moveItemSelector(target) {+ return `.d-reorderable-list__move-item.--${target}`;+}++/** Opens one row's move menu and leaves it open for inspection. */+export async function openMoveMenu(key, root = "") {+ await click(handleSelector(key, root));+}++/**+ * Moves a row the way a pointer user does. The menu closes itself, so this+ * leaves nothing open behind it.+ *+ * @param key - The row's reorderable key.+ * @param target - The destination to choose.+ * @param root - Optional scope, for a page holding several lists.+ */+export async function moveVia(key, target, root = "") {+ await openMoveMenu(key, root);+ await click(moveItemSelector(target));+}++/** The keyboard accelerator for each destination. */+const CHORD_KEYS = {+ up: "ArrowUp",+ down: "ArrowDown",+ top: "Home",+ bottom: "End",+};++/**+ * Moves a row the way the keyboard accelerator does: Alt with an arrow or+ * Home/End on the row's focused handle.+ *+ * @param key - The row's reorderable key.+ * @param target - The destination to move to.+ * @param root - Optional scope, for a page holding several lists.+ */+export async function moveViaChord(key, target, root = "") {+ // The chord is refused anywhere but the handle, so a caret shortcut inside a+ // row's own field stays its own.+ const handle = find(handleSelector(key, root));+ handle.focus();+ await triggerKeyEvent(handle, "keydown", CHORD_KEYS[target], {+ altKey: true,+ });+}diff --git a/frontend/discourse/tests/integration/ui-kit/d-drag-handle-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-drag-handle-test.gjsnew file mode 100644index 00000000000..3aa7c4bf8fd--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/d-drag-handle-test.gjs@@ -0,0 +1,49 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import DDragHandle from "discourse/ui-kit/d-drag-handle";++module("Integration | ui-kit | DDragHandle", function (hooks) {+ setupRenderingTest(hooks);++ test("is hidden from assistive technology and out of the tab order", async function (assert) {+ await render(<template><DDragHandle @label="Reorder Topics" /></template>);++ // The point of the component: a drag cannot be performed by keyboard, so+ // exposing the handle would offer a control that cannot be operated. The+ // keyboard path is a separate, operable control beside it.+ assert+ .dom(".d-drag-handle")+ .hasAttribute("aria-hidden", "true", "it is hidden from the a11y tree")+ .hasAttribute("tabindex", "-1", "and it is not a tab stop")+ .hasAttribute(+ "title",+ "Reorder Topics",+ "the label names what it drags for a sighted pointer user"+ );+ });++ test("passes attributes through so a consumer can register it with a source", async function (assert) {+ await render(+ <template>+ <DDragHandle+ class="my-row__handle"+ data-link-name="Topics"+ @label="Reorder Topics"+ />+ </template>+ );++ assert+ .dom(".d-drag-handle")+ .hasClass(+ "my-row__handle",+ "a consumer class lands alongside the component's own"+ )+ .hasAttribute(+ "data-link-name",+ "Topics",+ "and arbitrary attributes reach the element"+ );+ });+});diff --git a/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-group-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-group-test.gjsnew file mode 100644index 00000000000..63d53fdb683--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-group-test.gjs@@ -0,0 +1,2330 @@+import { tracked } from "@glimmer/tracking";+import { trackedArray } from "@ember/reactive/collections";+import {+ click,+ find,+ render,+ resetOnerror,+ settled,+ setupOnerror,+ triggerKeyEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import DMenus from "discourse/float-kit/components/d-menus";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import {+ centerOf,+ dragEvent,+ simulateDrag,+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";+import {+ assertDragReady,+ dropCoordinates,+ INDEX_KEY,+ label,+ noop,+ objectItems,+ renderedItemOrder,+} from "discourse/tests/helpers/ui-kit/reorderable-list-fixtures";+import {+ handleSelector,+ moveItemSelector,+ moveVia,+ moveViaChord,+ openMoveMenu,+ rowSelector,+} from "discourse/tests/helpers/ui-kit/reorderable-list-helper";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import DReorderableListGroup from "discourse/ui-kit/d-reorderable-list-group";++module("Integration | ui-kit | DReorderableList | group", function (hooks) {+ setupRenderingTest(hooks);++ test("DReorderableListGroup renders no wrapper around its block", async function (assert) {+ await render(+ <template>+ <DMenus />+ <div id="group-placement">+ <span data-placement="before">Before</span>+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <span+ data-group-context={{if group "present" "missing"}}+ data-placement="first"+ >First</span>+ <span data-placement="last">Last</span>+ </DReorderableListGroup>+ <span data-placement="after">After</span>+ </div>+ </template>+ );++ assert.deepEqual(+ Array.from(find("#group-placement").children).map(+ (element) => element.dataset.placement+ ),+ ["before", "first", "last", "after"],+ "the group inserts no element between its parent and block content"+ );+ });++ test("a group onMove false return vetoes the announcement", async function (assert) {+ const items = trackedArray(objectItems());+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const moves = [];+ // The group's callback wins over any member's own, so this is the veto the+ // member never sees.+ const groupMove = (move) => {+ moves.push(move);+ return false;+ };++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{groupMove}} as |group|>+ <DReorderableList+ @group={{group}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @listId="primary"+ @listLabel="Primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveVia("alpha", "down");++ assert.strictEqual(moves.length, 1, "the group callback still receives it");+ assert.strictEqual(+ announce.callCount,+ 0,+ "a move the group vetoed is not announced"+ );+ });++ test("DReorderableList requires listId when it joins a group", async function (assert) {+ const items = objectItems().slice(0, 1);+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <DReorderableList+ @group={{group}}+ @items={{items}}+ @key="id"+ @label={{label}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );+ } finally {+ resetOnerror();+ }++ assert.true(+ /Assertion Failed:.*(list.?id|required|group)/i.test(+ raised?.message ?? ""+ ),+ "a grouped member without listId triggers a development assertion"+ );+ });++ test("a member re-registering during a re-render keeps its place in the group", async function (assert) {+ const outer = objectItems().slice(0, 1);+ const inner = objectItems().slice(0, 2);+ const state = new (class {+ @tracked frozen = false;+ })();+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ {{! The member sits inside another list's row, which is what makes+ this reachable: freezing the outer list swaps its row branch, so+ the replacement member is constructed before the old one is torn+ down and both briefly claim the same listId. }}+ <DReorderableList+ @disabled={{state.frozen}}+ @items={{outer}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |section|>+ <DReorderableList+ @group={{group}}+ @items={{inner}}+ @key="id"+ @label={{label}}+ @listId={{section.id}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ state.frozen = true;+ await settled();+ state.frozen = false;+ await settled();+ } finally {+ resetOnerror();+ }++ assert.strictEqual(+ raised,+ undefined,+ "re-registering the same listId is churn, not a duplicate, so it raises nothing"+ );+ assert+ .dom("[data-test-item]")+ .exists(+ { count: 2 },+ "and the member is still rendering its rows afterwards"+ );+ });++ test("DReorderableList routes an in-list menu move through the group", async function (assert) {+ const primaryItems = objectItems();+ const secondaryItems = [{ id: "secondary-alpha", name: "Secondary Alpha" }];+ const movedItem = primaryItems[1];+ const fromIndex = primaryItems.indexOf(movedItem);+ const toIndex = fromIndex - 1;+ const proposed = [...primaryItems];+ proposed.splice(fromIndex, 1);+ proposed.splice(toIndex, 0, movedItem);+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ id="button-primary-list"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ @listLabel="Primary links"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="button-secondary-list"+ @group={{group}}+ @items={{secondaryItems}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveVia(movedItem.id, "up", "#button-primary-list");+ } finally {+ resetOnerror();+ }++ assert.strictEqual(+ raised,+ undefined,+ "the grouped menu move raises no error"+ );++ assert.strictEqual(+ onMove.callCount,+ 1,+ "one member menu move calls the group callback exactly once"+ );+ assert.deepEqual(+ onMove.firstCall.args[0],+ {+ method: "menu",+ item: movedItem,+ fromList: "primary",+ toList: "primary",+ fromIndex,+ toIndex,+ fromItems: primaryItems,+ toItems: primaryItems,+ proposedFromItems: proposed,+ proposedToItems: proposed,+ },+ "the grouped menu path keeps the standalone payload shape with member IDs"+ );+ assert.strictEqual(+ onMove.firstCall.args[0].fromItems,+ primaryItems,+ "the button payload carries the live member items reference"+ );+ assert.strictEqual(+ onMove.firstCall.args[0].proposedFromItems,+ onMove.firstCall.args[0].proposedToItems,+ "an in-list grouped button move shares one proposed array"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the grouped button move announces exactly once"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ `Moved ${label(movedItem)} to position ${toIndex + 1} of ${proposed.length}`,+ "an in-list grouped button move uses the standard announcement"+ );+ });++ test("DReorderableList routes an in-list drag move through the group", async function (assert) {+ const primaryItems = objectItems();+ const secondaryItems = [{ id: "secondary-alpha", name: "Secondary Alpha" }];+ const movedItem = primaryItems[2];+ const targetItem = primaryItems[0];+ const fromIndex = primaryItems.indexOf(movedItem);+ const targetIndex = primaryItems.indexOf(targetItem);+ const toIndex = targetIndex + 1;+ const proposed = [...primaryItems];+ proposed.splice(fromIndex, 1);+ proposed.splice(toIndex, 0, movedItem);+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ id="drag-primary-list"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="drag-secondary-list"+ @group={{group}}+ @items={{secondaryItems}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const source = rowSelector(movedItem.id, "#drag-primary-list");+ const target = rowSelector(targetItem.id, "#drag-primary-list");+ assertDragReady(assert, source, target);+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "after"),+ });+ } finally {+ resetOnerror();+ }++ assert.strictEqual(+ raised,+ undefined,+ "the grouped drag move raises no error"+ );++ assert.strictEqual(+ onMove.callCount,+ 1,+ "one member drag calls the group callback exactly once"+ );+ assert.deepEqual(+ onMove.firstCall.args[0],+ {+ method: "drag",+ item: movedItem,+ fromList: "primary",+ toList: "primary",+ fromIndex,+ toIndex,+ fromItems: primaryItems,+ toItems: primaryItems,+ proposedFromItems: proposed,+ proposedToItems: proposed,+ },+ "the grouped drag path keeps the standalone payload shape with member IDs"+ );+ assert.strictEqual(+ onMove.firstCall.args[0].fromItems,+ primaryItems,+ "the drag payload carries the live member items reference"+ );+ assert.strictEqual(+ onMove.firstCall.args[0].proposedFromItems,+ onMove.firstCall.args[0].proposedToItems,+ "an in-list grouped drag shares one proposed array"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the grouped in-list drag announces exactly once"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ `Moved ${label(movedItem)} to position ${toIndex + 1} of ${proposed.length}`,+ "an in-list grouped drag uses the standard announcement"+ );+ });++ test("DReorderableList commits a cross-list drag with frozen source slots", async function (assert) {+ const primaryItems = [+ { id: "primary-alpha", name: "Primary Alpha" },+ { id: "primary-fixed", name: "Primary Fixed" },+ { id: "primary-charlie", name: "Primary Charlie" },+ ];+ const secondaryItems = [+ { id: "secondary-alpha", name: "Secondary Alpha" },+ { id: "secondary-bravo", name: "Secondary Bravo" },+ ];+ const movedItem = primaryItems[0];+ const frozenItem = primaryItems[1];+ const targetItem = secondaryItems[0];+ const movable = (item) => item !== frozenItem;+ const proposedFromItems = [primaryItems[2], frozenItem];+ const proposedToItems = [secondaryItems[0], movedItem, secondaryItems[1]];+ const fromIndex = primaryItems.indexOf(movedItem);+ const toIndex = secondaryItems.indexOf(targetItem) + 1;+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ id="cross-primary-list"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ @listLabel="Primary links"+ @movable={{movable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="cross-secondary-list"+ @group={{group}}+ @items={{secondaryItems}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ @listLabel="Secondary links"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const source = rowSelector(movedItem.id, "#cross-primary-list");+ const target = rowSelector(targetItem.id, "#cross-secondary-list");+ assertDragReady(assert, source, target);+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "after"),+ });++ assert.strictEqual(+ onMove.callCount,+ 1,+ "one cross-list drop calls the group callback exactly once"+ );+ assert.deepEqual(+ onMove.firstCall.args[0],+ {+ method: "drag",+ item: movedItem,+ fromList: "primary",+ toList: "secondary",+ fromIndex,+ toIndex,+ fromItems: primaryItems,+ toItems: secondaryItems,+ proposedFromItems,+ proposedToItems,+ },+ "the cross-list drop reports both lists and their independent proposals"+ );+ assert.strictEqual(+ onMove.firstCall.args[0].fromItems,+ primaryItems,+ "fromItems is the live source array reference"+ );+ assert.strictEqual(+ onMove.firstCall.args[0].toItems,+ secondaryItems,+ "toItems is the live destination array reference"+ );+ assert.deepEqual(+ onMove.firstCall.args[0].proposedFromItems,+ proposedFromItems,+ "removal refills movable source slots while the frozen row keeps index one"+ );+ assert.deepEqual(+ onMove.firstCall.args[0].proposedToItems,+ proposedToItems,+ "an after drop inserts after the destination row without same-list correction"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the cross-list move announces exactly once"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ `Moved ${label(movedItem)} to Secondary links, position ${toIndex + 1} of ${proposedToItems.length}`,+ "the cross-list announcement names the labelled destination list"+ );+ });++ test("DReorderableList keeps step boundaries within each group member", async function (assert) {+ const primaryItems = [{ id: "primary-alpha", name: "Primary Alpha" }];+ const secondaryItems = [+ { id: "secondary-alpha", name: "Secondary Alpha" },+ { id: "secondary-bravo", name: "Secondary Bravo" },+ ];+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ id="boundary-primary-list"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="boundary-secondary-list"+ @group={{group}}+ @items={{secondaryItems}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await openMoveMenu(secondaryItems[0].id, "#boundary-secondary-list");+ assert+ .dom(moveItemSelector("up"))+ .doesNotExist(+ "the first row of the second member cannot step into the preceding member"+ );++ // A member's boundary is spoken by the accelerator, the one path that still+ // reaches it now the destination declines the press itself.+ await moveViaChord(secondaryItems[0].id, "up", "#boundary-secondary-list");++ assert.strictEqual(+ onMove.callCount,+ 0,+ "a refused local boundary move commits nothing to the group"+ );+ assert.true(+ announce.calledOnceWith("Secondary Alpha is already first"),+ "and the reader is told they reached the member's boundary"+ );+ });++ test("DReorderableList accepts a cross-list drop on an empty member root", async function (assert) {+ const primaryItems = [{ id: "primary-alpha", name: "Primary Alpha" }];+ const emptyItems = [];+ const movedItem = primaryItems[0];+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ id="empty-source-list"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="empty-target-list"+ @group={{group}}+ @items={{emptyItems}}+ @key="id"+ @label={{label}}+ @listId="empty"+ @listLabel="Empty links"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const source = rowSelector(movedItem.id, "#empty-source-list");+ const target = "#empty-target-list";+ assert+ .dom(target)+ .hasClass(+ "d-reorderable-list",+ "the empty destination keeps the standard list root"+ )+ .hasAttribute(+ "data-drop-target",+ "",+ "an empty grouped member registers its root as a drop target"+ );+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ });++ assert.strictEqual(+ onMove.callCount,+ 1,+ "dropping on the empty root calls the group callback once"+ );+ assert.deepEqual(+ onMove.firstCall.args[0],+ {+ method: "drag",+ item: movedItem,+ fromList: "primary",+ toList: "empty",+ fromIndex: 0,+ toIndex: 0,+ fromItems: primaryItems,+ toItems: emptyItems,+ proposedFromItems: [],+ proposedToItems: [movedItem],+ },+ "the empty-root drop removes the source and inserts at destination index zero"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the empty-root drop announces exactly once"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ `Moved ${label(movedItem)} to Empty links, position 1 of 1`,+ "the empty destination announcement measures its proposed one-item list"+ );+ });++ test("DReorderableList keeps non-empty member roots out of drop targeting", async function (assert) {+ const primaryItems = [{ id: "primary-alpha", name: "Primary Alpha" }];+ const secondaryItems = [{ id: "secondary-alpha", name: "Secondary Alpha" }];++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <DReorderableList+ id="non-empty-primary-list"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="non-empty-secondary-list"+ @group={{group}}+ @items={{secondaryItems}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ for (const root of [+ "#non-empty-primary-list",+ "#non-empty-secondary-list",+ ]) {+ assert+ .dom(root)+ .doesNotHaveAttribute(+ "data-drop-target",+ `${root} does not register its non-empty root for drops`+ );+ assert+ .dom(`${root} > .d-reorderable-list__row`)+ .hasAttribute(+ "data-drop-target",+ "",+ `${root} continues to accept drops on its row`+ );+ }+ });++ test("DReorderableList uses the standard cross-list announcement without a destination label", async function (assert) {+ const primaryItems = [{ id: "primary-alpha", name: "Primary Alpha" }];+ const secondaryItems = [{ id: "secondary-alpha", name: "Secondary Alpha" }];+ const movedItem = primaryItems[0];+ const targetItem = secondaryItems[0];+ const proposedToItems = [movedItem, targetItem];+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ id="unlabelled-primary-list"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ @listLabel="Primary links"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="unlabelled-secondary-list"+ @group={{group}}+ @items={{secondaryItems}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const source = rowSelector(movedItem.id, "#unlabelled-primary-list");+ const target = rowSelector(targetItem.id, "#unlabelled-secondary-list");+ assertDragReady(assert, source, target);+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "before"),+ });++ assert.strictEqual(+ onMove.callCount,+ 1,+ "the unlabelled destination still commits one cross-list move"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the unlabelled destination still announces exactly once"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ `Moved ${label(movedItem)} to position 1 of ${proposedToItems.length}`,+ "the fallback announcement omits a destination list name"+ );+ });++ test("DReorderableList isolates grouped and standalone drag surfaces", async function (assert) {+ const groupedItems = [+ { id: "grouped-alpha", name: "Grouped Alpha" },+ { id: "grouped-bravo", name: "Grouped Bravo" },+ ];+ const standaloneItems = [+ { id: "standalone-alpha", name: "Standalone Alpha" },+ { id: "standalone-bravo", name: "Standalone Bravo" },+ ];+ const groupOnMove = sinon.spy();+ const standaloneOnMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{groupOnMove}} as |group|>+ <DReorderableList+ id="isolated-grouped-list"+ @group={{group}}+ @items={{groupedItems}}+ @key="id"+ @label={{label}}+ @listId="grouped"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ <DReorderableList+ id="isolated-standalone-list"+ @items={{standaloneItems}}+ @key="id"+ @label={{label}}+ @onMove={{standaloneOnMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ const groupedSource = rowSelector(+ groupedItems[0].id,+ "#isolated-grouped-list"+ );+ const groupedTarget = rowSelector(+ groupedItems[1].id,+ "#isolated-grouped-list"+ );+ const standaloneSource = rowSelector(+ standaloneItems[0].id,+ "#isolated-standalone-list"+ );+ const standaloneTarget = rowSelector(+ standaloneItems[1].id,+ "#isolated-standalone-list"+ );++ await simulateDrag(groupedSource, standaloneTarget, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(standaloneTarget, "before"),+ });++ await simulateDrag(standaloneSource, groupedTarget, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(groupedTarget, "before"),+ });++ assert.strictEqual(+ groupOnMove.callCount,+ 0,+ "the group rejects the standalone drag"+ );+ assert.strictEqual(+ standaloneOnMove.callCount,+ 0,+ "the standalone list rejects the grouped drag"+ );+ assert.strictEqual(+ announce.callCount,+ 0,+ "rejected drags across the isolation boundary are silent"+ );+ });++ test("a list torn down with its menu open leaves nothing registered", async function (assert) {+ // The menu's content is rendered by the app-root host and its lifecycle is+ // the service's, so neither ends when the list does. Without the list+ // cascading destruction into the coordinator, the instance stays in the+ // service's registry for the life of the app, holding the trigger element+ // and, through the menu data, the list itself.+ const items = objectItems();+ const state = new (class {+ @tracked showList = true;+ })();+ const menu = this.owner.lookup("service:menu");++ await render(+ <template>+ <DMenus />+ {{#if state.showList}}+ <DReorderableList+ id="teardown-menu-list"+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ {{/if}}+ </template>+ );++ await openMoveMenu("alpha", "#teardown-menu-list");+ assert.dom(".d-reorderable-list__move-item").exists("the menu is open");+ assert.strictEqual(+ menu.registeredMenus.size,+ 1,+ "and the service is holding it"+ );++ state.showList = false;+ await settled();++ assert+ .dom("#teardown-menu-list")+ .doesNotExist("the list is fully unrendered with its menu still open");+ assert+ .dom(".d-reorderable-list__move-item")+ .doesNotExist("no menu content outlives the list that opened it");+ assert.strictEqual(+ menu.registeredMenus.size,+ 0,+ "and nothing is left registered with the service"+ );+ });++ test("DReorderableList refuses a drop after the source member is torn down", async function (assert) {+ const primaryItems = [{ id: "primary-alpha", name: "Primary Alpha" }];+ const secondaryItems = [{ id: "secondary-alpha", name: "Secondary Alpha" }];+ const state = new (class {+ @tracked showPrimary = true;+ })();+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ {{#if state.showPrimary}}+ <DReorderableList+ id="teardown-primary-list"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ {{/if}}+ <DReorderableList+ id="teardown-secondary-list"+ @group={{group}}+ @items={{secondaryItems}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const source = rowSelector(primaryItems[0].id, "#teardown-primary-list");+ const sourceHandle = `${source} .d-reorderable-list__handle`;+ const target = rowSelector(+ secondaryItems[0].id,+ "#teardown-secondary-list"+ );+ const dataTransfer = new DataTransfer();+ assert.dom(source).hasAttribute("data-drag-source", "");+ assert.dom(target).hasAttribute("data-drop-target", "");+ await dragEvent(sourceHandle, "dragstart", {+ dataTransfer,+ ...centerOf(sourceHandle),+ });++ state.showPrimary = false;+ await settled();++ assert+ .dom("#teardown-primary-list")+ .doesNotExist("the source member is fully unrendered mid-drag");+ const targetCoordinates = dropCoordinates(target, "before");+ await dragEvent(target, "dragenter", {+ dataTransfer,+ ...targetCoordinates,+ });+ await dragEvent(target, "dragover", {+ dataTransfer,+ ...targetCoordinates,+ });+ await dragEvent(target, "drop", {+ dataTransfer,+ ...targetCoordinates,+ });++ assert.strictEqual(+ onMove.callCount,+ 0,+ "the group refuses a drop whose source membership is gone"+ );+ assert.strictEqual(+ announce.callCount,+ 0,+ "the refused teardown drop makes no announcement"+ );+ });++ test("DReorderableList rejects duplicate group listId registrations", async function (assert) {+ const primaryItems = [{ id: "primary-alpha", name: "Primary Alpha" }];+ const secondaryItems = [{ id: "secondary-alpha", name: "Secondary Alpha" }];+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <DReorderableList+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="duplicate"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ @group={{group}}+ @items={{secondaryItems}}+ @key="id"+ @label={{label}}+ @listId="duplicate"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );+ } finally {+ resetOnerror();+ }++ assert.true(+ /Assertion Failed:.*(duplicate|list.?id|unique)/i.test(+ raised?.message ?? ""+ ),+ "duplicate listId registration triggers a development assertion"+ );+ });++ test("a member's list label is read live rather than captured at registration", async function (assert) {+ const primary = trackedArray(objectItems());+ const secondary = trackedArray([+ { id: "secondary-alpha", name: "Secondary Alpha" },+ ]);+ const state = new (class {+ @tracked secondaryLabel = "Secondary";+ })();++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <DReorderableList+ @group={{group}}+ @items={{primary}}+ @key="id"+ @label={{label}}+ @listId="primary"+ @listLabel="Primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ @group={{group}}+ @items={{secondary}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ @listLabel={{state.secondaryLabel}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ state.secondaryLabel = "Renamed";+ await settled();++ await openMoveMenu("alpha");++ assert+ .dom(moveItemSelector("list"))+ .hasText(+ "Move to Renamed",+ "a destination is named by what the list is called now, not by what it was called when it registered"+ );+ });++ /**+ * Two members that read as one run, which is the arrangement `@spill` is+ * for. The applier is the same shape a real consumer writes: the component+ * proposes an order and the store is the consumer's to update.+ */+ function spillFixture() {+ const first = trackedArray([+ { id: "alpha", name: "Alpha" },+ { id: "bravo", name: "Bravo" },+ ]);+ const second = trackedArray([{ id: "charlie", name: "Charlie" }]);+ const moves = [];+ const applyMove = (move) => {+ moves.push(move);+ const listFor = (id) => (id === "first" ? first : second);+ const from = listFor(move.fromList);+ from.splice(0, from.length, ...move.proposedFromItems);+ if (move.toList !== move.fromList) {+ const to = listFor(move.toList);+ to.splice(0, to.length, ...move.proposedToItems);+ }+ };+ return { first, second, moves, applyMove };+ }++ test("a spilling list carries a row past its own end into the next member", async function (assert) {+ const { first, second, moves, applyMove } = spillFixture();++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ class="spill-first"+ @group={{group}}+ @items={{first}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="First"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="spill-second"+ @group={{group}}+ @items={{second}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Second"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveViaChord("bravo", "down", ".spill-first");++ assert.deepEqual(+ renderedItemOrder(".spill-first"),+ ["alpha"],+ "the row left the list it had run out of room in"+ );+ assert.deepEqual(+ renderedItemOrder(".spill-second"),+ ["bravo", "charlie"],+ "and entered the next one at the top, still travelling downwards"+ );+ assert.strictEqual(+ moves.at(-1).method,+ "keyboard",+ "the consumer is told what the reader actually did, not that a menu was used"+ );+ assert+ .dom(handleSelector("bravo", ".spill-second"))+ .isFocused("focus follows the row across, so a second press is possible");+ });++ test("a spilling list carries a row backwards onto the previous member's tail", async function (assert) {+ const { first, second, applyMove } = spillFixture();++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ class="spill-first"+ @group={{group}}+ @items={{first}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="First"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="spill-second"+ @group={{group}}+ @items={{second}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Second"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveViaChord("charlie", "up", ".spill-second");++ assert.deepEqual(+ renderedItemOrder(".spill-first"),+ ["alpha", "bravo", "charlie"],+ "entering from below lands last, so the row keeps travelling upwards"+ );+ assert.deepEqual(+ renderedItemOrder(".spill-second"),+ [],+ "and the member it left is empty"+ );+ });++ test("the outermost end still refuses even when the list spills", async function (assert) {+ const { first, second, moves, applyMove } = spillFixture();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ class="spill-first"+ @group={{group}}+ @items={{first}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="First"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="spill-second"+ @group={{group}}+ @items={{second}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Second"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveViaChord("charlie", "down", ".spill-second");++ assert.strictEqual(moves.length, 0, "there is nowhere further to go");+ assert.strictEqual(+ announce.lastCall.args[0],+ "Charlie is already last",+ "and reaching the end of the whole run is still spoken"+ );+ });++ test("without spill a member's boundary refuses as it always did", async function (assert) {+ const { first, second, moves, applyMove } = spillFixture();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ class="spill-first"+ @group={{group}}+ @items={{first}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="First"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="spill-second"+ @group={{group}}+ @items={{second}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Second"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveViaChord("bravo", "down", ".spill-first");++ assert.strictEqual(moves.length, 0, "a member keeps to its own edges");+ assert.strictEqual(+ announce.lastCall.args[0],+ "Bravo is already last",+ "and says so"+ );+ assert.deepEqual(renderedItemOrder(".spill-second"), ["charlie"]);+ });++ test("a spillable row is offered the step in its menu", async function (assert) {+ const { first, second, applyMove } = spillFixture();++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ class="spill-first"+ @group={{group}}+ @items={{first}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="First"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="spill-second"+ @group={{group}}+ @items={{second}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Second"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await openMoveMenu("bravo", ".spill-first");++ assert+ .dom(moveItemSelector("down"))+ .exists(+ "the last row of a spilling member can still step down, so the menu says so"+ );+ assert+ .dom(moveItemSelector("bottom"))+ .doesNotExist("but the end of this list is somewhere it already is");+ });+});+module("Integration | ui-kit | DReorderableList | nested", function (hooks) {+ setupRenderingTest(hooks);++ const INNER = ".nested-inner";++ /**+ * An outer list whose first row hosts a list of its own, which is the shape+ * any tree of reorderable things takes: sections holding rows, groups holding+ * members. Only the first outer row nests one, so a selector naming an inner+ * key can never also name an outer one.+ */+ function nestedItems() {+ return trackedArray([+ {+ id: "outer-a",+ name: "Outer A",+ children: trackedArray([+ { id: "one", name: "One" },+ { id: "two", name: "Two" },+ ]),+ },+ { id: "outer-b", name: "Outer B", children: null },+ ]);+ }++ test("an accelerator on a nested handle moves the nested row, not the outer one", async function (assert) {+ const outer = nestedItems();+ const inner = outer[0].children;+ const outerMove = sinon.spy();+ // A real handler, not a spy: the component never mutates `@items`, so a+ // spy alone would leave the rendered order unchanged whether the move+ // reached the right list or no list at all.+ const innerMove = sinon.spy(({ proposedFromItems }) =>+ inner.splice(0, inner.length, ...proposedFromItems)+ );++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{outer}}+ @key="id"+ @label={{label}}+ @onMove={{outerMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ {{#if item.children}}+ <DReorderableList+ class="nested-inner"+ @items={{inner}}+ @key="id"+ @label={{label}}+ @onMove={{innerMove}}+ >+ <:row as |child|>+ <span data-test-item={{child.id}}>{{child.name}}</span>+ </:row>+ </DReorderableList>+ {{/if}}+ </:row>+ </DReorderableList>+ </template>+ );++ await moveViaChord("one", "down", INNER);++ assert.true(+ innerMove.calledOnce,+ "the list the handle belongs to is the list that moves"+ );+ assert.false(+ outerMove.called,+ "and the list it is nested in never sees a key it does not own"+ );+ assert.deepEqual(+ renderedItemOrder(INNER),+ ["two", "one"],+ "the nested row moved"+ );+ });++ test("an accelerator on an outer handle still moves the outer row", async function (assert) {+ const outer = nestedItems();+ const inner = outer[0].children;+ const outerMove = sinon.spy();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{outer}}+ @key="id"+ @label={{label}}+ @onMove={{outerMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ {{#if item.children}}+ <DReorderableList+ class="nested-inner"+ @items={{inner}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |child|>+ <span data-test-item={{child.id}}>{{child.name}}</span>+ </:row>+ </DReorderableList>+ {{/if}}+ </:row>+ </DReorderableList>+ </template>+ );++ await moveViaChord("outer-a", "down");++ assert.true(outerMove.calledOnce, "the outer list moves its own row");+ });++ test("the outer cursor steps over a nested list's handles", async function (assert) {+ const outer = nestedItems();+ const inner = outer[0].children;++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{outer}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ {{#if item.children}}+ <DReorderableList+ class="nested-inner"+ @items={{inner}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |child|>+ <span data-test-item={{child.id}}>{{child.name}}</span>+ </:row>+ </DReorderableList>+ {{/if}}+ </:row>+ </DReorderableList>+ </template>+ );++ const handle = find(handleSelector("outer-a"));+ handle.focus();+ await triggerKeyEvent(handle, "keydown", "ArrowDown");++ assert+ .dom(handleSelector("outer-b"))+ .isFocused(+ "the cursor walks the rows of the list it belongs to, not every handle beneath it"+ );+ });++ test("the nested cursor stops at its own end rather than escaping outwards", async function (assert) {+ const outer = nestedItems();+ const inner = outer[0].children;++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{outer}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ {{#if item.children}}+ <DReorderableList+ class="nested-inner"+ @items={{inner}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |child|>+ <span data-test-item={{child.id}}>{{child.name}}</span>+ </:row>+ </DReorderableList>+ {{/if}}+ </:row>+ </DReorderableList>+ </template>+ );++ const handle = find(handleSelector("two", INNER));+ handle.focus();+ await triggerKeyEvent(handle, "keydown", "ArrowDown");++ assert+ .dom(handleSelector("two", INNER))+ .isFocused(+ "the last row of a nested list has nowhere further to go inside it"+ );+ });+});++module(+ "Integration | ui-kit | DReorderableList | group | rev42618",+ function (hooks) {+ setupRenderingTest(hooks);++ /**+ * Records every move and applies it to the tracked lists it names, the+ * way a real consumer's handler does, so a move that should not have+ * happened shows up in the DOM as well as in the log.+ */+ function recordingApplier(listsById) {+ const moves = [];+ const applyMove = (move) => {+ moves.push(move);+ const from = listsById[move.fromList];+ from.splice(0, from.length, ...move.proposedFromItems);+ if (move.toList !== move.fromList) {+ const to = listsById[move.toList];+ to.splice(0, to.length, ...move.proposedToItems);+ }+ };+ return { moves, applyMove };+ }++ test("rev42618 a disabled member is not offered as a menu destination", async function (assert) {+ const primaryItems = objectItems();+ const archiveItems = [{ id: "archived-alpha", name: "Archived Alpha" }];++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <DReorderableList+ id="rev-disabled-menu-source"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ @listLabel="Primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="rev-disabled-menu-target"+ @disabled={{true}}+ @group={{group}}+ @items={{archiveItems}}+ @key="id"+ @label={{label}}+ @listId="archive"+ @listLabel="Archive"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await openMoveMenu(primaryItems[0].id, "#rev-disabled-menu-source");++ assert+ .dom(moveItemSelector("list"))+ .doesNotExist(+ "a member that cannot accept anything is not offered as somewhere to send a row"+ );+ });++ test("rev42618 a disabled member refuses a spilled move", async function (assert) {+ const primaryItems = trackedArray(objectItems());+ const archiveItems = trackedArray([+ { id: "archived-alpha", name: "Archived Alpha" },+ ]);+ const { moves, applyMove } = recordingApplier({+ primary: primaryItems,+ archive: archiveItems,+ });+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const lastItem = primaryItems.at(-1);++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ id="rev-spill-refused-source"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ @listLabel="Primary"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="rev-spill-refused-target"+ @disabled={{true}}+ @group={{group}}+ @items={{archiveItems}}+ @key="id"+ @label={{label}}+ @listId="archive"+ @listLabel="Archive"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const archiveOrderBefore = renderedItemOrder("#rev-spill-refused-target");++ await moveViaChord(lastItem.id, "down", "#rev-spill-refused-source");++ assert.strictEqual(+ moves.length,+ 0,+ "a spill aimed at a disabled member commits nothing"+ );+ assert.deepEqual(+ renderedItemOrder("#rev-spill-refused-target"),+ archiveOrderBefore,+ "the disabled member's rendered order is untouched"+ );+ assert.true(+ announce.calledWith(sinon.match(label(lastItem))),+ "the refusal is spoken as the row's own boundary"+ );+ });++ test("rev42618 a cross-list move refocuses the row it landed on", async function (assert) {+ const sourceItems = trackedArray([+ { id: "source-alpha", name: "Source Alpha" },+ { id: "source-bravo", name: "Source Bravo" },+ ]);+ const frozenItem = { id: "target-pinned", name: "Target Pinned" };+ const targetItems = trackedArray([+ frozenItem,+ { id: "target-alpha", name: "Target Alpha" },+ ]);+ const movable = (item) => item !== frozenItem;+ const { applyMove } = recordingApplier({+ source: sourceItems,+ target: targetItems,+ });+ const movedItem = sourceItems.at(-1);+ const otherTargetId = targetItems[1].id;++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ id="rev-refocus-source"+ @group={{group}}+ @items={{sourceItems}}+ @key="id"+ @label={{label}}+ @listId="source"+ @listLabel="Source"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="rev-refocus-target"+ @group={{group}}+ @items={{targetItems}}+ @key="id"+ @label={{label}}+ @listId="target"+ @listLabel="Target"+ @movable={{movable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveViaChord(movedItem.id, "down", "#rev-refocus-source");++ assert.deepEqual(+ renderedItemOrder("#rev-refocus-target"),+ [frozenItem.id, movedItem.id, otherTargetId],+ "the frozen row keeps index zero, so the arrival fills the first movable slot"+ );+ assert+ .dom(handleSelector(movedItem.id, "#rev-refocus-target"))+ .isFocused(+ "focus lands on the handle of the row that moved, in the list it moved into"+ );+ });++ test("rev42618 a cross-list move reports the slot the item landed in", async function (assert) {+ const sourceValues = ["bravo"];+ const secondValues = ["alpha", "bravo", "charlie"];+ const movedValue = sourceValues[0];+ const expectedProposed = [...secondValues, movedValue];+ const expectedToIndex = expectedProposed.length - 1;+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ id="rev-slot-source"+ @group={{group}}+ @items={{sourceValues}}+ @key={{INDEX_KEY}}+ @label={{label}}+ @listId="index-source"+ >+ <:row as |item|>+ <span data-test-item={{item}}>{{item}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="rev-slot-second"+ @group={{group}}+ @items={{secondValues}}+ @key={{INDEX_KEY}}+ @label={{label}}+ @listId="index-second"+ @listLabel="Second"+ >+ <:row as |item|>+ <span data-test-item={{item}}>{{item}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveVia("0", "list", "#rev-slot-source");++ assert.strictEqual(+ onMove.callCount,+ 1,+ "the menu destination commits one move"+ );+ assert.deepEqual(+ onMove.firstCall.args[0].proposedToItems,+ expectedProposed,+ "the arriving duplicate lands at the end of the destination's proposal"+ );+ assert.strictEqual(+ onMove.firstCall.args[0].toIndex,+ expectedToIndex,+ "toIndex names the slot the item landed in, not the first equal value"+ );+ assert.true(+ announce.calledWith(+ sinon.match(+ `position ${expectedToIndex + 1} of ${expectedProposed.length}`+ )+ ),+ "the announcement places the row in the slot it landed in"+ );+ });++ test("rev42618 the move menu commits a cross-list move", async function (assert) {+ const firstItems = trackedArray([+ { id: "first-alpha", name: "First Alpha" },+ { id: "first-bravo", name: "First Bravo" },+ ]);+ const secondItems = trackedArray([+ { id: "second-alpha", name: "Second Alpha" },+ ]);+ const { moves, applyMove } = recordingApplier({+ first: firstItems,+ second: secondItems,+ });+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const movedItem = firstItems[0];+ const expectedFirstOrder = firstItems+ .filter((item) => item !== movedItem)+ .map((item) => item.id);+ const expectedSecondOrder = [+ ...secondItems.map((item) => item.id),+ movedItem.id,+ ];++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ id="rev-menu-commit-source"+ @group={{group}}+ @items={{firstItems}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="First links"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="rev-menu-commit-target"+ @group={{group}}+ @items={{secondItems}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Second links"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveVia(movedItem.id, "list", "#rev-menu-commit-source");++ assert.deepEqual(+ renderedItemOrder("#rev-menu-commit-source"),+ expectedFirstOrder,+ "the row left the list it was sent from"+ );+ assert.deepEqual(+ renderedItemOrder("#rev-menu-commit-target"),+ expectedSecondOrder,+ "and joined the destination at its end"+ );+ assert.strictEqual(+ moves.length,+ 1,+ "choosing the destination commits exactly one move"+ );+ assert.strictEqual(+ moves[0].method,+ "menu",+ "a menu choice is reported as one"+ );+ assert.strictEqual(+ moves[0].fromList,+ "first",+ "the move names the member the row left"+ );+ assert.strictEqual(+ moves[0].toList,+ "second",+ "and the member it entered"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the cross-list menu move announces exactly once"+ );+ assert.true(+ announce.firstCall.args[0].includes("Second links"),+ "and the announcement names the destination list"+ );+ });++ test("rev42618 the move menu spills at a boundary", async function (assert) {+ const firstItems = trackedArray([+ { id: "run-alpha", name: "Run Alpha" },+ { id: "run-bravo", name: "Run Bravo" },+ ]);+ const secondItems = trackedArray([+ { id: "run-charlie", name: "Run Charlie" },+ ]);+ const { moves, applyMove } = recordingApplier({+ first: firstItems,+ second: secondItems,+ });+ const movedItem = firstItems.at(-1);+ const expectedFirstOrder = firstItems+ .filter((item) => item !== movedItem)+ .map((item) => item.id);+ const expectedSecondOrder = [+ movedItem.id,+ ...secondItems.map((item) => item.id),+ ];++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ id="rev-menu-spill-first"+ @group={{group}}+ @items={{firstItems}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="First"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="rev-menu-spill-second"+ @group={{group}}+ @items={{secondItems}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Second"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveVia(movedItem.id, "down", "#rev-menu-spill-first");++ assert.deepEqual(+ renderedItemOrder("#rev-menu-spill-first"),+ expectedFirstOrder,+ "the last row stepped out of the list it had run out of room in"+ );+ assert.deepEqual(+ renderedItemOrder("#rev-menu-spill-second"),+ expectedSecondOrder,+ "and entered the next member at the top"+ );+ assert.strictEqual(+ moves.length,+ 1,+ "the boundary step commits exactly one move"+ );+ assert.strictEqual(+ moves[0].method,+ "menu",+ "a spill chosen from the menu is reported as a menu move, not a keyboard one"+ );+ });++ test("rev42618 a frozen destination row keeps its slot when an item arrives", async function (assert) {+ const sourceItems = [+ { id: "drag-source-alpha", name: "Drag Source Alpha" },+ ];+ const frozenItem = { id: "drag-pinned", name: "Drag Pinned" };+ const targetItems = [+ { id: "drag-target-alpha", name: "Drag Target Alpha" },+ frozenItem,+ { id: "drag-target-charlie", name: "Drag Target Charlie" },+ ];+ const frozenIndex = targetItems.indexOf(frozenItem);+ const movable = (item) => item !== frozenItem;+ const onMove = sinon.spy();++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ id="rev-frozen-drop-source"+ @group={{group}}+ @items={{sourceItems}}+ @key="id"+ @label={{label}}+ @listId="source"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="rev-frozen-drop-target"+ @group={{group}}+ @items={{targetItems}}+ @key="id"+ @label={{label}}+ @listId="target"+ @movable={{movable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const source = rowSelector(sourceItems[0].id, "#rev-frozen-drop-source");+ const target = rowSelector(+ targetItems.at(-1).id,+ "#rev-frozen-drop-target"+ );+ assertDragReady(assert, source, target);+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "before"),+ });++ assert.strictEqual(onMove.callCount, 1, "the drop commits one move");+ assert.strictEqual(+ onMove.firstCall.args[0].proposedToItems[frozenIndex],+ frozenItem,+ "the frozen destination row holds its slot while the arrival is interleaved around it"+ );+ });++ test("rev42618 a stale cross-list destination announces its refusal", async function (assert) {+ const primaryItems = objectItems();+ const secondaryItems = [+ { id: "stale-secondary-alpha", name: "Stale Secondary Alpha" },+ ];+ const state = new (class {+ @tracked showSecondary = true;+ })();+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ id="rev-stale-source"+ @group={{group}}+ @items={{primaryItems}}+ @key="id"+ @label={{label}}+ @listId="primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ {{#if state.showSecondary}}+ <DReorderableList+ id="rev-stale-target"+ @group={{group}}+ @items={{secondaryItems}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ @listLabel="Secondary links"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ {{/if}}+ </DReorderableListGroup>+ </template>+ );++ await openMoveMenu(primaryItems[0].id, "#rev-stale-source");+ assert+ .dom(moveItemSelector("list"))+ .exists(+ "the destination stands in the menu while its member is mounted"+ );++ state.showSecondary = false;+ await settled();++ await click(moveItemSelector("list"));++ assert.strictEqual(+ onMove.callCount,+ 0,+ "no move is recorded against a member that no longer exists"+ );+ assert.true(+ announce+ .getCalls()+ .some((call) => String(call.args[0]).includes("Could not move")),+ "the refusal itself is spoken, not a success sentence for a move that never happened"+ );+ });++ test("rev42618 spill follows document order not registration order", async function (assert) {+ const alphaItems = trackedArray([+ { id: "alpha-one", name: "Alpha One" },+ { id: "alpha-two", name: "Alpha Two" },+ ]);+ const betaItems = trackedArray([{ id: "beta-one", name: "Beta One" }]);+ const members = trackedArray([+ {+ listId: "alpha",+ listLabel: "Alpha",+ className: "doc-order-alpha",+ items: alphaItems,+ },+ {+ listId: "beta",+ listLabel: "Beta",+ className: "doc-order-beta",+ items: betaItems,+ },+ ]);+ const { applyMove } = recordingApplier({+ alpha: alphaItems,+ beta: betaItems,+ });+ const alphaOrderBefore = alphaItems.map((item) => item.id);+ const movedItem = betaItems[0];++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ {{#each members key="listId" as |member|}}+ <DReorderableList+ class={{member.className}}+ @group={{group}}+ @items={{member.items}}+ @key="id"+ @label={{label}}+ @listId={{member.listId}}+ @listLabel={{member.listLabel}}+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ {{/each}}+ </DReorderableListGroup>+ </template>+ );++ // Reversing the keyed array moves the members' DOM nodes without+ // destroying the components, so the group's registration order still+ // says "alpha" came first. Only a neighbour lookup sorted by document+ // position can tell that "beta" now renders above it; a+ // registration-ordered one would refuse this move as the group's end.+ const [alphaMember, betaMember] = [...members];+ members.splice(0, members.length, betaMember, alphaMember);+ await settled();++ await moveViaChord(movedItem.id, "down", ".doc-order-beta");++ assert.deepEqual(+ renderedItemOrder(".doc-order-alpha"),+ [movedItem.id, ...alphaOrderBefore],+ "the row spilled into the member that now renders below its own"+ );+ assert.deepEqual(+ renderedItemOrder(".doc-order-beta"),+ [],+ "and left the member it ran out of"+ );+ });+ }+);diff --git a/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-keyboard-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-keyboard-test.gjsnew file mode 100644index 00000000000..b2630b5b759--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-keyboard-test.gjs@@ -0,0 +1,1756 @@+import { tracked } from "@glimmer/tracking";+import { concat } from "@ember/helper";+import { trackedArray } from "@ember/reactive/collections";+import {+ click,+ find,+ findAll,+ focus,+ render,+ settled,+ triggerKeyEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import DialogHolder from "discourse/dialog-holder/components/dialog-holder";+import DMenus from "discourse/float-kit/components/d-menus";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import {+ INDEX_KEY,+ isMovable,+ label,+ List,+ MENU_SELECTOR,+ mixedItems,+ noop,+ objectItems,+ renderedItemOrder,+} from "discourse/tests/helpers/ui-kit/reorderable-list-fixtures";+import {+ handleSelector,+ moveItemSelector,+ moveVia,+ moveViaChord,+ openMoveMenu,+ rowSelector,+} from "discourse/tests/helpers/ui-kit/reorderable-list-helper";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import DReorderableListGroup from "discourse/ui-kit/d-reorderable-list-group";++module(+ "Integration | ui-kit | DReorderableList | keyboard and menu",+ function (hooks) {+ setupRenderingTest(hooks);++ const moveKeys = [+ "method",+ "item",+ "fromList",+ "toList",+ "fromIndex",+ "toIndex",+ "fromItems",+ "toItems",+ "proposedFromItems",+ "proposedToItems",+ ].sort();++ test("every movable row renders one handle carrying its description", async function (assert) {+ const items = objectItems();+ const movable = (item) => item.id !== "bravo";++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(".d-reorderable-list__handle")+ .exists({ count: 2 }, "only the movable rows carry a handle");+ assert+ .dom(handleSelector("bravo"))+ .doesNotExist("a frozen row renders no control at all");++ for (const key of ["alpha", "charlie"]) {+ const handle = find(handleSelector(key));+ const describedBy = handle.getAttribute("aria-describedby");+ assert+ .dom(`#${describedBy}`)+ .hasText(+ "Use the arrow keys to move between rows. Press Enter for move options.",+ `${key}'s handle is described by the interaction hint`+ );+ assert.true(+ handle.contains(find(`#${describedBy}`)),+ `${key}'s description belongs to its own control, not to the list`+ );+ }+ });++ test("the handle names its row and reports its menu state", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ assert+ .dom(handleSelector("bravo"))+ .hasAria(+ "label",+ "Reorder Bravo",+ "the handle names which row it moves"+ )+ .hasAria("expanded", "false");++ await openMoveMenu("bravo");++ assert+ .dom(handleSelector("bravo"))+ .hasAria(+ "expanded",+ "true",+ "the open menu is reported on the trigger"+ );+ });++ test("every handle is a tab stop, and arrows walk between them", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ const tabbable = findAll(".d-reorderable-list__handle").filter(+ (element) => element.getAttribute("tabindex") !== "-1"+ );+ assert.strictEqual(+ tabbable.length,+ items.length,+ "every row's handle is reachable by Tab, in DOM order with the row's own controls"+ );++ await focus(handleSelector("alpha"));+ await triggerKeyEvent(handleSelector("alpha"), "keydown", "ArrowDown");++ assert+ .dom(handleSelector("bravo"))+ .isFocused(+ "a plain arrow is an accelerator that moves focus, not the row"+ );+ assert.deepEqual(+ renderedItemOrder(),+ ["alpha", "bravo", "charlie"],+ "and nothing reordered"+ );+ });++ test("the remove control names what it removes and reports the item", async function (assert) {+ const items = objectItems();+ const removed = [];+ const onRemove = (item) => removed.push(item.id);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @onRemove={{onRemove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(`${rowSelector("bravo")} .d-reorderable-list__remove`)+ .hasAria(+ "label",+ "Remove Bravo",+ "an icon-only control still says what it removes"+ );++ await click(`${rowSelector("bravo")} .d-reorderable-list__remove`);++ assert.deepEqual(removed, ["bravo"], "the item itself is reported");+ });++ test("removal is announced and leaves focus on the row that took its place", async function (assert) {+ const state = new (class {+ @tracked items = objectItems();+ })();+ const onRemove = (item) => {+ state.items = state.items.filter((candidate) => candidate !== item);+ };+ // Spied rather than read back off the service: an announcement schedules+ // its own clear, and `settled()` waits that timer out.+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{state.items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @onRemove={{onRemove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await click(`${rowSelector("bravo")} .d-reorderable-list__remove`);++ assert.strictEqual(+ announce.callCount,+ 1,+ "one announcement per removal, not one per rerender"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ "Removed Bravo",+ "a row leaving under the reader is not a silent no-op"+ );+ assert+ .dom(`${rowSelector("charlie")} .d-reorderable-list__remove`)+ .isFocused(+ "focus lands on the row that moved up, so a second removal needs no re-entry"+ );+ });++ test("a row refused by @removable renders no remove control", async function (assert) {+ const items = objectItems();+ const removable = (item) => item.id !== "bravo";++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @onRemove={{noop}}+ @removable={{removable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(`${rowSelector("bravo")} .d-reorderable-list__remove`)+ .doesNotExist(+ "a protected row carries no dead control, exactly as a frozen row carries no handle"+ );+ assert+ .dom(`${rowSelector("alpha")} .d-reorderable-list__remove`)+ .exists("while the rows that can go still offer it");+ });++ test("opening the menu hands focus to its first destination", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ await openMoveMenu("bravo");++ assert+ .dom(moveItemSelector("top"))+ .isFocused(+ "focus moves into the menu rather than staying on the trigger it was opened from"+ );+ });++ test("moving the cursor closes a menu it would otherwise leave behind", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ await openMoveMenu("alpha");+ assert+ .dom(".d-reorderable-list__move-item")+ .exists("the menu is open on the first row");++ await triggerKeyEvent(handleSelector("alpha"), "keydown", "ArrowDown");++ assert+ .dom(handleSelector("bravo"))+ .isFocused("the cursor still moves between rows");+ assert+ .dom(".d-reorderable-list__move-item")+ .doesNotExist(+ "and the menu closes rather than staying open over a row the cursor has left"+ );+ assert+ .dom(handleSelector("alpha"))+ .hasAria("expanded", "false", "the trigger reports itself closed");+ });++ test("tab order runs in DOM order through each row and its controls", async function (assert) {+ // A roving cursor over the handles would interleave with the rows' own+ // tab order, leaving a handle unreachable from the control beside it.+ const items = objectItems();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ <button class={{concat "extra-" item.id}} type="button">x</button>+ </:row>+ </DReorderableList>+ </template>+ );++ const order = findAll(+ ".d-reorderable-list__handle, [class^='extra-']"+ ).map((element) =>+ element.classList.contains("d-reorderable-list__handle")+ ? `handle-${element.closest("[data-reorderable-key]").dataset.reorderableKey}`+ : element.className+ );++ assert.deepEqual(+ order,+ [+ "handle-alpha",+ "extra-alpha",+ "handle-bravo",+ "extra-bravo",+ "handle-charlie",+ "extra-charlie",+ ],+ "each row's handle precedes its own controls and nothing interleaves"+ );+ });++ test("clicking a row's non-interactive area moves the cursor there", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ await click(`${rowSelector("charlie")} [data-test-item]`);++ assert+ .dom(handleSelector("charlie"))+ .isFocused("the pointer and the keyboard agree on where 'here' is");+ });++ test("a menu move emits the exact payload and one announcement", async function (assert) {+ const items = trackedArray(objectItems());+ const moves = [];+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const handleMove = (move) => {+ moves.push(move);+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ await moveVia("alpha", "down");++ assert.strictEqual(moves.length, 1, "one commit for one chosen move");+ const [move] = moves;+ assert.deepEqual(Object.keys(move).sort(), moveKeys, "the payload shape");+ assert.strictEqual(move.method, "menu", "the method names the menu");+ assert.strictEqual(move.item.id, "alpha");+ assert.strictEqual(move.fromIndex, 0);+ assert.strictEqual(move.toIndex, 1);+ assert.deepEqual(+ move.proposedToItems.map((item) => item.id),+ ["bravo", "alpha", "charlie"]+ );+ assert.deepEqual(renderedItemOrder(), ["bravo", "alpha", "charlie"]);++ assert.true(+ announce.calledOnceWith("Moved Alpha to position 2 of 3"),+ "exactly one announcement, naming the item and its new position"+ );+ });++ test("move to top and move to bottom jump the whole distance in one commit", async function (assert) {+ const items = trackedArray(objectItems());+ const moves = [];+ const handleMove = (move) => {+ moves.push(move);+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ await moveVia("charlie", "top");++ assert.deepEqual(renderedItemOrder(), ["charlie", "alpha", "bravo"]);+ assert.strictEqual(+ moves.length,+ 1,+ "one commit, not one per position crossed"+ );++ await moveVia("charlie", "bottom");++ assert.deepEqual(renderedItemOrder(), ["alpha", "bravo", "charlie"]);+ assert.strictEqual(moves.length, 2);+ });++ test("opening focuses the first destination the row can use", async function (assert) {+ // The first row can go nowhere but down, and the destinations it cannot+ // use are not in the menu to be focused in the first place.+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ await openMoveMenu("alpha");++ assert+ .dom(moveItemSelector("top"))+ .doesNotExist("the first row cannot go to the top");+ assert+ .dom(moveItemSelector("down"))+ .isFocused("so focus lands on the first destination it can use");+ });++ test("the menu is a menu, and its destinations are its items", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ assert+ .dom(handleSelector("alpha"))+ .hasAttribute(+ "aria-haspopup",+ "menu",+ "the handle says what it opens before it is opened"+ );++ await openMoveMenu("alpha");++ assert+ .dom(MENU_SELECTOR)+ .hasAttribute("role", "menu")+ .hasAttribute(+ "aria-label",+ "Reorder Alpha",+ "and the menu carries its trigger's name, so it is announced with the row it acts on"+ );+ assert+ .dom(moveItemSelector("down"))+ .hasAttribute("role", "menuitem", "each destination is an item of it");+ });++ test("arrows move between destinations, wrapping and skipping the refused", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ await openMoveMenu("bravo");+ assert+ .dom(moveItemSelector("top"))+ .isFocused("opening lands on the first");++ await triggerKeyEvent(moveItemSelector("top"), "keydown", "ArrowDown");+ assert.dom(moveItemSelector("up")).isFocused("ArrowDown steps forward");++ await triggerKeyEvent(moveItemSelector("up"), "keydown", "ArrowUp");+ assert.dom(moveItemSelector("top")).isFocused("ArrowUp steps back");++ await triggerKeyEvent(moveItemSelector("top"), "keydown", "End");+ assert.dom(moveItemSelector("bottom")).isFocused("End reaches the last");++ await triggerKeyEvent(moveItemSelector("bottom"), "keydown", "Home");+ assert+ .dom(moveItemSelector("top"))+ .isFocused("Home returns to the first");++ await triggerKeyEvent(moveItemSelector("top"), "keydown", "ArrowUp");+ assert+ .dom(moveItemSelector("bottom"))+ .isFocused("and the ends wrap rather than dead-ending");+ });++ test("the cursor steps over a destination the row cannot take", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ // The first row refuses both upward destinations, so wrapping backwards+ // from the first it can take has to clear them in one step.+ await openMoveMenu("alpha");+ assert.dom(moveItemSelector("down")).isFocused();++ await triggerKeyEvent(moveItemSelector("down"), "keydown", "ArrowUp");++ assert+ .dom(moveItemSelector("bottom"))+ .isFocused("the refused destinations are stepped over, not landed on");+ });++ test("an arrow inside the menu does not move the row cursor", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ await openMoveMenu("bravo");+ await triggerKeyEvent(moveItemSelector("top"), "keydown", "ArrowDown");++ assert+ .dom(moveItemSelector("up"))+ .isFocused("the arrow belongs to the menu it was pressed in");+ assert+ .dom(handleSelector("charlie"))+ .isNotFocused("and never reaches the row beneath");+ });++ test("Tab leaves the menu rather than cycling inside it", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ await openMoveMenu("bravo");+ assert.dom(moveItemSelector("top")).isFocused();++ await triggerKeyEvent(moveItemSelector("top"), "keydown", "Tab");++ // A non-modal float shows nothing to say that Tab has stopped meaning+ // "move on", so it dismisses and hands the sequence back where the reader+ // would have been had the menu never opened, rather than trapping them+ // with Escape as their only way out.+ assert+ .dom(".d-reorderable-list__move-item")+ .doesNotExist("Tab dismisses the menu");+ assert+ .dom(handleSelector("charlie"))+ .isFocused("and continues from the stop after the handle it opened at");++ await openMoveMenu("bravo");+ await triggerKeyEvent(moveItemSelector("top"), "keydown", "Tab", {+ shiftKey: true,+ });++ assert+ .dom(".d-reorderable-list__move-item")+ .doesNotExist("Shift+Tab dismisses it too");+ assert+ .dom(handleSelector("bravo"))+ .isFocused(+ "landing back on the handle, which is where the reader came in"+ );+ });++ test("the accelerator works from inside the menu it is advertised in", async function (assert) {+ const items = trackedArray(objectItems());+ const moves = [];+ const handleMove = (move) => {+ moves.push(move);+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ await openMoveMenu("alpha");+ await triggerKeyEvent(moveItemSelector("down"), "keydown", "ArrowDown", {+ altKey: true,+ });++ assert.strictEqual(moves.length, 1, "the chord commits the same move");+ assert.deepEqual(renderedItemOrder(), ["bravo", "alpha", "charlie"]);+ assert+ .dom(".d-reorderable-list__move-item")+ .doesNotExist("and closes the menu, as choosing the destination would");+ });++ test("each destination shows and announces the accelerator it answers to", async function (assert) {+ const items = objectItems();+ const emptyItems = [];++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <DReorderableList+ id="hint-primary"+ @group={{group}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @listId="primary"+ @listLabel="Primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="hint-secondary"+ @group={{group}}+ @items={{emptyItems}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ @listLabel="Secondary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await openMoveMenu("bravo", "#hint-primary");++ // Two forms, deliberately different. The drawn half carries the glyph+ // an arrow key shows on every platform, beside a spoken name for the+ // reader; the announced half carries the spoken name alone, because a+ // reader hearing the glyph learns nothing. Only the key half is+ // assertable: the modifier differs by keyboard.+ for (const [target, announced, drawn] of [+ ["top", /\+Home$/, "Home"],+ ["up", /\+Up arrow$/, "\u2191"],+ ["down", /\+Down arrow$/, "\u2193"],+ ["bottom", /\+End$/, "End"],+ ]) {+ assert+ .dom(moveItemSelector(target))+ .hasAttribute(+ "aria-keyshortcuts",+ announced,+ `${target} announces its accelerator by name`+ );+ assert+ .dom(`${moveItemSelector(target)} kbd`)+ .includesText(drawn, `${target} draws its key`);+ }++ // The raw event name is what a hand-rolled shortcut leaks; neither form+ // should ever carry it.+ assert+ .dom(`${moveItemSelector("up")} kbd`)+ .doesNotIncludeText(+ "ArrowUp",+ "the drawn form names the key for a reader, not for the event system"+ );++ assert+ .dom(moveItemSelector("list"))+ .doesNotHaveAttribute(+ "aria-keyshortcuts",+ "a cross-list destination has no accelerator to advertise"+ );+ assert+ .dom(`${moveItemSelector("list")} kbd`)+ .doesNotExist("so it shows nothing either");+ });++ test("a boundary row offers only the destinations that work", async function (assert) {+ const items = trackedArray(objectItems());+ const moves = [];+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const handleMove = (move) => moves.push(move);++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ await openMoveMenu("alpha");++ assert+ .dom(".d-reorderable-list__move-item")+ .exists(+ { count: 2 },+ "the first row is announced as holding only what it can reach"+ );+ for (const target of ["top", "up"]) {+ assert+ .dom(moveItemSelector(target))+ .doesNotExist(`${target} leads nowhere from the first row`);+ }+ for (const target of ["down", "bottom"]) {+ assert.dom(moveItemSelector(target)).exists(`${target} is available`);+ }++ await openMoveMenu("alpha");+ await openMoveMenu("bravo");++ assert+ .dom(".d-reorderable-list__move-item")+ .exists({ count: 4 }, "a row with room on both sides offers all four");++ await openMoveMenu("bravo");+ await openMoveMenu("charlie");++ assert+ .dom(".d-reorderable-list__move-item")+ .exists({ count: 2 }, "and the last row mirrors the first");+ for (const target of ["down", "bottom"]) {+ assert+ .dom(moveItemSelector(target))+ .doesNotExist(`${target} leads nowhere from the last row`);+ }++ await openMoveMenu("charlie");++ // The accelerator still reaches a boundary the menu no longer shows, so+ // the refusal is the only thing left to say it happened.+ await moveViaChord("alpha", "up");++ assert.deepEqual(moves, [], "a refused move commits nothing");+ assert.deepEqual(renderedItemOrder(), ["alpha", "bravo", "charlie"]);+ assert.true(+ announce.calledOnceWith("Alpha is already first"),+ "and the refusal is spoken rather than being a silent no-op"+ );+ });++ test("a row with nowhere to go renders no handle at all", async function (assert) {+ const items = [{ id: "alpha", name: "Alpha" }];++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ assert+ .dom(rowSelector("alpha"))+ .exists("the row is still rendered, it simply cannot be reordered");+ assert+ .dom(handleSelector("alpha"))+ .doesNotExist(+ "a lone row in a standalone list can be neither dragged nor moved, so it offers no control that would open onto nothing"+ );+ });++ test("a lone row keeps its handle where a sibling list is somewhere to go", async function (assert) {+ const items = [{ id: "alpha", name: "Alpha" }];+ const emptyItems = [];++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <DReorderableList+ id="lone-primary"+ @group={{group}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @listId="primary"+ @listLabel="Primary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="lone-secondary"+ @group={{group}}+ @items={{emptyItems}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ @listLabel="Secondary"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ assert+ .dom(handleSelector("alpha", "#lone-primary"))+ .exists("the sibling is a destination, so the handle has work to do");++ await openMoveMenu("alpha", "#lone-primary");++ assert+ .dom(".d-reorderable-list__move-item")+ .exists({ count: 1 }, "and the menu holds only that destination");+ assert+ .dom(moveItemSelector("list"))+ .exists("which is the sibling list, not a direction");+ });++ test("the arrow cursor reaches the rows a move cannot", async function (assert) {+ const items = trackedArray(mixedItems());++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{isMovable}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ find(handleSelector("bravo")).focus();+ await triggerKeyEvent(handleSelector("bravo"), "keydown", "ArrowDown");++ assert+ .dom(rowSelector("charlie"))+ .isFocused("the cursor carries on into a row that cannot be moved");++ await triggerKeyEvent(rowSelector("charlie"), "keydown", "ArrowDown");++ assert.dom(rowSelector("delta")).isFocused("and keeps going");++ await triggerKeyEvent(rowSelector("delta"), "keydown", "ArrowDown");++ assert+ .dom(rowSelector("delta"))+ .isFocused("clamping at the last row rather than wrapping");++ await triggerKeyEvent(rowSelector("delta"), "keydown", "ArrowUp");+ await triggerKeyEvent(rowSelector("charlie"), "keydown", "ArrowUp");++ assert+ .dom(handleSelector("bravo"))+ .isFocused("and hands back to the handle where a row renders one");+ });++ test("only a row with no handle becomes an arrow target", async function (assert) {+ const items = trackedArray(mixedItems());++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{isMovable}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(rowSelector("alpha"))+ .doesNotHaveAttribute(+ "tabindex",+ "a row whose handle is the cursor target stays out of the tab sequence itself"+ );+ assert+ .dom(rowSelector("charlie"))+ .hasAttribute(+ "tabindex",+ "-1",+ "a row with no handle is reachable by the cursor but never by Tab"+ );+ });++ test("a row's own field keeps the arrows its caret needs", async function (assert) {+ const items = trackedArray(mixedItems());++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{isMovable}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <input id="field-{{item.id}}" value={{item.name}} />+ </:row>+ </DReorderableList>+ </template>+ );++ find("#field-alpha").focus();+ await triggerKeyEvent("#field-alpha", "keydown", "ArrowDown");++ assert+ .dom("#field-alpha")+ .isFocused(+ "a field is neither a handle nor a cursor row, so the list never claims its arrows"+ );+ });++ test("a control that cannot use an arrow lets the cursor step from its row", async function (assert) {+ const items = trackedArray(mixedItems());++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{isMovable}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <button+ aria-checked="false"+ id="switch-{{item.id}}"+ role="switch"+ type="button"+ >{{item.name}}</button>+ </:row>+ </DReorderableList>+ </template>+ );++ find("#switch-charlie").focus();+ await triggerKeyEvent("#switch-charlie", "keydown", "ArrowDown");++ assert+ .dom(rowSelector("delta"))+ .isFocused(+ "a switch has no use for Up and Down, so the row it sits in answers for them"+ );++ await triggerKeyEvent(rowSelector("delta"), "keydown", "ArrowUp");++ assert+ .dom(rowSelector("charlie"))+ .isFocused("and the cursor is back on the row, not on the switch");+ });++ test("a control that does use the arrows keeps them", async function (assert) {+ const items = trackedArray(mixedItems());++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{isMovable}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <button+ aria-checked="false"+ id="radio-{{item.id}}"+ role="radio"+ type="button"+ >{{item.name}}</button>+ </:row>+ </DReorderableList>+ </template>+ );++ find("#radio-charlie").focus();+ await triggerKeyEvent("#radio-charlie", "keydown", "ArrowDown");++ assert+ .dom("#radio-charlie")+ .isFocused(+ "the arrows move between radios in a group, so the list never claims them"+ );+ });++ test("an accelerator is refused on a row that cannot move", async function (assert) {+ const items = trackedArray(mixedItems());+ const moves = [];+ const handleMove = (move) => moves.push(move);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{isMovable}}+ @onMove={{handleMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ find(rowSelector("charlie")).focus();+ await triggerKeyEvent(rowSelector("charlie"), "keydown", "ArrowUp", {+ altKey: true,+ });++ assert.deepEqual(+ moves,+ [],+ "the chord belongs to the handle, and a frozen row has none"+ );+ assert.deepEqual(renderedItemOrder(), [+ "alpha",+ "bravo",+ "charlie",+ "delta",+ ]);+ });++ test("the arrow cursor steps over a target it cannot land on", async function (assert) {+ const items = trackedArray(mixedItems());++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{isMovable}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ // Taken out of layout rather than out of the list, so the row is still a+ // selector match: exactly the case a raw querySelectorAll walk would hand+ // focus to.+ find(rowSelector("charlie")).style.display = "none";++ find(handleSelector("bravo")).focus();+ await triggerKeyEvent(handleSelector("bravo"), "keydown", "ArrowDown");++ assert+ .dom(rowSelector("delta"))+ .isFocused(+ "a row removed from layout is nowhere focus can be put, so the cursor passes it"+ );+ });++ test("a repeated chord carries the same row down an index-keyed list", async function (assert) {+ // Where the key is the position, refocusing by the key the row had before+ // the move lands on whichever row took that slot — so the next press+ // moves the wrong item and the two swap back and forth forever.+ const items = trackedArray(["Alpha", "Bravo", "Charlie"]);+ const indexKey = "@index";+ const handleMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key={{indexKey}}+ @label={{label}}+ @onMove={{handleMove}}+ >+ <:row as |item|>+ <span data-test-item={{item}}>{{item}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveViaChord("0", "down");++ assert.deepEqual(renderedItemOrder(), ["Bravo", "Alpha", "Charlie"]);+ assert+ .dom(handleSelector("1"))+ .isFocused("focus follows the row that moved, not the slot it left");++ await triggerKeyEvent(handleSelector("1"), "keydown", "ArrowDown", {+ altKey: true,+ });++ assert.deepEqual(+ renderedItemOrder(),+ ["Bravo", "Charlie", "Alpha"],+ "so pressing again carries the same row further rather than swapping it back"+ );+ assert.dom(handleSelector("2")).isFocused();+ });++ test("Alt with an arrow moves the row and keeps focus on its handle", async function (assert) {+ const items = trackedArray(objectItems());+ const moves = [];+ const handleMove = (move) => {+ moves.push(move);+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ await moveViaChord("alpha", "down");++ assert.deepEqual(renderedItemOrder(), ["bravo", "alpha", "charlie"]);+ assert.strictEqual(moves.length, 1);+ assert.strictEqual(+ moves[0].method,+ "keyboard",+ "the method distinguishes the chord from the menu"+ );+ assert+ .dom(handleSelector("alpha"))+ .isFocused(+ "focus follows the row it moved, so a second press is possible"+ );++ await triggerKeyEvent(document.activeElement, "keydown", "ArrowUp", {+ altKey: true,+ });++ assert.deepEqual(+ renderedItemOrder(),+ ["alpha", "bravo", "charlie"],+ "and the opposite chord reverses it"+ );+ });++ test("Alt with Home or End sends the row to an end", async function (assert) {+ const items = trackedArray(objectItems());+ const handleMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ await moveViaChord("alpha", "bottom");+ assert.deepEqual(renderedItemOrder(), ["bravo", "charlie", "alpha"]);++ await moveViaChord("alpha", "top");+ assert.deepEqual(renderedItemOrder(), ["alpha", "bravo", "charlie"]);+ });++ test("a chord at a boundary announces without committing", async function (assert) {+ const items = trackedArray(objectItems());+ const moves = [];+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const handleMove = (move) => moves.push(move);++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ await moveViaChord("charlie", "down");++ assert.deepEqual(moves, [], "nothing committed past the end");+ assert.true(+ announce.calledOnceWith("Charlie is already last"),+ "arriving at the end is reported"+ );+ });++ test("a run of chord moves speaks position only until it settles", async function (assert) {+ const items = trackedArray(objectItems());+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const handleMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ // Dispatched directly, and both in one turn: `triggerKeyEvent` awaits+ // `settled()`, which drains the run's settle timer and would end the run+ // between the two presses. A held key repeats far faster than that.+ const press = () =>+ document.activeElement.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ altKey: true,+ bubbles: true,+ })+ );+ find(handleSelector("alpha")).focus();+ press();+ press();+ await settled();++ assert.deepEqual(renderedItemOrder(), ["bravo", "charlie", "alpha"]);+ assert.deepEqual(+ announce.getCalls().map((call) => call.args[0]),+ ["2 of 3", "3 of 3", "Moved Alpha to position 3 of 3"],+ "terse while the run continues, the full sentence once it settles"+ );+ });++ test("a run cut short by teardown does not speak for a list that is gone", async function (assert) {+ const items = trackedArray(objectItems());+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const state = new (class {+ @tracked show = true;+ })();+ const handleMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template>+ <DMenus />+ {{#if state.show}}+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{handleMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ {{/if}}+ </template>+ );++ // Dispatched directly rather than through `triggerKeyEvent`, which awaits+ // `settled()` and would drain the settle timer before the teardown.+ find(handleSelector("alpha")).focus();+ document.activeElement.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ altKey: true,+ bubbles: true,+ })+ );++ state.show = false;+ await settled();++ assert.deepEqual(+ announce.getCalls().map((call) => call.args[0]),+ ["2 of 3"],+ "the in-run position stands, and the settle timer speaks nothing after teardown"+ );+ });++ test("a menu move always speaks the full sentence", async function (assert) {+ const items = trackedArray(objectItems());+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const handleMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ await moveVia("alpha", "down");+ await moveVia("alpha", "down");++ assert.deepEqual(+ announce.getCalls().map((call) => call.args[0]),+ ["Moved Alpha to position 2 of 3", "Moved Alpha to position 3 of 3"],+ "a deliberate single choice is never abbreviated"+ );+ });++ test("a chord hops frozen rows", async function (assert) {+ const items = trackedArray(objectItems());+ const movable = (item) => item.id !== "bravo";+ const handleMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{handleMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveViaChord("alpha", "down");++ assert.deepEqual(+ renderedItemOrder(),+ ["charlie", "bravo", "alpha"],+ "the frozen row keeps its exact visible slot while the others swap"+ );+ });++ test("the handle is still the drag source", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ assert+ .dom(rowSelector("alpha"))+ .hasAttribute(+ "data-drag-source",+ "",+ "the row is what a drop target receives and what the preview shows"+ );+ });++ test("an unmodified Escape does not reorder anything", async function (assert) {+ const items = trackedArray(objectItems());+ const moves = [];+ const handleMove = (move) => moves.push(move);++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ await focus(handleSelector("bravo"));+ await triggerKeyEvent(handleSelector("bravo"), "keydown", "Escape");++ assert.deepEqual(moves, [], "there is no mode for Escape to unwind");+ assert.deepEqual(renderedItemOrder(), ["alpha", "bravo", "charlie"]);+ });++ test("index identity is safe now that nothing is held across a move", async function (assert) {+ const items = trackedArray(["alpha", "bravo", "charlie"]);+ const handleMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key={{INDEX_KEY}}+ @label={{label}}+ @onMove={{handleMove}}+ >+ <:row as |item|>+ <span data-test-item={{item}}>{{item}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveVia("0", "down");++ assert.deepEqual(+ renderedItemOrder(),+ ["bravo", "alpha", "charlie"],+ "a position-keyed list reorders without a held key to invalidate"+ );+ });++ test("a removal that defers is not spoken for until it completes", async function (assert) {+ const state = new (class {+ @tracked items = objectItems();+ })();+ let release;+ const confirmed = new Promise((resolve) => (release = resolve));+ // What a consumer putting a confirmation in front of the removal returns:+ // the handler is back long before the reader has answered.+ const onRemove = (item) =>+ confirmed.then(() => {+ state.items = state.items.filter((candidate) => candidate !== item);+ });+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{state.items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @onRemove={{onRemove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await click(`${rowSelector("bravo")} .d-reorderable-list__remove`);++ assert.strictEqual(+ announce.callCount,+ 0,+ "nothing is announced while the row is still on screen"+ );+ assert.dom(rowSelector("bravo")).exists("and the row is still there");++ release();+ await settled();++ assert.dom(rowSelector("bravo")).doesNotExist("the row went");+ assert.strictEqual(+ announce.callCount,+ 1,+ "and the announcement lands once it has"+ );+ });++ test("a removal behind a confirmation lands focus once the dialog has gone", async function (assert) {+ const state = new (class {+ @tracked items = objectItems();+ })();+ const dialog = this.owner.lookup("service:dialog");+ // Exactly the shape a consumer with a confirmation writes: the promise is+ // returned so the list waits, and the store is only touched on confirm.+ const onRemove = (item) =>+ dialog.yesNoConfirm({+ message: "Remove it?",+ didConfirm: () => {+ state.items = state.items.filter((candidate) => candidate !== item);+ },+ });+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DialogHolder />+ <DReorderableList+ @items={{state.items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @onRemove={{onRemove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await click(`${rowSelector("bravo")} .d-reorderable-list__remove`);++ assert.strictEqual(+ announce.callCount,+ 0,+ "nothing is said while the reader is still being asked"+ );+ assert.dom(rowSelector("bravo")).exists("and the row is still there");++ await click(".dialog-footer .btn-primary");++ assert.dom(rowSelector("bravo")).doesNotExist("the row went");+ assert.strictEqual(+ announce.callCount,+ 1,+ "and the removal is announced once it actually happened"+ );+ assert+ .dom(`${rowSelector("charlie")} .d-reorderable-list__remove`)+ .isFocused(+ "focus survives the dialog's teardown, so a reader clearing several rows is not thrown to the top of the page after each one"+ );+ });++ test("a cancelled confirmation leaves focus on the control that asked", async function (assert) {+ const items = trackedArray(objectItems());+ const dialog = this.owner.lookup("service:dialog");+ const onRemove = (item) =>+ dialog.yesNoConfirm({+ message: "Remove it?",+ didConfirm: () => items.splice(items.indexOf(item), 1),+ });++ await render(+ <template>+ <DMenus />+ <DialogHolder />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @onRemove={{onRemove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ const control = `${rowSelector("bravo")} .d-reorderable-list__remove`;+ await click(control);+ await click(".dialog-footer .btn-default");++ assert.dom(rowSelector("bravo")).exists("the row stayed");+ assert+ .dom(control)+ .isFocused(+ "the reader is put back where they were, since the confirmation hands focus to an element it has already detached"+ );+ });++ test("a removal the consumer declines is neither announced nor refocused", async function (assert) {+ const items = objectItems();+ // A handler that takes no action, which is every cancelled confirmation+ // and every refusal a consumer makes on its own terms.+ const onRemove = () => {};+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @onRemove={{onRemove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ const control = `${rowSelector("bravo")} .d-reorderable-list__remove`;+ await click(control);++ assert.strictEqual(+ announce.callCount,+ 0,+ "the list reports what happened, not what it asked for"+ );+ assert+ .dom(control)+ .isFocused("and leaves focus on the control that was pressed");+ });++ test("rev42618 a chord run settles onto the row that moved", async function (assert) {+ const items = trackedArray(["Alpha", "Bravo", "Charlie"]);+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const handleMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key={{INDEX_KEY}}+ @label={{label}}+ @onMove={{handleMove}}+ >+ <:row as |item|>+ <span data-test-item={{item}}>{{item}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ // Dispatched directly, then settled: `settled()` drains the run's+ // settle timer, which is what lands the full sentence.+ find(handleSelector("0")).focus();+ document.activeElement.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ altKey: true,+ bubbles: true,+ })+ );+ await settled();++ assert.deepEqual(+ renderedItemOrder(),+ ["Bravo", "Alpha", "Charlie"],+ "the move was applied, so the settled sentence describes a reordered list"+ );+ assert.strictEqual(+ announce.lastCall.args[0],+ "Moved Alpha to position 2 of 3",+ "the settled sentence names the row that moved, not whichever row now sits at the index the run remembered"+ );+ });++ test("rev42618 announceMove false suppresses the settle sentence", async function (assert) {+ const items = trackedArray(objectItems());+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const suppress = () => false;+ const handleMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @announceMove={{suppress}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{handleMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ // Dispatched directly, then settled: `settled()` drains the run's+ // settle timer, which is where the leaked default sentence comes from.+ find(handleSelector("alpha")).focus();+ document.activeElement.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ altKey: true,+ bubbles: true,+ })+ );+ await settled();++ assert.strictEqual(+ announce.callCount,+ 0,+ "a consumer returning false silences the whole move: the settle timer honors the override instead of speaking the default sentence anyway"+ );+ });++ test("rev42618 a vetoed move is not announced at settle", async function (assert) {+ const items = trackedArray(objectItems());+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const handleMove = () => false;++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ // Dispatched directly, then settled: `settled()` drains the run's+ // settle timer, which must not speak for a move that never happened.+ find(handleSelector("alpha")).focus();+ document.activeElement.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ altKey: true,+ bubbles: true,+ })+ );+ await settled();++ assert.strictEqual(+ announce.callCount,+ 0,+ "a move the consumer vetoed never happened, so neither the run nor its settle timer has anything to announce"+ );+ assert.deepEqual(+ renderedItemOrder(),+ ["alpha", "bravo", "charlie"],+ "and the rendered order is unchanged, confirming the veto held"+ );+ });++ test("rev42618 an arrow at the list boundary is not left to the browser", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ // Constructed by hand because `triggerKeyEvent` never hands the event+ // back, and `defaultPrevented` is the whole assertion.+ await focus(handleSelector("alpha"));+ const upAtStart = new KeyboardEvent("keydown", {+ key: "ArrowUp",+ bubbles: true,+ cancelable: true,+ });+ find(handleSelector("alpha")).dispatchEvent(upAtStart);+ await settled();++ assert.true(+ upAtStart.defaultPrevented,+ "a bare ArrowUp on the first handle is consumed even though the cursor clamps: otherwise the browser scrolls the page while focus stays on the end handle"+ );++ await focus(handleSelector("charlie"));+ const downAtEnd = new KeyboardEvent("keydown", {+ key: "ArrowDown",+ bubbles: true,+ cancelable: true,+ });+ find(handleSelector("charlie")).dispatchEvent(downAtEnd);+ await settled();++ assert.true(+ downAtEnd.defaultPrevented,+ "and a bare ArrowDown on the last handle is likewise consumed rather than handed to the browser to scroll with"+ );+ });+ }+);diff --git a/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-repairs-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-repairs-test.gjsnew file mode 100644index 00000000000..b330cecf09a--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-repairs-test.gjs@@ -0,0 +1,403 @@+import { tracked } from "@glimmer/tracking";+import { trackedArray } from "@ember/reactive/collections";+import { click, find, focus, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import DMenus from "discourse/float-kit/components/d-menus";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import {+ label,+ List,+ MENU_SELECTOR,+ noop,+ objectItems,+ renderedItemOrder,+} from "discourse/tests/helpers/ui-kit/reorderable-list-fixtures";+import {+ handleSelector,+ moveItemSelector,+ openMoveMenu,+} from "discourse/tests/helpers/ui-kit/reorderable-list-helper";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import DReorderableListGroup from "discourse/ui-kit/d-reorderable-list-group";++module("Integration | ui-kit | DReorderableList | repairs", function (hooks) {+ setupRenderingTest(hooks);++ test("fix42618 a run that ends in a spill announces nothing about the list it left", async function (assert) {+ const upper = trackedArray([{ id: "golf", name: "Golf" }]);+ const lower = trackedArray([+ { id: "alpha", name: "Alpha" },+ { id: "bravo", name: "Bravo" },+ ]);+ // Both lists apply their moves for real, so the DOM reflects reality and+ // the settle timer reads the rows a reader would actually be looking at.+ const applyMove = (move) => {+ const listFor = (id) => (id === "upper" ? upper : lower);+ const from = listFor(move.fromList);+ from.splice(0, from.length, ...move.proposedFromItems);+ if (move.toList !== move.fromList) {+ const to = listFor(move.toList);+ to.splice(0, to.length, ...move.proposedToItems);+ }+ };+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ id="repair-spill-upper"+ @group={{group}}+ @items={{upper}}+ @key="id"+ @label={{label}}+ @listId="upper"+ @listLabel="Upper"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="repair-spill-lower"+ @group={{group}}+ @items={{lower}}+ @key="id"+ @label={{label}}+ @listId="lower"+ @listLabel="Lower"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ // Dispatched directly, and both in one turn: `triggerKeyEvent` awaits+ // `settled()`, which drains the run's settle timer and would end the run+ // between the two presses. A held key repeats far faster than that.+ const press = () =>+ document.activeElement.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowUp",+ altKey: true,+ bubbles: true,+ })+ );+ find(handleSelector("bravo", "#repair-spill-lower")).focus();+ press();+ press();+ await settled();++ assert.deepEqual(+ renderedItemOrder("#repair-spill-lower"),+ ["alpha"],+ "the first press committed in-list and the second hit the top boundary and spilled the row out"+ );+ assert.deepEqual(+ renderedItemOrder("#repair-spill-upper"),+ ["golf", "bravo"],+ "landing it on the tail of the member above, still travelling upwards"+ );+ for (const call of announce.getCalls()) {+ assert.false(+ String(call.args[0]).includes("Alpha"),+ `"${call.args[0]}" never mentions Alpha, the row that stayed behind: the settle sentence must speak for the row that travelled, not for whichever row now occupies the run's remembered index in the list it left`+ );+ }+ });++ test("fix42618 a custom announcer speaks once per chord press", async function (assert) {+ const items = trackedArray(objectItems());+ // Rendered directly rather than through the shared List fixture, which+ // does not forward @announceMove.+ const customSentence = () => "Custom sentence";+ const handleMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @announceMove={{customSentence}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{handleMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ // Dispatched directly, then settled: `settled()` drains the run's settle+ // timer, which is where the duplicate custom sentence comes from.+ find(handleSelector("alpha")).focus();+ document.activeElement.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ altKey: true,+ bubbles: true,+ })+ );+ await settled();++ assert.strictEqual(+ announce.callCount,+ 1,+ "one press is one sentence: the custom announcer fires at commit or at settle but never both, so the reader does not hear the same sentence twice"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ "Custom sentence",+ "and the one sentence spoken is the consumer's own"+ );+ });++ test("fix42618 an unapplied move is not announced at settle", async function (assert) {+ const items = objectItems();+ const moves = [];+ // Records but neither applies nor returns false: the shape of a handler+ // awaiting a server round trip that outlasts the settle window.+ const handleMove = (move) => {+ moves.push(move);+ };+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template><List @items={{items}} @onMove={{handleMove}} /></template>+ );++ // Dispatched directly, then settled: `settled()` drains the run's settle+ // timer, which must not speak for a move the DOM never showed.+ find(handleSelector("alpha")).focus();+ document.activeElement.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ altKey: true,+ bubbles: true,+ })+ );+ await settled();++ assert.strictEqual(+ moves.length,+ 1,+ "the move was dispatched to the consumer"+ );+ assert.deepEqual(+ renderedItemOrder(),+ ["alpha", "bravo", "charlie"],+ "but never applied, so the rendered order is unchanged"+ );+ for (const call of announce.getCalls()) {+ assert.false(+ String(call.args[0]).includes("Bravo"),+ `"${call.args[0]}" never names Bravo, the row that merely sat at the landing slot: settling on an unapplied move must be silence, not a sentence about a row that did not move`+ );+ }+ });++ test("fix42618 a handle whose destinations vanished still closes its own menu", async function (assert) {+ const soloItems = [{ id: "solo", name: "Solo" }];+ const partnerItems = [{ id: "partner-alpha", name: "Partner Alpha" }];+ const state = new (class {+ @tracked showPartner = true;+ })();++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <DReorderableList+ id="repair-vanish-solo"+ @group={{group}}+ @items={{soloItems}}+ @key="id"+ @label={{label}}+ @listId="solo"+ @listLabel="Solo"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ {{#if state.showPartner}}+ <DReorderableList+ id="repair-vanish-partner"+ @group={{group}}+ @items={{partnerItems}}+ @key="id"+ @label={{label}}+ @listId="partner"+ @listLabel="Partner"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ {{/if}}+ </DReorderableListGroup>+ </template>+ );++ await openMoveMenu("solo", "#repair-vanish-solo");++ assert+ .dom(moveItemSelector("list"))+ .exists(+ "the sibling is a destination while it is mounted, so the menu opens holding it"+ );++ state.showPartner = false;+ await settled();++ assert+ .dom("#repair-vanish-partner")+ .doesNotExist(+ "the sibling unmounted while the menu was still open, taking the only destination with it"+ );++ await click(handleSelector("solo", "#repair-vanish-solo"));++ assert+ .dom(MENU_SELECTOR)+ .doesNotExist(+ "pressing the trigger of an open menu closes it even when every destination has since vanished: the empty-destination guard must not make the toggle inert and strand the menu open"+ );+ });++ test("fix42618 a modified arrow keeps its browser meaning", async function (assert) {+ const items = objectItems();++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ // Constructed by hand because `triggerKeyEvent` never hands the event+ // back, and `defaultPrevented` is the whole assertion.+ await focus(handleSelector("alpha"));+ const modified = new KeyboardEvent("keydown", {+ key: "ArrowUp",+ bubbles: true,+ cancelable: true,+ metaKey: true,+ });+ find(handleSelector("alpha")).dispatchEvent(modified);+ await settled();++ assert.false(+ modified.defaultPrevented,+ "a meta-modified arrow is a browser shortcut rather than a cursor move, so the list must let it pass instead of swallowing it"+ );++ const bare = new KeyboardEvent("keydown", {+ key: "ArrowUp",+ bubbles: true,+ cancelable: true,+ });+ find(handleSelector("alpha")).dispatchEvent(bare);+ await settled();++ assert.true(+ bare.defaultPrevented,+ "while an unmodified ArrowUp on that same first handle is still consumed, so reclaiming the modified form does not regress the bare cursor arrows"+ );+ });+ test("fix42618 a drag-only handle does not promise a keyboard menu", async function (assert) {+ const soloItems = [{ id: "golf", name: "Golf" }];+ const otherItems = [+ { id: "hotel", name: "Hotel" },+ { id: "india", name: "India" },+ ];++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <DReorderableList+ id="solo-list"+ @group={{group}}+ @items={{soloItems}}+ @key="id"+ @label={{label}}+ @listId="solo"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="other-list"+ @group={{group}}+ @items={{otherItems}}+ @key="id"+ @label={{label}}+ @listId="other"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const handle = find(handleSelector("golf", "#solo-list"));+ assert.dom(handle).exists("the lone grouped row keeps its drag handle");++ const describedBy = handle.getAttribute("aria-describedby");+ const description = describedBy ? find(`#${describedBy}`) : null;+ const spoken = description ? description.textContent.trim() : "";+ assert.false(+ spoken.includes("Enter"),+ "a handle that opens no menu does not tell a screen reader to press Enter for move options"+ );+ assert+ .dom(handle)+ .hasAria("label", "Reorder Golf", "and it keeps its name");+ });+ test("fix42618 the settled sentence counts the list as it stands", async function (assert) {+ const items = trackedArray(objectItems());+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const applyMove = (move) => {+ items.splice(0, items.length, ...move.proposedToItems);+ };++ await render(+ <template>+ <DMenus />+ <List @items={{items}} @onMove={{applyMove}} />+ </template>+ );++ // Dispatched raw so the settle timer is still armed while the list grows;+ // `triggerKeyEvent` would await settled() and drain it first.+ find(handleSelector("alpha")).focus();+ document.activeElement.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ altKey: true,+ bubbles: true,+ })+ );+ items.push({ id: "delta", name: "Delta" });+ await settled();++ assert.strictEqual(+ announce.lastCall.args[0],+ "Moved Alpha to position 2 of 4",+ "the settled sentence counts the rows on screen when it speaks, not the rows the move was committed against"+ );+ });+});diff --git a/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-supplemental-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-supplemental-test.gjsnew file mode 100644index 00000000000..f1e41a4fe88--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-supplemental-test.gjs@@ -0,0 +1,1305 @@+import { tracked } from "@glimmer/tracking";+import { trackedArray } from "@ember/reactive/collections";+import {+ click,+ find,+ render,+ resetOnerror,+ settled,+ setupOnerror,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import DMenus from "discourse/float-kit/components/d-menus";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import { simulateDrag } from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";+import {+ dropCoordinates,+ INDEX_KEY,+ label,+ noop,+ objectItems,+ renderedItemOrder,+} from "discourse/tests/helpers/ui-kit/reorderable-list-fixtures";+import {+ moveItemSelector,+ moveVia,+ moveViaChord,+ openMoveMenu,+ rowSelector,+} from "discourse/tests/helpers/ui-kit/reorderable-list-helper";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import DReorderableListGroup from "discourse/ui-kit/d-reorderable-list-group";++/**+ * Supplemental invariant suite for `DReorderableList`, written blind against+ * the public contract in `types.ts`. It pins cross-cutting guarantees —+ * conservation, frozen-row pinning, path agreement, announcement/DOM+ * correspondence, audible refusals, focus retention — rather than restating+ * individual fixes.+ */++/** The comparable identity of one item, object or primitive. */+function idOf(item) {+ return item?.id ?? String(item);+}++/** The identity multiset of one or more item lists, as `{ id: count }`. */+function multiset(lists) {+ const counts = {};+ for (const list of lists) {+ for (const item of list) {+ const id = idOf(item);+ counts[id] = (counts[id] ?? 0) + 1;+ }+ }+ return counts;+}++/**+ * Asserts that one committed move's payload conserves the item multiset: the+ * proposed orders hold exactly the items the visible lists held, nothing+ * duplicated and nothing lost, whether the move stayed in one list or crossed.+ */+function assertConserved(assert, move, context) {+ const crossList = move.fromList !== move.toList;+ const before = crossList+ ? multiset([move.fromItems, move.toItems])+ : multiset([move.fromItems]);+ const after = crossList+ ? multiset([move.proposedFromItems, move.proposedToItems])+ : multiset([move.proposedToItems]);+ assert.deepEqual(+ after,+ before,+ `${context}: the proposed orders hold exactly the items the lists held, nothing duplicated or lost`+ );+}++/**+ * The last announced "position N of M", parsed. Terse in-run fragments like+ * "2 of 3" deliberately do not match; only the settled sentence does.+ */+function lastSpokenPosition(announce) {+ const spoken = announce+ .getCalls()+ .map((call) => call.args[0])+ .filter((text) => /position \d+ of \d+/.test(text))+ .at(-1);+ const match = /position (\d+) of (\d+)/.exec(spoken ?? "");+ return match && { position: Number(match[1]), total: Number(match[2]) };+}++/**+ * A tracked two-member group store with the applier a real consumer writes:+ * the component proposes orders and the store adopts them. Member listIds are+ * `"first"` and `"second"`.+ */+function groupStore(firstItems, secondItems) {+ const first = trackedArray(firstItems);+ const second = trackedArray(secondItems);+ const moves = [];+ const applyMove = (move) => {+ moves.push(move);+ const listFor = (listId) => (listId === "first" ? first : second);+ const from = listFor(move.fromList);+ from.splice(0, from.length, ...move.proposedFromItems);+ if (move.toList !== move.fromList) {+ const to = listFor(move.toList);+ to.splice(0, to.length, ...move.proposedToItems);+ }+ };+ return { first, second, moves, applyMove };+}++/** A tracked standalone list store whose applier adopts each proposed order. */+function listStore(initialItems) {+ const items = trackedArray(initialItems);+ const moves = [];+ const applyMove = (move) => {+ moves.push(move);+ items.splice(0, items.length, ...move.proposedToItems);+ };+ return { items, moves, applyMove };+}++module(+ "Integration | ui-kit | DReorderableList | supplemental",+ function (hooks) {+ setupRenderingTest(hooks);++ test("supp42618 every committed move conserves the item multiset across all involved lists", async function (assert) {+ const { first, second, moves, applyMove } = groupStore(+ [+ { id: "f-one", name: "F One" },+ { id: "f-two", name: "F Two" },+ { id: "f-three", name: "F Three" },+ ],+ [+ { id: "s-one", name: "S One" },+ { id: "s-two", name: "S Two" },+ ]+ );+ const initialUnion = multiset([first, second]);++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ class="supp-first"+ @group={{group}}+ @items={{first}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="First"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="supp-second"+ @group={{group}}+ @items={{second}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Second"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveVia("f-two", "up", ".supp-first");++ assert.strictEqual(+ moves.length,+ 1,+ "the in-list menu move commits exactly once"+ );+ assert.strictEqual(+ moves.at(-1).method,+ "menu",+ "the first operation really travelled the menu path"+ );+ assert.strictEqual(+ moves.at(-1).fromList,+ moves.at(-1).toList,+ "and stayed inside one list"+ );+ assertConserved(assert, moves.at(-1), "in-list menu move");++ const dragSource = rowSelector("f-three", ".supp-first");+ const dragTarget = rowSelector("s-one", ".supp-second");+ await simulateDrag(dragSource, dragTarget, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(dragTarget, "before"),+ });++ assert.strictEqual(+ moves.length,+ 2,+ "the cross-list drag commits exactly once"+ );+ assert.strictEqual(+ moves.at(-1).method,+ "drag",+ "the second operation really travelled the drag path"+ );+ assert.notStrictEqual(+ moves.at(-1).fromList,+ moves.at(-1).toList,+ "and crossed lists"+ );+ assertConserved(assert, moves.at(-1), "cross-list drag");++ await moveVia("s-two", "list", ".supp-second");++ assert.strictEqual(+ moves.length,+ 3,+ "the cross-list menu move commits exactly once"+ );+ assert.strictEqual(+ moves.at(-1).method,+ "menu",+ "the third operation really travelled the menu path"+ );+ assert.notStrictEqual(+ moves.at(-1).fromList,+ moves.at(-1).toList,+ "and crossed lists"+ );+ assertConserved(assert, moves.at(-1), "cross-list menu move");++ const lastFirstKey = renderedItemOrder(".supp-first").at(-1);+ await moveViaChord(lastFirstKey, "down", ".supp-first");++ assert.strictEqual(+ moves.length,+ 4,+ "the keyboard spill commits exactly once"+ );+ assert.strictEqual(+ moves.at(-1).method,+ "keyboard",+ "the fourth operation really travelled the keyboard path"+ );+ assert.notStrictEqual(+ moves.at(-1).fromList,+ moves.at(-1).toList,+ "and spilled across the member boundary"+ );+ assertConserved(assert, moves.at(-1), "keyboard spill");++ assert.deepEqual(+ multiset([first, second]),+ initialUnion,+ "after all four input methods the live stores still hold exactly the original items"+ );+ assert.deepEqual(+ multiset([+ renderedItemOrder(".supp-first"),+ renderedItemOrder(".supp-second"),+ ]),+ initialUnion,+ "and the rendered rows across both lists are the same multiset the page started with"+ );+ });++ test("supp42618 frozen rows at the first, middle, and last index hold their slots through in-list moves", async function (assert) {+ const { items, moves, applyMove } = listStore([+ { id: "pin-first", name: "Pin First" },+ { id: "mov-a", name: "Mov A" },+ { id: "pin-mid", name: "Pin Mid" },+ { id: "mov-b", name: "Mov B" },+ { id: "pin-last", name: "Pin Last" },+ ]);+ const movable = (item) => item.id.startsWith("mov");+ const pinnedSlots = { "pin-first": 0, "pin-mid": 2, "pin-last": 4 };++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{applyMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveVia("mov-a", "bottom");++ assert.strictEqual(moves.length, 1, "the bottom move commits once");+ for (const [id, slot] of Object.entries(pinnedSlots)) {+ assert.strictEqual(+ moves.at(-1).proposedToItems.findIndex((item) => item.id === id),+ slot,+ `${id} keeps visible index ${slot} in the proposal while a row moves to the bottom past it`+ );+ }+ assert.deepEqual(+ renderedItemOrder(),+ ["pin-first", "mov-b", "pin-mid", "mov-a", "pin-last"],+ "the movable rows traded places around all three pinned slots"+ );++ await moveViaChord("mov-a", "top");++ assert.strictEqual(moves.length, 2, "the top chord commits once");+ for (const [id, slot] of Object.entries(pinnedSlots)) {+ assert.strictEqual(+ moves.at(-1).proposedToItems.findIndex((item) => item.id === id),+ slot,+ `${id} keeps visible index ${slot} in the proposal while a row moves to the top past it`+ );+ }+ assert.deepEqual(+ renderedItemOrder(),+ ["pin-first", "mov-a", "pin-mid", "mov-b", "pin-last"],+ "the round trip left every frozen row exactly where it started"+ );+ });++ test("supp42618 frozen edge rows hold their slots when an item leaves one list and enters another", async function (assert) {+ const { first, second, moves, applyMove } = groupStore(+ [+ { id: "src-pin", name: "Src Pin" },+ { id: "src-a", name: "Src A" },+ { id: "src-b", name: "Src B" },+ ],+ [+ { id: "dst-a", name: "Dst A" },+ { id: "dst-b", name: "Dst B" },+ { id: "dst-pin", name: "Dst Pin" },+ ]+ );+ const movable = (item) => !item.id.endsWith("pin");++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{applyMove}} as |group|>+ <DReorderableList+ class="fz-source"+ @group={{group}}+ @items={{first}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="Source"+ @movable={{movable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="fz-destination"+ @group={{group}}+ @items={{second}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Destination"+ @movable={{movable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const source = rowSelector("src-a", ".fz-source");+ const target = rowSelector("dst-a", ".fz-destination");+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "after"),+ });++ assert.strictEqual(moves.length, 1, "the cross-list drop commits once");+ const move = moves[0];+ assertConserved(assert, move, "cross-list drop between frozen edges");++ assert.strictEqual(+ move.proposedFromItems.findIndex((item) => item.id === "src-pin"),+ 0,+ "a frozen first row keeps visible index 0 when a movable row leaves its list"+ );+ assert.strictEqual(+ move.proposedFromItems.length,+ 2,+ "the source proposal shrank by exactly the departed row"+ );+ assert.strictEqual(+ move.proposedToItems.length,+ 4,+ "the destination proposal grew by exactly the arriving row"+ );+ assert.strictEqual(+ move.proposedToItems.findIndex((item) => item.id === "dst-pin"),+ 2,+ "a frozen LAST row keeps visible index 2 when an arrival grows the list, rather than being carried to the new end"+ );+ assert.true(+ move.proposedToItems.some((item) => item.id === "src-a"),+ "and the arrival itself is present in the destination proposal"+ );++ assert.strictEqual(+ renderedItemOrder(".fz-source").indexOf("src-pin"),+ 0,+ "after the host applies the move, the source's frozen row still renders first"+ );+ assert.strictEqual(+ renderedItemOrder(".fz-destination").indexOf("dst-pin"),+ 2,+ "and the destination's frozen row still renders at its original index"+ );+ assert.strictEqual(+ renderedItemOrder(".fz-destination").length,+ 4,+ "with the destination holding all four rows"+ );+ });++ test("supp42618 drag, menu, and chord produce identical results for the same logical move", async function (assert) {+ const makeStore = () => {+ const items = trackedArray(objectItems());+ const store = { items, committed: [] };+ store.onMove = (move) => {+ store.committed.push(move.proposedToItems.map((item) => item.id));+ items.splice(0, items.length, ...move.proposedToItems);+ };+ return store;+ };+ const dragStore = makeStore();+ const menuStore = makeStore();+ const chordStore = makeStore();+ const dragItems = dragStore.items;+ const menuItems = menuStore.items;+ const chordItems = chordStore.items;+ const dragMove = dragStore.onMove;+ const menuMove = menuStore.onMove;+ const chordMove = chordStore.onMove;++ await render(+ <template>+ <DMenus />+ <DReorderableList+ id="agree-drag"+ @items={{dragItems}}+ @key="id"+ @label={{label}}+ @onMove={{dragMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="agree-menu"+ @items={{menuItems}}+ @key="id"+ @label={{label}}+ @onMove={{menuMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="agree-chord"+ @items={{chordItems}}+ @key="id"+ @label={{label}}+ @onMove={{chordMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ // The same logical move — bravo one step down — issued three ways+ // against three identical starting states.+ const dragSource = rowSelector("bravo", "#agree-drag");+ const dragTarget = rowSelector("charlie", "#agree-drag");+ await simulateDrag(dragSource, dragTarget, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(dragTarget, "after"),+ });+ await moveVia("bravo", "down", "#agree-menu");+ await moveViaChord("bravo", "down", "#agree-chord");++ assert.strictEqual(+ dragStore.committed.length,+ 1,+ "the drag committed its move exactly once"+ );+ const agreed = dragStore.committed[0];+ assert.deepEqual(+ menuStore.committed,+ [agreed],+ "the menu path committed once and proposed exactly the order the drag proposed"+ );+ assert.deepEqual(+ chordStore.committed,+ [agreed],+ "the chord path committed once and proposed exactly the order the drag proposed"+ );+ assert.deepEqual(+ renderedItemOrder("#agree-drag"),+ agreed,+ "the drag-driven list renders the agreed order"+ );+ assert.deepEqual(+ renderedItemOrder("#agree-menu"),+ agreed,+ "the menu-driven list renders the agreed order"+ );+ assert.deepEqual(+ renderedItemOrder("#agree-chord"),+ agreed,+ "the chord-driven list renders the agreed order"+ );+ });++ test("supp42618 an in-list announcement names the position the row actually occupies", async function (assert) {+ const { items, applyMove } = listStore(objectItems());+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{applyMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveVia("alpha", "down");++ const menuSpoken = lastSpokenPosition(announce);+ assert.notStrictEqual(+ menuSpoken,+ null,+ "the menu move announced a position at all, so the correspondence is checkable"+ );+ assert.strictEqual(+ renderedItemOrder()[menuSpoken?.position - 1],+ "alpha",+ "the rendered row at the announced menu-move position is the row that moved"+ );+ assert.strictEqual(+ menuSpoken?.total,+ renderedItemOrder().length,+ "and the announced total is the number of rows actually rendered"+ );++ announce.resetHistory();+ await moveViaChord("charlie", "top");++ const chordSpoken = lastSpokenPosition(announce);+ assert.notStrictEqual(+ chordSpoken,+ null,+ "the chord move announced a position at all, so the correspondence is checkable"+ );+ assert.strictEqual(+ renderedItemOrder()[chordSpoken?.position - 1],+ "charlie",+ "the rendered row at the announced chord-move position is the row that moved"+ );+ assert.strictEqual(+ chordSpoken?.total,+ renderedItemOrder().length,+ "and the chord announcement's total matches the rendered row count"+ );+ });++ test("supp42618 a cross-list announcement names the slot the item occupies beside a frozen row", async function (assert) {+ const movable = (item) => item.id !== "an-dst-pin";+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const store = groupStore(+ [+ { id: "an-src-a", name: "An Src A" },+ { id: "an-src-b", name: "An Src B" },+ ],+ [+ { id: "an-dst-a", name: "An Dst A" },+ { id: "an-dst-pin", name: "An Dst Pin" },+ ]+ );+ const storeFirst = store.first;+ const storeSecond = store.second;+ const storeApply = store.applyMove;++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{storeApply}} as |group|>+ <DReorderableList+ class="an-source"+ @group={{group}}+ @items={{storeFirst}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="Announce source"+ @movable={{movable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="an-target"+ @group={{group}}+ @items={{storeSecond}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Announce target"+ @movable={{movable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const source = rowSelector("an-src-a", ".an-source");+ const target = rowSelector("an-dst-a", ".an-target");+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "after"),+ });++ assert.strictEqual(+ store.moves.length,+ 1,+ "the cross-list drop into the frozen-holding destination commits once"+ );+ const spoken = lastSpokenPosition(announce);+ assert.notStrictEqual(+ spoken,+ null,+ "the cross-list move announced a position at all, so the correspondence is checkable"+ );+ assert.strictEqual(+ renderedItemOrder(".an-target")[spoken?.position - 1],+ "an-src-a",+ "the rendered destination row at the announced position is the item that arrived, even with a frozen row holding a slot it might naively have been given"+ );+ assert.strictEqual(+ spoken?.total,+ renderedItemOrder(".an-target").length,+ "and the announced total is the destination's actual rendered row count"+ );+ });++ test("supp42618 the announced position stays truthful among equal primitive values", async function (assert) {+ const { items, moves, applyMove } = listStore([+ "Alpha",+ "Bravo",+ "Alpha",+ ]);+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key={{INDEX_KEY}}+ @label={{label}}+ @onMove={{applyMove}}+ >+ <:row as |item|>+ <span data-test-item={{item}}>{{item}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveVia("0", "down");++ assert.strictEqual(+ moves.length,+ 1,+ "moving one of two equal values commits exactly once"+ );+ const spoken = lastSpokenPosition(announce);+ assert.notStrictEqual(+ spoken,+ null,+ "the move among duplicates announced a position at all, so the correspondence is checkable"+ );+ assert.strictEqual(+ spoken?.position,+ moves[0].toIndex + 1,+ "the announced position is the committed landing index, not the slot of the other equal value"+ );+ assert.strictEqual(+ renderedItemOrder()[spoken?.position - 1],+ "Alpha",+ "and the rendered row at the announced position holds the moved value"+ );+ assert.deepEqual(+ multiset([items]),+ { Alpha: 2, Bravo: 1 },+ "with both equal values surviving the move, neither merged nor duplicated"+ );+ });++ test("supp42618 a refused boundary chord leaves the order alone and says so", async function (assert) {+ const store = listStore(objectItems());+ const items = store.items;+ const apply = store.applyMove;+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{apply}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveViaChord("charlie", "down");++ assert.strictEqual(+ store.moves.length,+ 0,+ "the boundary refusal commits nothing"+ );+ assert.deepEqual(+ renderedItemOrder(),+ ["alpha", "bravo", "charlie"],+ "and the rendered order is untouched"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "yet the explicit command was answered exactly once"+ );+ const spokenText = String(announce.firstCall.args[0]);+ assert.true(spokenText.length > 0, "with a non-empty explanation");+ assert.true(+ spokenText.includes("Charlie"),+ "that names the row the reader tried to move"+ );+ });++ test("supp42618 a spill aimed at a disabled member commits nothing and says so", async function (assert) {+ const first = trackedArray([+ { id: "dis-a", name: "Dis A" },+ { id: "dis-b", name: "Dis B" },+ ]);+ const second = trackedArray([{ id: "dis-c", name: "Dis C" }]);+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ class="dis-first"+ @group={{group}}+ @items={{first}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="Enabled"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="dis-second"+ @disabled={{true}}+ @group={{group}}+ @items={{second}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Disabled"+ @spill={{true}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ await moveViaChord("dis-b", "down", ".dis-first");+ } finally {+ resetOnerror();+ }++ assert.strictEqual(+ raised,+ undefined,+ "spilling toward a disabled member raises no error"+ );+ assert.strictEqual(+ onMove.callCount,+ 0,+ "and commits no move into a list that is read-only"+ );+ assert.deepEqual(+ renderedItemOrder(".dis-first"),+ ["dis-a", "dis-b"],+ "the source order is unchanged"+ );+ assert.deepEqual(+ renderedItemOrder(".dis-second"),+ ["dis-c"],+ "the disabled destination is unchanged"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "yet the refused command is answered exactly once"+ );+ assert.true(+ String(announce.firstCall.args[0]).includes("Dis B"),+ "with an explanation naming the row that could not go"+ );+ });++ test("supp42618 choosing a destination that unmounted mid-menu commits nothing and says so", async function (assert) {+ const firstItems = [+ { id: "st-a", name: "St A" },+ { id: "st-b", name: "St B" },+ ];+ const secondItems = [{ id: "st-c", name: "St C" }];+ const state = new (class {+ @tracked showSecond = true;+ })();+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{onMove}} as |group|>+ <DReorderableList+ class="stale-first"+ @group={{group}}+ @items={{firstItems}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="Stale source"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ {{#if state.showSecond}}+ <DReorderableList+ class="stale-second"+ @group={{group}}+ @items={{secondItems}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Stale target"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ {{/if}}+ </DReorderableListGroup>+ </template>+ );++ await openMoveMenu("st-a", ".stale-first");+ assert+ .dom(moveItemSelector("list"))+ .exists("the destination is offered while its list is mounted");++ state.showSecond = false;+ await settled();++ assert+ .dom(".stale-second")+ .doesNotExist("the destination list is fully unrendered");+ assert+ .dom(moveItemSelector("list"))+ .exists(+ "the already-open menu still shows the destination the reader was considering"+ );++ await click(moveItemSelector("list"));+ } finally {+ resetOnerror();+ }++ assert.strictEqual(+ raised,+ undefined,+ "choosing the stale destination raises no error"+ );+ assert.strictEqual(+ onMove.callCount,+ 0,+ "and commits nothing to a list that no longer exists"+ );+ assert.deepEqual(+ renderedItemOrder(".stale-first"),+ ["st-a", "st-b"],+ "the source order is unchanged"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "yet the explicit command is answered exactly once"+ );+ assert.true(+ String(announce.firstCall.args[0]).length > 0,+ "with a non-empty explanation rather than silence"+ );+ });++ test("supp42618 focus stays inside the surface after in-list and cross-list commits", async function (assert) {+ const store = groupStore(+ [+ { id: "mf-a", name: "Mf A" },+ { id: "mf-b", name: "Mf B" },+ ],+ [+ { id: "mf-pin", name: "Mf Pin" },+ { id: "mf-c", name: "Mf C" },+ ]+ );+ const storeFirst = store.first;+ const storeSecond = store.second;+ const storeApply = store.applyMove;+ const movable = (item) => item.id !== "mf-pin";++ await render(+ <template>+ <DMenus />+ <div id="move-focus-arena">+ <DReorderableListGroup @onMove={{storeApply}} as |group|>+ <DReorderableList+ class="mf-first"+ @group={{group}}+ @items={{storeFirst}}+ @key="id"+ @label={{label}}+ @listId="first"+ @listLabel="Focus first"+ @movable={{movable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="mf-second"+ @group={{group}}+ @items={{storeSecond}}+ @key="id"+ @label={{label}}+ @listId="second"+ @listLabel="Focus second"+ @movable={{movable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </div>+ </template>+ );++ const arena = find("#move-focus-arena");++ await moveViaChord("mf-a", "down", ".mf-first");++ assert.strictEqual(store.moves.length, 1, "the in-list chord committed");+ assert.notStrictEqual(+ document.activeElement,+ document.body,+ "an in-list commit does not dump focus onto the body"+ );+ assert.true(+ arena.contains(document.activeElement),+ "focus is still somewhere inside the reordering surface after the in-list move"+ );++ await moveVia("mf-a", "list", ".mf-first");++ assert.strictEqual(+ store.moves.length,+ 2,+ "the cross-list menu move committed"+ );+ assert.strictEqual(+ renderedItemOrder(".mf-second").indexOf("mf-pin"),+ 0,+ "the destination's frozen first row still holds index 0 after the arrival"+ );+ assert.notStrictEqual(+ document.activeElement,+ document.body,+ "a cross-list commit into a frozen-first list does not dump focus onto the body"+ );+ assert.true(+ arena.contains(document.activeElement),+ "focus is still somewhere inside the reordering surface after the cross-list move"+ );+ });++ test("supp42618 focus stays inside the list as removals empty it", async function (assert) {+ const state = new (class {+ @tracked+ items = [+ { id: "rm-pin", name: "Rm Pin" },+ { id: "rm-a", name: "Rm A" },+ { id: "rm-b", name: "Rm B" },+ ];+ })();+ const movable = (item) => item.id !== "rm-pin";+ const removable = (item) => item.id !== "rm-pin";+ const onRemove = (item) => {+ state.items = state.items.filter((candidate) => candidate !== item);+ };++ await render(+ <template>+ <DMenus />+ <div id="remove-focus-arena">+ <DReorderableList+ @items={{state.items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{noop}}+ @onRemove={{onRemove}}+ @removable={{removable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </div>+ </template>+ );++ const arena = find("#remove-focus-arena");++ await click(`${rowSelector("rm-a")} .d-reorderable-list__remove`);++ assert.deepEqual(+ renderedItemOrder(),+ ["rm-pin", "rm-b"],+ "the middle row really went"+ );+ assert.notStrictEqual(+ document.activeElement,+ document.body,+ "removing a middle row does not dump focus onto the body"+ );+ assert.true(+ arena.contains(document.activeElement),+ "focus is still inside the list after the middle removal"+ );++ await click(`${rowSelector("rm-b")} .d-reorderable-list__remove`);++ assert.deepEqual(+ renderedItemOrder(),+ ["rm-pin"],+ "the last removable row really went"+ );+ assert.notStrictEqual(+ document.activeElement,+ document.body,+ "removing the last removable row does not dump focus onto the body"+ );+ assert.true(+ arena.contains(document.activeElement),+ "focus is still inside the list even with no removable rows left to hold it"+ );+ });++ test("supp42618 an index-keyed cross-list move between equal values neither throws nor corrupts", async function (assert) {+ const store = groupStore(["Alpha", "Bravo"], ["Alpha", "Charlie"]);+ const storeFirst = store.first;+ const storeSecond = store.second;+ const storeApply = store.applyMove;+ const initialUnion = multiset([storeFirst, storeSecond]);+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{storeApply}} as |group|>+ <DReorderableList+ class="eq-first"+ @group={{group}}+ @items={{storeFirst}}+ @key={{INDEX_KEY}}+ @label={{label}}+ @listId="first"+ @listLabel="Eq first"+ >+ <:row as |item|>+ <span data-test-item={{item}}>{{item}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ class="eq-second"+ @group={{group}}+ @items={{storeSecond}}+ @key={{INDEX_KEY}}+ @label={{label}}+ @listId="second"+ @listLabel="Eq second"+ >+ <:row as |item|>+ <span data-test-item={{item}}>{{item}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ const source = rowSelector("0", ".eq-first");+ const target = rowSelector("1", ".eq-second");+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "before"),+ });+ } finally {+ resetOnerror();+ }++ assert.strictEqual(+ raised,+ undefined,+ "dragging an index-keyed value into a list holding an equal value raises no error"+ );+ assert.true(+ store.moves.length <= 1,+ "at most the one commanded move commits, never a cascade"+ );+ assert.deepEqual(+ multiset([storeFirst, storeSecond]),+ initialUnion,+ "the live stores still hold exactly the original values, so the equal values neither merged nor duplicated"+ );+ assert.deepEqual(+ multiset([+ renderedItemOrder(".eq-first"),+ renderedItemOrder(".eq-second"),+ ]),+ initialUnion,+ "and the rendered rows across both lists are the same multiset the page started with"+ );+ for (const committed of store.moves) {+ assertConserved(+ assert,+ committed,+ "index-keyed cross-list move between equal values"+ );+ assert.strictEqual(+ committed.item,+ "Alpha",+ "the committed move resolved the dragged duplicate's value, not some other row"+ );+ }+ });++ test("supp42618 replacing the items under an open menu neither throws nor commits", async function (assert) {+ const state = new (class {+ @tracked items = objectItems();+ })();+ const replacement = [+ { id: "rep-a", name: "Rep A" },+ { id: "rep-b", name: "Rep B" },+ ];+ const onMove = sinon.spy();+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{state.items}}+ @key="id"+ @label={{label}}+ @onMove={{onMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await openMoveMenu("bravo");+ assert+ .dom(moveItemSelector("up"))+ .exists("the menu opened over the row before the swap");++ state.items = replacement;+ await settled();++ // The component may close the stale menu itself or leave it to be+ // chosen; either way choosing must not commit against the old items.+ const staleDestination = find(moveItemSelector("up"));+ if (staleDestination) {+ await click(staleDestination);+ }+ } finally {+ resetOnerror();+ }++ assert.strictEqual(+ raised,+ undefined,+ "swapping the whole collection under an open menu raises no error"+ );+ assert.strictEqual(+ onMove.callCount,+ 0,+ "and no move commits for a row that no longer exists"+ );+ assert.deepEqual(+ renderedItemOrder(),+ ["rep-a", "rep-b"],+ "the list renders the replacement collection intact"+ );+ });+ }+);diff --git a/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-test.gjsnew file mode 100644index 00000000000..b1351411b3b--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/d-reorderable-list-test.gjs@@ -0,0 +1,2530 @@+import { tracked } from "@glimmer/tracking";+import { trackedArray } from "@ember/reactive/collections";+import {+ click,+ fillIn,+ find,+ findAll,+ render,+ resetOnerror,+ settled,+ setupOnerror,+ triggerKeyEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import DMenus from "discourse/float-kit/components/d-menus";+import loadAccessibleName from "discourse/lib/load-accessible-name";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import {+ centerOf,+ dragEvent,+ dragOver,+ simulateDrag,+ simulateUntargetedDrag,+ startDrag,+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";+import {+ assertDragReady,+ dropCoordinates,+ label,+ List,+ MENU_SELECTOR,+ noop,+ objectItems,+ renderedItemOrder,+} from "discourse/tests/helpers/ui-kit/reorderable-list-fixtures";+import {+ handleSelector,+ moveItemSelector,+ moveVia,+ openMoveMenu,+ rowSelector,+} from "discourse/tests/helpers/ui-kit/reorderable-list-helper";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import DReorderableListGroup from "discourse/ui-kit/d-reorderable-list-group";++module("Integration | ui-kit | DReorderableList", function (hooks) {+ setupRenderingTest(hooks);++ test("renders the default shell, rows, controls, labels, and row metadata", async function (assert) {+ const items = objectItems();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="identity.value"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item controls|>+ <span+ class="row-content"+ data-first={{if controls.isFirst "true" "false"}}+ data-index={{controls.index}}+ data-last={{if controls.isLast "true" "false"}}+ data-movable={{if controls.movable "true" "false"}}+ data-test-item={{item.id}}+ >{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom("ul.d-reorderable-list")+ .exists({ count: 1 }, "the default root is one unordered list")+ .doesNotHaveClass(+ "--reveal-controls",+ "controls are always visible by default"+ );+ assert+ .dom(".d-reorderable-list__row")+ .exists(+ { count: items.length },+ "one default list item renders per item"+ );++ for (const [index, item] of items.entries()) {+ const key = item.identity.value;+ const row = rowSelector(key);+ const itemLabel = label(item);++ assert+ .dom(row)+ .hasTagName("li", `the row for ${itemLabel} uses the default item tag`)+ .hasClass(+ "d-reorderable-list__row",+ `the row for ${itemLabel} has the row class`+ );+ assert+ .dom(handleSelector(key))+ .hasTagName("button", `${itemLabel}'s handle is a real control`)+ .hasAria(+ "label",+ `Reorder ${itemLabel}`,+ `${itemLabel}'s handle names the row it moves`+ )+ .hasAttribute(+ "title",+ `Reorder ${itemLabel}`,+ `${itemLabel}'s handle tooltip names the item`+ );+ assert+ .dom(`${row} [data-test-item="${item.id}"]`)+ .hasAttribute(+ "data-index",+ String(index),+ `${itemLabel} yields its visible index`+ )+ .hasAttribute(+ "data-first",+ String(index === 0),+ `${itemLabel} yields its first-movable state`+ )+ .hasAttribute(+ "data-last",+ String(index === items.length - 1),+ `${itemLabel} yields its last-movable state`+ )+ .hasAttribute(+ "data-movable",+ "true",+ `${itemLabel} is movable by default`+ );+ }++ const firstRowChildren = Array.from(+ find(rowSelector(items[0].identity.value)).children+ );+ assert.strictEqual(+ firstRowChildren.length,+ 2,+ "a row is its one control plus its content, nothing else"+ );+ assert+ .dom(firstRowChildren[0])+ .hasClass(+ "d-reorderable-list__handle",+ "the control is the first child, before the row block"+ );+ assert.dom(firstRowChildren[1]).hasClass("row-content");+ });++ test("renders the header block before every row", async function (assert) {+ const items = objectItems().slice(0, 2);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:header><li data-slot="header">Header</li></:header>+ <:row as |item|><span+ data-test-item={{item.id}}+ >{{item.name}}</span></:row>+ </DReorderableList>+ </template>+ );++ assert.dom(".d-reorderable-list").exists("the list root renders");+ assert.deepEqual(+ Array.from(find(".d-reorderable-list").children).map(+ (element) => element.dataset.slot ?? element.dataset.reorderableKey+ ),+ ["header", ...items.map((item) => item.id)],+ "the header precedes every row"+ );+ });++ test("renders the empty block in the rows position", async function (assert) {+ const items = [];++ await render(+ <template>+ <DMenus />+ <DReorderableList @items={{items}} @label={{label}} @onMove={{noop}}>+ <:header><li data-slot="header">Header</li></:header>+ <:row as |item|><span data-test-item={{item}}>{{item}}</span></:row>+ <:empty><li data-slot="empty">Nothing here</li></:empty>+ </DReorderableList>+ </template>+ );++ assert.dom(".d-reorderable-list").exists("the empty list root renders");+ assert+ .dom(".d-reorderable-list__row")+ .doesNotExist("an empty collection renders no rows");+ assert.deepEqual(+ Array.from(find(".d-reorderable-list").children).map(+ (element) => element.dataset.slot+ ),+ ["header", "empty"],+ "the empty block replaces the rows after the header"+ );+ });++ test("supports custom shell tags, roles, and attributes", async function (assert) {+ const items = objectItems().slice(0, 1);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ class="consumer-list"+ data-consumer="present"+ id="custom-list"+ @itemRole="option"+ @items={{items}}+ @itemTag="article"+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @role="listbox"+ @tag="section"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom("#custom-list")+ .hasTagName("section", "the root uses the requested tag")+ .hasClass("d-reorderable-list", "the root keeps its base class")+ .hasClass("consumer-list", "the root merges the consumer class")+ .hasAttribute("role", "listbox", "the root receives the requested role")+ .hasAttribute(+ "data-consumer",+ "present",+ "attributes pass through to the root"+ );+ assert+ .dom("#custom-list > .d-reorderable-list__row")+ .hasTagName("article", "rows use the requested item tag")+ .hasAttribute("role", "option", "rows receive the requested item role");+ });++ test("applies string and callback row classes", async function (assert) {+ const items = objectItems().slice(0, 2);+ const seen = new Map();+ const movable = (item) => item.id !== items[1].id;+ const rowClass = (item, row) => {+ seen.set(item.id, { ...row });+ return `row-${row.index} ${row.movable ? "--can-move" : "--fixed"}`;+ };++ await render(+ <template>+ <DMenus />+ <DReorderableList+ id="string-classes"+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @rowClass="string-one string-two"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="callback-classes"+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{noop}}+ @rowClass={{rowClass}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom("#string-classes > .d-reorderable-list__row")+ .hasClass("string-one", "a string row class is applied")+ .hasClass("string-two", "multiple string classes are preserved");+ assert+ .dom(rowSelector(items[0].id, "#callback-classes"))+ .hasClass("row-0", "the callback receives the first visible index")+ .hasClass("--can-move", "the callback receives the movable state");+ assert+ .dom(rowSelector(items[1].id, "#callback-classes"))+ .hasClass("row-1", "the callback receives the second visible index")+ .hasClass("--fixed", "the callback receives the frozen state");+ assert.deepEqual(+ seen.get(items[1].id),+ { index: 1, movable: false },+ "the callback context contains exactly index and movable"+ );+ });++ test("a row without a handle lines its content up with rows that have one", async function (assert) {+ const items = objectItems().slice(0, 3);+ const movable = (item) => item.id !== items[2].id;+ const contentLeft = (item) =>+ find(`[data-test-item="${item.id}"]`).getBoundingClientRect().left;++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(handleSelector(items[2].id))+ .doesNotExist("the frozen row renders no handle");+ assert.strictEqual(+ contentLeft(items[2]),+ contentLeft(items[0]),+ "the frozen row's content starts where a handled row's content does"+ );+ assert+ .dom(`${rowSelector(items[2].id)} :is(button, [tabindex])`)+ .doesNotExist("the reserved space adds nothing to the tab sequence");+ });++ test("rows reserve no handle space when no row in the list has a handle", async function (assert) {+ const items = objectItems().slice(0, 2);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @disabled={{true}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert.strictEqual(+ find(`[data-test-item="${items[0].id}"]`).getBoundingClientRect().left,+ find(rowSelector(items[0].id)).getBoundingClientRect().left,+ "the content starts at the row's own edge"+ );+ });++ test("a manual list leaves handle spacing to the consumer", async function (assert) {+ const items = objectItems().slice(0, 3);+ const movable = (item) => item.id !== items[2].id;++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @controls="manual"+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{noop}}+ >+ <:row as |item controls|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ {{#if controls.handle}}<controls.handle />{{/if}}+ </:row>+ </DReorderableList>+ </template>+ );++ assert.strictEqual(+ find(`[data-test-item="${items[2].id}"]`).getBoundingClientRect().left,+ find(rowSelector(items[2].id)).getBoundingClientRect().left,+ "the frozen manual row's content starts at the row's own edge"+ );+ });++ test("a manual row places its own handle wherever it belongs", async function (assert) {+ const items = objectItems().slice(0, 2);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @controls="manual"+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item controls|>+ <span class="row-content" data-test-item={{item.id}}>+ {{item.name}}+ </span>+ <controls.handle />+ </:row>+ </DReorderableList>+ </template>+ );++ const children = Array.from(find(rowSelector(items[0].id)).children);+ assert.strictEqual(children.length, 2);+ assert.dom(children[0]).hasClass("row-content");+ assert+ .dom(children[1])+ .hasClass(+ "d-reorderable-list__handle",+ "a handle placed after the block sits after it in the DOM, so reading and focus order follow the layout"+ );+ });++ test("disabled removes every control and drag registration", async function (assert) {+ const items = objectItems();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @disabled={{true}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(".d-reorderable-list__row")+ .exists({ count: items.length }, "disabled lists still render every row");+ assert+ .dom(".d-reorderable-list__handle")+ .doesNotExist("disabled lists render no handles");+ assert+ .dom(".d-reorderable-list [data-drag-source]")+ .doesNotExist("disabled lists register no drag sources");+ assert+ .dom(".d-reorderable-list [data-drop-target]")+ .doesNotExist("disabled lists register no drop targets");+ assert+ .dom(".d-reorderable-list [draggable]")+ .doesNotExist("disabled lists expose no draggable element");+ });++ test("frozen rows have no controls or drag targets and arrow moves hop over them", async function (assert) {+ const items = objectItems();+ const frozen = items[1];+ const movable = (item) => item !== frozen;+ const moves = [];+ const onMove = (move) => moves.push(move);+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{onMove}}+ >+ <:row as |item controls|>+ <span+ data-movable={{if controls.movable "true" "false"}}+ data-test-item={{item.id}}+ >{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ const frozenRow = rowSelector(frozen.id);+ assert+ .dom(`${frozenRow} .d-reorderable-list__handle`)+ .doesNotExist("a frozen row has no handle");+ assert+ .dom(frozenRow)+ .doesNotHaveAttribute("data-drop-target", "a frozen row refuses drops");+ assert+ .dom(`${frozenRow} [data-drag-source]`)+ .doesNotExist("a frozen row is not a drag source");++ await moveVia(items[0].id, "down");++ assert.strictEqual(moves.length, 1, "one chosen move commits once");+ assert.strictEqual(+ moves[0].fromIndex,+ 0,+ "the move starts at the first visible index"+ );+ assert.strictEqual(+ moves[0].toIndex,+ 2,+ "the move lands at the next movable visible index"+ );+ assert.deepEqual(+ moves[0].proposedToItems,+ [items[2], frozen, items[0]],+ "the movable rows trade places while the frozen row keeps its visible index"+ );+ assert.strictEqual(announce.callCount, 1, "the real hop announces once");++ const source = rowSelector(items[2].id);+ assert+ .dom(source)+ .hasAttribute(+ "data-drag-source",+ "",+ "a movable row remains registered as a drag source"+ );+ assert+ .dom(source)+ .hasAttribute(+ "data-drop-target",+ "",+ "and as a drop target, so a drag between two movable rows is wired"+ );+ await simulateUntargetedDrag(source, frozenRow, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(frozenRow, "before"),+ });++ assert.strictEqual(+ moves.length,+ 1,+ "dropping on a frozen row commits no move"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "dropping on a frozen row adds no announcement"+ );+ });++ test("argument changes after the first render are picked up", async function (assert) {+ // Every one of these is read lazily today. A collaborator that captured+ // one at construction would still pass every other test in this file,+ // because nothing else swaps an argument after the first render.+ const items = trackedArray(objectItems());+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ const state = new (class {+ @tracked movable = () => true;+ @tracked removable = () => true;+ @tracked itemLabel = label;+ })();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{state.itemLabel}}+ @movable={{state.movable}}+ @onMove={{noop}}+ @onRemove={{noop}}+ @removable={{state.removable}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert.dom(".d-reorderable-list__handle").exists({ count: 3 });+ assert.dom(".d-reorderable-list__remove").exists({ count: 3 });++ state.movable = (item) => item.id !== "bravo";+ await settled();+ assert+ .dom(handleSelector("bravo"))+ .doesNotExist("a swapped @movable re-freezes the row");+ assert.dom(".d-reorderable-list__handle").exists({ count: 2 });++ state.removable = (item) => item.id !== "charlie";+ await settled();+ assert+ .dom(`${rowSelector("charlie")} .d-reorderable-list__remove`)+ .doesNotExist("a swapped @removable withdraws the control");++ state.itemLabel = (item) => `Renamed ${item.name}`;+ await settled();+ await moveVia("alpha", "down");+ assert.true(+ announce.lastCall.args[0].includes("Renamed Alpha"),+ "the announcement reads through the swapped @label rather than a captured one"+ );+ });++ test("lets a consumer choose the remove control's button weight", async function (assert) {+ const items = objectItems();+ const state = new (class {+ @tracked buttonClass;+ })();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @onRemove={{noop}}+ @removeButtonClass={{state.buttonClass}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(".d-reorderable-list__remove")+ .hasClass("btn-flat", "falls back to a flat control");++ state.buttonClass = "btn-default";+ await settled();++ assert+ .dom(".d-reorderable-list__remove")+ .hasClass("btn-default", "takes the weight the consumer asked for");+ assert+ .dom(".d-reorderable-list__remove")+ .doesNotHaveClass(+ "btn-flat",+ "and drops the default rather than merging"+ );+ });++ test("offers only the reachable directions in the movable subsequence", async function (assert) {+ const items = objectItems();+ const movable = (item) => item !== items[1];++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await openMoveMenu(items[0].id);+ assert+ .dom(moveItemSelector("up"))+ .doesNotExist("the first movable item cannot move up");+ assert+ .dom(moveItemSelector("down"))+ .exists("the first movable item can move down");+ await click(moveItemSelector("down"));++ await openMoveMenu(items[2].id);+ assert+ .dom(moveItemSelector("up"))+ .exists("the last movable item can move up");+ assert+ .dom(moveItemSelector("down"))+ .doesNotExist("the last movable item cannot move down");+ });++ test("menu moves emit the exact move payload and one default announcement", async function (assert) {+ const items = objectItems();+ const moves = [];+ const onMove = (move) => moves.push(move);+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template><List @items={{items}} @onMove={{onMove}} /></template>+ );++ await moveVia(items[1].id, "up");++ const proposed = [items[1], items[0], items[2]];+ assert.strictEqual(+ moves.length,+ 1,+ "one menu choice calls onMove exactly once"+ );+ assert.deepEqual(+ moves[0],+ {+ method: "menu",+ item: items[1],+ fromList: "default",+ toList: "default",+ fromIndex: 1,+ toIndex: 0,+ fromItems: items,+ toItems: items,+ proposedFromItems: proposed,+ proposedToItems: proposed,+ },+ "the button path emits only the complete public move shape"+ );+ assert.strictEqual(+ moves[0].fromItems,+ moves[0].toItems,+ "single-list source arrays share one reference"+ );+ assert.strictEqual(+ moves[0].proposedFromItems,+ moves[0].proposedToItems,+ "single-list proposed arrays share one reference"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the real move announces exactly once"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ `Moved ${label(items[1])} to position ${moves[0].toIndex + 1} of ${proposed.length}`,+ "the default announcement names the item and its measured destination"+ );+ });++ test("a trackedArray host reorders once, rerenders, announces once, and retains focus", async function (assert) {+ const sourceItems = objectItems();+ const items = trackedArray(sourceItems);+ let moveCount = 0;+ const onMove = (move) => {+ moveCount++;+ items.splice(0, items.length, ...move.proposedToItems);+ };+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template><List @items={{items}} @onMove={{onMove}} /></template>+ );++ await moveVia(sourceItems[1].id, "down");++ const expectedOrder = [sourceItems[0], sourceItems[2], sourceItems[1]];+ assert.strictEqual(+ moveCount,+ 1,+ "the tracked host receives one callback without re-entry"+ );+ assert.deepEqual(+ Array.from(items),+ expectedOrder,+ "the host adopts the proposed order"+ );+ assert.deepEqual(+ renderedItemOrder(),+ expectedOrder.map((item) => item.id),+ "the component rerenders the tracked array in its new order"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the host-driven rerender does not double-announce"+ );+ assert+ .dom(handleSelector(sourceItems[1].id))+ .isFocused("the handle regains focus after its keyed row moves");+ });++ test("an onMove false return vetoes the announcement", async function (assert) {+ const items = objectItems();+ const onMove = sinon.stub().returns(false);+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template><List @items={{items}} @onMove={{onMove}} /></template>+ );++ await moveVia(items[1].id, "up");++ assert.strictEqual(+ onMove.callCount,+ 1,+ "the vetoing callback still receives the move"+ );+ assert.strictEqual(announce.callCount, 0, "a vetoed move is not announced");+ });++ test("announceMove overrides the default announcement", async function (assert) {+ const items = objectItems();+ let announcedMove;+ let committedMove;+ const onMove = (move) => (committedMove = move);+ const customMessage = `Custom move for ${label(items[1])}`;+ const announceMove = (move) => {+ announcedMove = move;+ return customMessage;+ };+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @announceMove={{announceMove}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{onMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveVia(items[1].id, "up");++ assert.strictEqual(+ announcedMove,+ committedMove,+ "the override receives the committed move object"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the override still produces one announcement"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ customMessage,+ "the override supplies the spoken text"+ );+ });++ test("announceMove false suppresses only the announcement", async function (assert) {+ const items = objectItems();+ const onMove = sinon.spy();+ const announceMove = sinon.stub().returns(false);+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @announceMove={{announceMove}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{onMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveVia(items[1].id, "up");++ assert.strictEqual(+ onMove.callCount,+ 1,+ "onMove still receives the real move"+ );+ assert.strictEqual(+ announceMove.callCount,+ 1,+ "the announcement override evaluates once"+ );+ assert.strictEqual(+ announce.callCount,+ 0,+ "false suppresses the a11y service call"+ );+ });++ test("a before drop emits the exact drag payload and one announcement", async function (assert) {+ const items = objectItems();+ const moves = [];+ const onMove = (move) => moves.push(move);+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template><List @items={{items}} @onMove={{onMove}} /></template>+ );++ const source = rowSelector(items[0].id);+ const target = rowSelector(items[2].id);+ assertDragReady(assert, source, target);+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "before"),+ });++ const proposed = [items[1], items[0], items[2]];+ assert.strictEqual(+ moves.length,+ 1,+ "one before drop calls onMove exactly once"+ );+ assert.deepEqual(+ moves[0],+ {+ method: "drag",+ item: items[0],+ fromList: "default",+ toList: "default",+ fromIndex: 0,+ toIndex: 1,+ fromItems: items,+ toItems: items,+ proposedFromItems: proposed,+ proposedToItems: proposed,+ },+ "the drag path emits only the complete public move shape"+ );+ assert.strictEqual(+ moves[0].fromItems,+ moves[0].toItems,+ "single-list drag arrays share one reference"+ );+ assert.strictEqual(+ moves[0].proposedFromItems,+ moves[0].proposedToItems,+ "single-list proposed drag arrays share one reference"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the real drop announces exactly once"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ `Moved ${label(items[0])} to position ${moves[0].toIndex + 1} of ${proposed.length}`,+ "the drag announcement uses the normalized destination"+ );+ });++ test("an after drop normalizes to the post-removal destination", async function (assert) {+ const items = objectItems();+ const moves = [];+ const onMove = (move) => moves.push(move);++ await render(+ <template><List @items={{items}} @onMove={{onMove}} /></template>+ );++ const source = rowSelector(items[2].id);+ const target = rowSelector(items[0].id);+ assertDragReady(assert, source, target);+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "after"),+ });++ assert.strictEqual(moves.length, 1, "one after drop commits once");+ assert.deepEqual(+ {+ fromIndex: moves[0].fromIndex,+ toIndex: moves[0].toIndex,+ proposed: moves[0].proposedToItems,+ },+ { fromIndex: 2, toIndex: 1, proposed: [items[0], items[2], items[1]] },+ "after means target index plus one before removal normalization"+ );+ });++ test("a same-index drop is a no-op", async function (assert) {+ const items = objectItems();+ const onMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template><List @items={{items}} @onMove={{onMove}} /></template>+ );++ const source = rowSelector(items[0].id);+ const target = rowSelector(items[1].id);+ assertDragReady(assert, source, target);+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "before"),+ });++ assert.strictEqual(+ onMove.callCount,+ 0,+ "a normalized same-index drop does not call onMove"+ );+ assert.strictEqual(+ announce.callCount,+ 0,+ "a normalized same-index drop is not announced"+ );+ });++ test("drag keys resolve the current item and indices at drop time", async function (assert) {+ const initialItems = objectItems();+ const currentItems = [+ { ...initialItems[2], name: `${initialItems[2].name} current` },+ { ...initialItems[0], name: `${initialItems[0].name} current` },+ { ...initialItems[1], name: `${initialItems[1].name} current` },+ ];+ const state = new (class {+ @tracked items = initialItems;+ })();+ const moves = [];+ const onMove = (move) => moves.push(move);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{state.items}}+ @key="id"+ @label={{label}}+ @onMove={{onMove}}+ >+ <:row as |item|><span+ data-test-item={{item.id}}+ >{{item.name}}</span></:row>+ </DReorderableList>+ </template>+ );++ const draggedKey = initialItems[1].id;+ const sourceHandle = `${rowSelector(draggedKey)} .d-reorderable-list__handle`;+ const dataTransfer = new DataTransfer();+ assert+ .dom(rowSelector(draggedKey))+ .hasAttribute(+ "data-drag-source",+ "",+ "the keyed source handle is registered before the drag starts"+ );+ await dragEvent(sourceHandle, "dragstart", {+ dataTransfer,+ ...centerOf(sourceHandle),+ });+ assert+ .dom(rowSelector(draggedKey))+ .hasClass(+ "--dragging",+ "the primitive marks the dragged row, so no state is mirrored by hand"+ );++ state.items = currentItems;+ await settled();++ const target = rowSelector(initialItems[0].id);+ assert+ .dom(target)+ .hasAttribute(+ "data-drop-target",+ "",+ "the current target row remains registered after the host rerenders"+ );+ const targetCoordinates = dropCoordinates(target, "before");+ await dragEvent(target, "dragenter", {+ dataTransfer,+ ...targetCoordinates,+ });+ await dragEvent(target, "dragover", { dataTransfer, ...targetCoordinates });+ await dragEvent(target, "drop", { dataTransfer, ...targetCoordinates });++ const currentSourceHandle = `${rowSelector(draggedKey)} .d-reorderable-list__handle`;+ await dragEvent(currentSourceHandle, "dragend", {+ dataTransfer,+ ...centerOf(currentSourceHandle),+ });+ assert+ .dom(rowSelector(draggedKey))+ .doesNotHaveClass(+ "--dragging",+ "the source clears its drag state at the end"+ );++ assert.strictEqual(+ moves.length,+ 1,+ "the in-flight drag commits once after the host changes"+ );+ assert.strictEqual(+ moves[0].item,+ currentItems[2],+ "the key resolves to the replacement item object"+ );+ assert.strictEqual(+ moves[0].fromItems,+ currentItems,+ "the payload uses the current visible array"+ );+ assert.deepEqual(+ {+ fromIndex: moves[0].fromIndex,+ toIndex: moves[0].toIndex,+ proposed: moves[0].proposedToItems,+ },+ {+ fromIndex: 2,+ toIndex: 1,+ proposed: [currentItems[0], currentItems[2], currentItems[1]],+ },+ "indices and proposed order resolve against the current items at drop time"+ );+ });++ test("separate instances reject each other's drags", async function (assert) {+ const firstItems = objectItems().slice(0, 2);+ const secondItems = objectItems().slice(1);+ const firstOnMove = sinon.spy();+ const secondOnMove = sinon.spy();+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ id="first-list"+ @items={{firstItems}}+ @key="id"+ @label={{label}}+ @onMove={{firstOnMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="second-list"+ @items={{secondItems}}+ @key="id"+ @label={{label}}+ @onMove={{secondOnMove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ const source = rowSelector(firstItems[0].id, "#first-list");+ const target = rowSelector(secondItems[1].id, "#second-list");+ assertDragReady(assert, source, target);+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "before"),+ });++ assert.strictEqual(+ firstOnMove.callCount,+ 0,+ "the source instance does not receive a cross-list move"+ );+ assert.strictEqual(+ secondOnMove.callCount,+ 0,+ "the target instance rejects the foreign drag type"+ );+ assert.strictEqual(+ announce.callCount,+ 0,+ "a rejected cross-instance drag is not announced"+ );+ });++ test("rejects duplicate resolved keys", async function (assert) {+ const items = objectItems();+ items[1].id = items[0].id;+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.name}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );+ } finally {+ resetOnerror();+ }++ assert.true(+ /duplicate|unique|key/i.test(raised?.message ?? ""),+ "duplicate resolved keys trigger a development assertion"+ );+ });++ test("supports @index identity for primitive collections", async function (assert) {+ const items = ["Alpha", "Bravo", "Charlie"];+ const indexKey = "@index";++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key={{indexKey}}+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item}}>{{item}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert.deepEqual(+ findAll(".d-reorderable-list__row").map(+ (element) => element.dataset.reorderableKey+ ),+ items.map((_, index) => String(index)),+ "@index resolves primitive row identities from their visible indices"+ );+ assert.deepEqual(+ renderedItemOrder(),+ items,+ "primitive row content stays in display order"+ );+ });++ test("uses object identity for keyed rerendering when key is omitted", async function (assert) {+ const items = objectItems();+ const state = new (class {+ @tracked items = items;+ })();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{state.items}}+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(".d-reorderable-list__row")+ .exists(+ { count: items.length },+ "every object renders a row before identity is inspected"+ );+ const keys = findAll(".d-reorderable-list__row").map(+ (element) => element.dataset.reorderableKey+ );+ const firstRow = find("[data-test-item='alpha']").closest(+ ".d-reorderable-list__row"+ );++ assert.true(+ keys.every(Boolean),+ "object identity produces a DOM key for every row"+ );+ assert.strictEqual(+ new Set(keys).size,+ items.length,+ "distinct objects resolve distinct DOM keys"+ );++ state.items = [...items].reverse();+ await settled();++ assert.deepEqual(+ renderedItemOrder(),+ [...items].reverse().map((item) => item.id),+ "the rows follow the reordered object collection"+ );+ assert.strictEqual(+ find("[data-test-item='alpha']").closest(".d-reorderable-list__row"),+ firstRow,+ "the row element follows its object identity across the rerender"+ );+ });+});++module(+ "Integration | ui-kit | DReorderableList | manual controls and create",+ function (hooks) {+ setupRenderingTest(hooks);++ test("manual mode renders no automatic controls", async function (assert) {+ const items = objectItems();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @controls="manual"+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item controls|>+ <span class="row-content" data-test-item={{item.id}}>+ {{item.name}}+ </span>+ {{#if controls.handle}}+ <div class="consumer-control-cell"><controls.handle /></div>+ {{/if}}+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(".d-reorderable-list__row > .d-reorderable-list__handle")+ .doesNotExist("manual mode inserts no handle beside the row block");+ assert+ .dom(".row-content")+ .exists(+ { count: items.length },+ "every row block still renders when controls are manual"+ );+ });++ test("manual row API exposes controls only for movable manual rows", async function (assert) {+ const items = objectItems();+ const movable = (item) => item !== items[1];++ await render(+ <template>+ <DMenus />+ <DReorderableList+ id="manual-api"+ @controls="manual"+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{noop}}+ >+ <:row as |item controls|>+ <span+ data-handle={{if controls.handle "true" "false"}}+ data-test-item={{item.id}}+ >{{item.name}}</span>+ {{#if controls.handle}}<controls.handle />{{/if}}+ </:row>+ </DReorderableList>++ <DReorderableList+ id="auto-api"+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item controls|><span+ data-handle={{if controls.handle "true" "false"}}+ data-test-item={{item.id}}+ >{{item.name}}</span></:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(`${rowSelector(items[0].id, "#manual-api")} [data-test-item]`)+ .hasAttribute(+ "data-handle",+ "true",+ "a movable manual row yields a handle"+ );+ assert+ .dom(`${rowSelector(items[1].id, "#manual-api")} [data-test-item]`)+ .hasAttribute(+ "data-handle",+ "false",+ "a frozen manual row yields no handle"+ );++ for (const root of ["#auto-api"]) {+ assert+ .dom(`${root} [data-test-item]`)+ .hasAttribute(+ "data-handle",+ "false",+ `${root} rows do not yield a manual handle`+ );+ }+ });++ test("a lone movable row still yields a handle the consumer can render", async function (assert) {+ const items = [{ id: "alpha", name: "Alpha" }];++ await render(+ <template>+ <DMenus />+ <DReorderableList+ id="lone-manual"+ @controls="manual"+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item controls|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ <controls.handle />+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom("#lone-manual [data-test-item]")+ .exists(+ "the row renders rather than the block failing on an absent control"+ );+ assert+ .dom("#lone-manual .d-reorderable-list__handle")+ .doesNotExist(+ "and the control draws nothing, because a lone row has nowhere to move"+ );+ });++ test("a manually placed handle matches the automatic one", async function (assert) {+ const items = objectItems();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @controls="manual"+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item controls|>+ <div class="consumer-cell" data-test-item={{item.id}}>+ <controls.handle+ class="consumer-handle"+ data-consumer-handle={{item.id}}+ />+ </div>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(".consumer-cell > .d-reorderable-list__handle")+ .exists(+ { count: items.length },+ "one manually placed handle renders inside each nested cell"+ );++ for (const [index, item] of items.entries()) {+ const row = rowSelector(item.id);+ const itemLabel = label(item);++ assert+ .dom(`${row} .consumer-handle`)+ .hasTagName(+ "button",+ `${itemLabel}'s manual handle is a real control`+ )+ .hasClass(+ "d-reorderable-list__handle",+ `${itemLabel}'s manual handle keeps the list class`+ )+ .hasAria(+ "label",+ `Reorder ${itemLabel}`,+ `${itemLabel}'s manual handle uses the standard translated label`+ )+ .hasAttribute(+ "data-consumer-handle",+ item.id,+ `${itemLabel}'s consumer attribute passes through`+ )+ .hasAttribute(+ "draggable",+ "true",+ `${itemLabel}'s manual handle is still where a drag begins`+ );++ await openMoveMenu(item.id);++ const expectAbsent = {+ up: index === 0,+ down: index === items.length - 1,+ };+ for (const [target, absent] of Object.entries(expectAbsent)) {+ if (absent) {+ assert+ .dom(moveItemSelector(target))+ .doesNotExist(+ `${itemLabel}'s manual menu omits ${target} at the boundary`+ );+ } else {+ assert+ .dom(moveItemSelector(target))+ .exists(`${itemLabel}'s manual menu leaves ${target} available`);+ }+ }++ await triggerKeyEvent(document.activeElement, "keydown", "Escape");+ }+ });++ test("manually placed handle commits a normalized drag move", async function (assert) {+ const items = objectItems();+ const sourceItem = items[0];+ const targetItem = items.at(-1);+ const fromIndex = items.indexOf(sourceItem);+ const targetIndex = items.indexOf(targetItem);+ const toIndex = targetIndex - Number(fromIndex < targetIndex);+ const proposed = [...items];+ proposed.splice(fromIndex, 1);+ proposed.splice(toIndex, 0, sourceItem);+ const moves = [];+ const onMove = (move) => moves.push(move);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @controls="manual"+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{onMove}}+ >+ <:row as |item controls|>+ <div data-test-item={{item.id}}>+ <span class="consumer-handle-cell"><controls.handle /></span>+ </div>+ </:row>+ </DReorderableList>+ </template>+ );++ const source = rowSelector(sourceItem.id);+ const target = rowSelector(targetItem.id);+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: dropCoordinates(target, "before"),+ });++ assert.strictEqual(+ moves.length,+ 1,+ "one manual-handle drag commits once"+ );+ assert.deepEqual(+ moves[0],+ {+ method: "drag",+ item: sourceItem,+ fromList: "default",+ toList: "default",+ fromIndex,+ toIndex,+ fromItems: items,+ toItems: items,+ proposedFromItems: proposed,+ proposedToItems: proposed,+ },+ "the nested manual handle emits the complete normalized drag payload"+ );+ });++ test("a handle-only manual surface commits and announces without asserting", async function (assert) {+ const items = objectItems();+ const movedItem = items[1];+ const fromIndex = items.indexOf(movedItem);+ const toIndex = fromIndex - 1;+ const proposed = [...items];+ proposed.splice(fromIndex, 1);+ proposed.splice(toIndex, 0, movedItem);+ const moves = [];+ const onMove = (move) => moves.push(move);+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableList+ @controls="manual"+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{onMove}}+ >+ <:row as |item controls|>+ <div data-test-item={{item.id}}><controls.handle /></div>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveVia(movedItem.id, "up");+ } finally {+ resetOnerror();+ }++ assert.strictEqual(+ raised,+ undefined,+ "the placed handle satisfies the manual guard"+ );+ assert+ .dom(".d-reorderable-list__handle")+ .exists(+ { count: items.length },+ "the handle a manual row places is its only control"+ );+ assert.strictEqual(+ moves.length,+ 1,+ "one manual menu choice commits once"+ );+ assert.deepEqual(+ moves[0],+ {+ method: "menu",+ item: movedItem,+ fromList: "default",+ toList: "default",+ fromIndex,+ toIndex,+ fromItems: items,+ toItems: items,+ proposedFromItems: proposed,+ proposedToItems: proposed,+ },+ "manual arrows emit the complete normalized button payload"+ );+ assert.strictEqual(+ announce.callCount,+ 1,+ "the manual arrow move announces once"+ );+ assert.strictEqual(+ announce.firstCall.args[0],+ `Moved ${label(movedItem)} to position ${moves[0].toIndex + 1} of ${proposed.length}`,+ "manual arrows use the standard measured announcement"+ );+ });++ test("manual mode asserts when a movable row omits its handle", async function (assert) {+ const items = objectItems().slice(0, 2);+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableList+ @controls="manual"+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );+ } finally {+ resetOnerror();+ }++ assert+ .dom("[data-test-item]")+ .exists("the manual row renders before the delayed guard runs");+ assert.true(+ /Assertion Failed:.*handle/i.test(raised?.message ?? ""),+ "a movable row with no handle has no way to reorder, and says so"+ );+ });++ test("allowCreate renders the default create row between rows and static content", async function (assert) {+ const items = objectItems().slice(0, 2);+ const accessibleName = await loadAccessibleName();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @allowCreate={{true}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onCreate={{noop}}+ @onMove={{noop}}+ >+ <:row as |item|><span+ data-test-item={{item.id}}+ >{{item.name}}</span></:row>+ </DReorderableList>+ </template>+ );++ assert.deepEqual(+ Array.from(find(".d-reorderable-list").children).map((element) => {+ if (element.classList.contains("d-reorderable-list__create")) {+ return "create";+ }+ return element.dataset.reorderableKey ?? element.dataset.slot;+ }),+ [...items.map((item) => item.id), "create"],+ "the create row follows every item and precedes static content"+ );+ assert+ .dom(".d-reorderable-list__create")+ .exists({ count: 1 }, "one default create row renders");+ assert+ .dom(".d-reorderable-list__create-input")+ .hasTagName("input", "the default create control is an input");+ assert.strictEqual(+ find(".d-reorderable-list__create-input").type,+ "text",+ "the create input accepts text"+ );+ assert.strictEqual(+ accessibleName(find(".d-reorderable-list__create-input")),+ "Add an item",+ "the create input has the translated accessible name"+ );+ assert+ .dom(".d-reorderable-list__create button")+ .exists({ count: 1 }, "the create row has one icon button");+ assert.strictEqual(+ accessibleName(find(".d-reorderable-list__create button")),+ "Add an item",+ "the create button has the translated accessible name"+ );+ assert+ .dom(".d-reorderable-list__create button .d-icon")+ .exists("the create action is rendered as an icon button");+ });++ test("Enter creates one trimmed value and clears the input while ignoring whitespace", async function (assert) {+ const items = objectItems().slice(0, 1);+ const onCreate = sinon.spy();+ const enteredValue = ` ${items[0].name} draft `;+ const expectedValue = enteredValue.trim();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @allowCreate={{true}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onCreate={{onCreate}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ const input = ".d-reorderable-list__create-input";+ await fillIn(input, enteredValue);+ await triggerKeyEvent(input, "keydown", "Enter");++ assert.strictEqual(+ onCreate.callCount,+ 1,+ "Enter calls onCreate exactly once"+ );+ assert.strictEqual(+ onCreate.firstCall.args[0],+ expectedValue,+ "Enter submits the measured trimmed value"+ );+ assert+ .dom(input)+ .hasValue("", "a successful Enter submission clears the input");++ await fillIn(input, " ");+ await triggerKeyEvent(input, "keydown", "Enter");++ assert.strictEqual(+ onCreate.callCount,+ 1,+ "Enter on whitespace adds no create callback"+ );+ });++ test("create button submits one trimmed value and clears the input while ignoring whitespace", async function (assert) {+ const items = objectItems().slice(0, 1);+ const onCreate = sinon.spy();+ const enteredValue = ` ${items[0].id} copy `;+ const expectedValue = enteredValue.trim();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @allowCreate={{true}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onCreate={{onCreate}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ const input = ".d-reorderable-list__create-input";+ const button = ".d-reorderable-list__create button";+ await fillIn(input, enteredValue);+ await click(button);++ assert.strictEqual(+ onCreate.callCount,+ 1,+ "the create button calls onCreate exactly once"+ );+ assert.strictEqual(+ onCreate.firstCall.args[0],+ expectedValue,+ "the create button submits the measured trimmed value"+ );+ assert+ .dom(input)+ .hasValue("", "a successful button submission clears the input");++ await fillIn(input, "\t ");+ await click(button);++ assert.strictEqual(+ onCreate.callCount,+ 1,+ "clicking create for whitespace adds no callback"+ );+ });++ test("the default create input shares its add button's centre line", async function (assert) {+ const items = objectItems().slice(0, 2);+ const centreY = (selector) => {+ const rect = find(selector).getBoundingClientRect();+ return rect.top + rect.height / 2;+ };++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @allowCreate={{true}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onCreate={{noop}}+ @onMove={{noop}}+ >+ <:row as |item|><span+ data-test-item={{item.id}}+ >{{item.name}}</span></:row>+ </DReorderableList>+ </template>+ );++ assert.strictEqual(+ getComputedStyle(find(".d-reorderable-list__create-input"))+ .marginBottom,+ "0px",+ "the input carries no bottom margin into the row"+ );+ assert.true(+ Math.abs(+ centreY(".d-reorderable-list__create-input") -+ centreY(".d-reorderable-list__create-button")+ ) < 1,+ "the input and the add button are centred on one line"+ );+ });++ test("create UI is absent unless allowCreate is true", async function (assert) {+ const items = objectItems().slice(0, 1);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onCreate={{noop}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(".d-reorderable-list__create")+ .doesNotExist("the create row is opt-in");+ assert+ .dom(".d-reorderable-list__create-input")+ .doesNotExist("an opted-out list has no create input");+ });++ test("custom create block replaces the default create row", async function (assert) {+ const items = objectItems().slice(0, 1);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @allowCreate={{true}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onCreate={{noop}}+ @onMove={{noop}}+ >+ <:row as |item|><span+ data-test-item={{item.id}}+ >{{item.name}}</span></:row>+ <:create><li data-slot="create">Consumer create</li></:create>+ </DReorderableList>+ </template>+ );++ assert.deepEqual(+ Array.from(find(".d-reorderable-list").children).map(+ (element) => element.dataset.reorderableKey ?? element.dataset.slot+ ),+ [items[0].id, "create"],+ "the custom create block occupies the default create position"+ );+ assert+ .dom("[data-slot='create']")+ .exists({ count: 1 }, "the consumer create block renders once");+ assert+ .dom(".d-reorderable-list__create")+ .doesNotExist(+ "the custom block replaces the default create row entirely"+ );+ assert+ .dom(".d-reorderable-list__create-input")+ .doesNotExist("the custom block renders no default input");+ });++ test("create renders alongside the empty block", async function (assert) {+ const items = [];++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @allowCreate={{true}}+ @items={{items}}+ @label={{label}}+ @onCreate={{noop}}+ @onMove={{noop}}+ >+ <:row as |item|><span data-test-item={{item}}>{{item}}</span></:row>+ <:empty><li data-slot="empty">Nothing here</li></:empty>+ </DReorderableList>+ </template>+ );++ assert.deepEqual(+ Array.from(find(".d-reorderable-list").children).map((element) => {+ if (element.classList.contains("d-reorderable-list__create")) {+ return "create";+ }+ return element.dataset.slot;+ }),+ ["empty", "create"],+ "the empty block and create row both render before static content"+ );+ assert+ .dom(".d-reorderable-list__create-input")+ .exists("an empty collection still offers the create input");+ });++ test("removing a dragged item clears its state before reinsertion", async function (assert) {+ const initialItems = objectItems();+ const draggedItem = initialItems[1];+ const state = new (class {+ @tracked items = initialItems;+ })();++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{state.items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|><span+ data-test-item={{item.id}}+ >{{item.name}}</span></:row>+ </DReorderableList>+ </template>+ );++ const sourceHandle = `${rowSelector(draggedItem.id)} .d-reorderable-list__handle`;+ const sourceElement = find(sourceHandle);+ const sourceCoordinates = centerOf(sourceHandle);+ const dataTransfer = new DataTransfer();+ await dragEvent(sourceElement, "dragstart", {+ dataTransfer,+ ...sourceCoordinates,+ });+ assert+ .dom(rowSelector(draggedItem.id))+ .hasClass(+ "--dragging",+ "the primitive marks the dragged row, so no state is mirrored by hand"+ );++ state.items = initialItems.filter((item) => item !== draggedItem);+ await settled();+ assert+ .dom(rowSelector(draggedItem.id))+ .doesNotExist("the host removes the in-flight row");++ await dragEvent(sourceElement, "dragend", {+ dataTransfer,+ ...sourceCoordinates,+ });+ state.items = initialItems;+ await settled();++ assert+ .dom(rowSelector(draggedItem.id))+ .doesNotHaveClass(+ "--dragging",+ "a reinserted row does not inherit a removed drag's state"+ );+ });+ }+);++module(+ "Integration | ui-kit | DReorderableList | rev42618 review oracle",+ function (hooks) {+ setupRenderingTest(hooks);++ test("rev42618 removal is judged by the row leaving not by the count", async function (assert) {+ const items = trackedArray(objectItems());+ const removed = items[1];+ const onRemove = (item) => {+ items.splice(items.indexOf(item), 1);+ items.push({ id: "delta", name: "Delta" });+ };+ const announce = sinon.spy(this.owner.lookup("service:a11y"), "announce");++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ @onRemove={{onRemove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await click(`${rowSelector(removed.id)} .d-reorderable-list__remove`);++ assert.false(+ renderedItemOrder().includes(removed.id),+ "the removed row is gone from the rendered order even though the count is unchanged"+ );+ assert.true(+ announce+ .getCalls()+ .some((call) => call.args[0].includes(label(removed))),+ "the removal is announced by the row leaving, naming the removed row, not inferred from the count"+ );+ });++ test("rev42618 focus after removal lands on the control that took the slot", async function (assert) {+ const items = trackedArray([+ { id: "alpha", name: "Alpha" },+ { id: "bravo", name: "Bravo" },+ { id: "charlie", name: "Charlie" },+ { id: "delta", name: "Delta" },+ { id: "echo", name: "Echo" },+ ]);+ const movable = (item) => item.id !== "alpha" && item.id !== "bravo";+ const onRemove = (item) => items.splice(items.indexOf(item), 1);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{noop}}+ @onRemove={{onRemove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await click(`${rowSelector("charlie")} .d-reorderable-list__remove`);++ assert.strictEqual(+ document.activeElement,+ find(`${rowSelector("delta")} .d-reorderable-list__remove`),+ "focus lands on the remove control of the row that now occupies the vacated slot, not on the last row's control"+ );+ });++ test("rev42618 removing the last removable row keeps focus in the list", async function (assert) {+ const items = trackedArray([{ id: "alpha", name: "Alpha" }]);+ const onRemove = (item) => items.splice(items.indexOf(item), 1);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @allowCreate={{true}}+ @items={{items}}+ @key="id"+ @label={{label}}+ @onCreate={{noop}}+ @onMove={{noop}}+ @onRemove={{onRemove}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await click(`${rowSelector("alpha")} .d-reorderable-list__remove`);++ assert.notStrictEqual(+ document.activeElement,+ document.body,+ "focus does not fall to the body when the last removable row goes"+ );+ assert.true(+ find(".d-reorderable-list").contains(document.activeElement),+ "focus stays inside the list root, where the reader can act again"+ );+ });++ test("rev42618 a row without a handle is not itself draggable", async function (assert) {+ const items = [{ id: "alpha", name: "Alpha" }];++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert+ .dom(handleSelector("alpha"))+ .doesNotExist(+ "a lone standalone row has nowhere to move, so it renders no handle"+ );+ assert.notStrictEqual(+ find(rowSelector("alpha")).getAttribute("draggable"),+ "true",+ "the drag source does not fall back to the row element, so the row's text stays selectable"+ );+ });++ test("rev42618 an open menu closes when its row leaves the list", async function (assert) {+ const items = trackedArray(objectItems());+ const removedKey = items[1].id;++ await render(+ <template><List @items={{items}} @onMove={{noop}} /></template>+ );++ await openMoveMenu(removedKey);+ assert+ .dom(MENU_SELECTOR)+ .exists("the move menu is open before the row leaves");++ const remaining = items.filter((item) => item.id !== removedKey);+ items.splice(0, items.length, ...remaining);+ await settled();++ assert+ .dom(MENU_SELECTOR)+ .doesNotExist(+ "the menu is dismissed when the row it describes leaves the list"+ );+ });++ test("rev42618 a lone grouped row advertises no popup", async function (assert) {+ const soloItems = [{ id: "golf", name: "Golf" }];+ const otherItems = [+ { id: "hotel", name: "Hotel" },+ { id: "india", name: "India" },+ ];++ await render(+ <template>+ <DMenus />+ <DReorderableListGroup @onMove={{noop}} as |group|>+ <DReorderableList+ id="solo-list"+ @group={{group}}+ @items={{soloItems}}+ @key="id"+ @label={{label}}+ @listId="solo"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ <DReorderableList+ id="other-list"+ @group={{group}}+ @items={{otherItems}}+ @key="id"+ @label={{label}}+ @listId="other"+ >+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>+ </template>+ );++ assert+ .dom(handleSelector("golf", "#solo-list"))+ .exists(+ "the lone grouped row keeps its handle, which is still the cross-list drag source"+ );+ assert+ .dom(handleSelector("golf", "#solo-list"))+ .doesNotHaveAttribute(+ "aria-haspopup",+ "a handle whose menu holds no destinations advertises no popup"+ );++ await openMoveMenu("golf", "#solo-list");+ assert+ .dom(MENU_SELECTOR)+ .doesNotExist("clicking the handle opens no empty menu");+ });++ test("rev42618 the default create row is a cell in a table shell", async function (assert) {+ const items = objectItems().slice(0, 2);+ const onCreate = sinon.spy();++ await render(+ <template>+ <DMenus />+ {{! eslint-disable ember/template-table-groups }}+ <table>+ <DReorderableList+ @allowCreate={{true}}+ @items={{items}}+ @itemTag="tr"+ @key="id"+ @label={{label}}+ @onCreate={{onCreate}}+ @onMove={{noop}}+ @tag="tbody"+ >+ <:row as |item|>+ <td data-test-item={{item.id}}>{{item.name}}</td>+ </:row>+ </DReorderableList>+ </table>+ </template>+ );++ const createRow = find(".d-reorderable-list__create");+ assert+ .dom(createRow)+ .hasTagName("tr", "the create row adopts the table shell's item tag");+ const children = Array.from(createRow.children);+ assert.strictEqual(+ children.length,+ 1,+ "the create row holds exactly one element child, so the tr contains no stray non-cell children"+ );+ assert+ .dom(children[0])+ .hasTagName("td", "that only child is a table cell");+ assert.true(+ !!children[0]?.querySelector(".d-reorderable-list__create-input"),+ "the create input lives inside the cell, keeping the table markup valid"+ );+ });++ test("rev42618 a standalone list without onMove asserts", async function (assert) {+ const items = objectItems();+ let raised;++ setupOnerror((error) => {+ raised = error;+ });++ try {+ await render(+ <template>+ <DMenus />+ <DReorderableList @items={{items}} @key="id" @label={{label}}>+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ await moveVia(items[1].id, "up");+ } finally {+ resetOnerror();+ }++ assert.true(+ /Assertion Failed:.*@onMove/i.test(raised?.message ?? ""),+ "a standalone list has no way to commit a move without @onMove, and a development assertion says so"+ );+ });++ test("rev42618 a row refuses a drop on itself", async function (assert) {+ const items = objectItems();+ const onMove = sinon.spy();++ await render(+ <template><List @items={{items}} @onMove={{onMove}} /></template>+ );++ const source = rowSelector(items[1].id);+ assertDragReady(assert, source, source);++ const dataTransfer = new DataTransfer();+ await startDrag(source, { dataTransfer });+ await dragOver(source, {+ dataTransfer,+ coordinates: dropCoordinates(source, "before"),+ });++ assert+ .dom(source)+ .doesNotHaveClass(+ "--drag-above",+ "hovering a row with its own drag offers no before indicator"+ );+ assert+ .dom(source)+ .doesNotHaveClass(+ "--drag-below",+ "and no after indicator, so the row is never offered a position relative to itself"+ );++ await dragEvent(source, "drop", {+ dataTransfer,+ ...dropCoordinates(source, "before"),+ });+ const handle = handleSelector(items[1].id);+ await dragEvent(handle, "dragend", { dataTransfer, ...centerOf(handle) });++ assert.strictEqual(+ onMove.callCount,+ 0,+ "a drop of a row on itself commits no move"+ );+ });++ test("rev42618 the hint block renders before the header", async function (assert) {+ const items = objectItems().slice(0, 2);++ await render(+ <template>+ <DMenus />+ <DReorderableList+ @items={{items}}+ @key="id"+ @label={{label}}+ @onMove={{noop}}+ >+ <:hint><li data-slot="hint">Hint</li></:hint>+ <:header><li data-slot="header">Header</li></:header>+ <:row as |item|>+ <span data-test-item={{item.id}}>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+ );++ assert.dom("[data-slot='hint']").exists("the hint block renders");+ assert.dom("[data-slot='header']").exists("the header block renders");+ assert.deepEqual(+ Array.from(find(".d-reorderable-list").children).map(+ (element) => element.dataset.slot ?? element.dataset.reorderableKey+ ),+ ["hint", "header", ...items.map((item) => item.id)],+ "the hint precedes the header in document order, and both precede every row"+ );+ });++ test("rev42618 the move callback is read live", async function (assert) {+ const items = objectItems();+ const firstOnMove = sinon.spy();+ const secondOnMove = sinon.spy();+ const state = new (class {+ @tracked onMove = firstOnMove;+ })();++ await render(+ <template><List @items={{items}} @onMove={{state.onMove}} /></template>+ );++ state.onMove = secondOnMove;+ await settled();++ await moveVia(items[1].id, "up");++ assert.strictEqual(+ secondOnMove.callCount,+ 1,+ "the callback swapped in after the first render receives the move"+ );+ assert.strictEqual(+ firstOnMove.callCount,+ 0,+ "the callback captured at the first render does not, proving @onMove is read live"+ );+ });+ }+);diff --git a/frontend/discourse/tests/unit/ui-kit/d-reorderable-list/move-engine-test.js b/frontend/discourse/tests/unit/ui-kit/d-reorderable-list/move-engine-test.jsnew file mode 100644index 00000000000..ada1b423310--- /dev/null+++ b/frontend/discourse/tests/unit/ui-kit/d-reorderable-list/move-engine-test.js@@ -0,0 +1,238 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import MoveEngine from "discourse/ui-kit/d-reorderable-list/-internals/engine/move-engine";++/**+ * The engine drives the frozen-row interleaving, which the component tests+ * reach only through rendered output. Exercised directly here because it is+ * the part of the split most able to drift while every rendered assertion+ * still passes: a projection that mislays one frozen row still renders a list+ * of the right length, in an order no assertion names.+ */+module("Unit | ui-kit | DReorderableList | MoveEngine", function (hooks) {+ setupTest(hooks);++ /** Builds the row projection the component would hand the engine. */+ function rowsFor(spec) {+ return spec.map((entry, index) => ({+ item: entry.id,+ key: entry.id,+ index,+ movable: entry.movable !== false,+ isFirst: false,+ isLast: false,+ label: entry.id,+ }));+ }++ function engineFor(spec, overrides = {}) {+ const rows = rowsFor(spec);+ const moves = [];+ const engine = new MoveEngine({+ args: () => ({+ items: rows.map((row) => row.item),+ onMove: (move) => moves.push(move),+ ...overrides,+ }),+ rows: () => rows,+ listId: () => "default",+ announcer: {+ announceMove() {},+ announceBoundary() {},+ noteRun() {},+ updateRun() {},+ cancelRun() {},+ },+ refocusIndex() {},+ });+ return { engine, rows, moves };+ }++ test("a move reorders only the movable subsequence", async function (assert) {+ const { engine, moves } = engineFor([+ { id: "a" },+ { id: "b" },+ { id: "c" },+ ]);++ engine.move("a", "down", "menu");++ assert.deepEqual(moves.at(-1).proposedToItems, ["b", "a", "c"]);+ assert.strictEqual(moves.at(-1).fromIndex, 0);+ assert.strictEqual(moves.at(-1).toIndex, 1);+ });++ test("frozen rows keep their exact visible slots", async function (assert) {+ // The invariant the interleaving exists for: "pinned" never moves, and the+ // movable items refill the remaining slots in their new order.+ const { engine, moves } = engineFor([+ { id: "a" },+ { id: "pinned", movable: false },+ { id: "b" },+ { id: "c" },+ ]);++ engine.move("a", "bottom", "menu");++ assert.deepEqual(+ moves.at(-1).proposedToItems,+ ["b", "pinned", "c", "a"],+ "the frozen row holds index 1 while the movable slots refill around it"+ );+ });++ test("a move to an end that the row already occupies is a no-op", async function (assert) {+ const { engine, moves } = engineFor([{ id: "a" }, { id: "b" }]);++ engine.move("a", "top", "menu");+ engine.move("a", "up", "menu");++ assert.deepEqual(moves, [], "neither reports a move nor a projection");+ });++ test("a frozen row refuses to move at all", async function (assert) {+ const { engine, moves } = engineFor([+ { id: "a", movable: false },+ { id: "b" },+ ]);++ engine.move("a", "down", "menu");++ assert.deepEqual(moves, []);+ });++ test("an onMove false return still commits, and only gates the announcement", async function (assert) {+ let announced = 0;+ const rows = rowsFor([{ id: "a" }, { id: "b" }]);+ const seen = [];+ const engine = new MoveEngine({+ args: () => ({+ items: ["a", "b"],+ onMove: (move) => {+ seen.push(move);+ return false;+ },+ }),+ rows: () => rows,+ listId: () => "default",+ announcer: {+ announceMove() {+ announced += 1;+ },+ announceBoundary() {},+ noteRun() {},+ updateRun() {},+ cancelRun() {},+ },+ refocusIndex() {},+ });++ engine.move("a", "down", "menu");++ assert.strictEqual(seen.length, 1, "the consumer is still told");+ assert.strictEqual(announced, 0, "but the veto stops the announcement");+ });++ test("removalProjection leaves frozen rows on their own indices", async function (assert) {+ const { engine } = engineFor([+ { id: "a" },+ { id: "pinned", movable: false },+ { id: "b" },+ { id: "c" },+ ]);++ const removal = engine.removalProjection("a");++ assert.strictEqual(removal.item, "a");+ assert.strictEqual(removal.fromIndex, 0);+ assert.deepEqual(+ removal.proposedFromItems,+ ["b", "pinned", "c"],+ "the list shrinks by its last slot and the frozen row keeps index 1"+ );+ });++ test("removalProjection refuses a key it does not own or cannot move", async function (assert) {+ const { engine } = engineFor([{ id: "a", movable: false }, { id: "b" }]);++ assert.strictEqual(engine.removalProjection("a"), undefined, "frozen");+ assert.strictEqual(engine.removalProjection("nope"), undefined, "unknown");+ });++ test("rev42618 removalProjection keeps a frozen final row", async function (assert) {+ // "pinned" sits on the final visible index, the one slot the shrinking+ // list no longer has, so it must join the end of the refill queue.+ const { engine } = engineFor([+ { id: "a" },+ { id: "b" },+ { id: "pinned", movable: false },+ ]);++ const removal = engine.removalProjection("a");++ assert.deepEqual(+ removal.proposedFromItems,+ ["b", "pinned"],+ "the frozen row whose slot was dropped joins the end instead of vanishing"+ );+ assert.strictEqual(+ removal.proposedFromItems.length,+ 2,+ "the list shrinks by exactly one slot"+ );+ assert.deepEqual(+ [...removal.proposedFromItems].sort(),+ ["a", "b", "pinned"].filter((item) => item !== "a").sort(),+ "conservation: the projection holds exactly the original items minus the removed one"+ );+ });++ test("rev42618 commitCrossMove keeps a frozen destination row on its slot", async function (assert) {+ const crossMoves = [];+ const sourceMember = {+ listId: "source",+ listLabel: () => "Source",+ disabled: () => false,+ getItems: () => ["arrival"],+ element: () => undefined,+ removalProjection: (key) =>+ key === "arrival"+ ? { item: "arrival", fromIndex: 0, proposedFromItems: [] }+ : undefined,+ acceptMove() {},+ };+ const group = {+ token: "token",+ generation: () => 0,+ registerMember: () => () => {},+ lookupMember: (listId) =>+ listId === "source" ? sourceMember : undefined,+ siblings: () => [],+ neighbour: () => undefined,+ onMove: (move) => crossMoves.push(move),+ };+ const { engine } = engineFor(+ [{ id: "x" }, { id: "pinned", movable: false }, { id: "y" }],+ { group }+ );++ engine.commitCrossMove("source", "arrival", 2, "menu");++ const move = crossMoves.at(-1);+ assert.strictEqual(+ move.proposedToItems[1],+ "pinned",+ "the frozen destination row keeps its original visible index while the list grows"+ );+ assert.strictEqual(+ move.proposedToItems[move.toIndex],+ "arrival",+ "the arriving item sits exactly where the move reports it landed"+ );+ assert.deepEqual(+ [...move.proposedToItems].sort(),+ ["x", "pinned", "y", "arrival"].sort(),+ "conservation: the destination holds exactly its own items plus the arriving one"+ );+ });+});diff --git a/frontend/discourse/tests/unit/ui-kit/d-reorderable-list/move-menu-coordinator-test.js b/frontend/discourse/tests/unit/ui-kit/d-reorderable-list/move-menu-coordinator-test.jsnew file mode 100644index 00000000000..869bf0ffc3c--- /dev/null+++ b/frontend/discourse/tests/unit/ui-kit/d-reorderable-list/move-menu-coordinator-test.js@@ -0,0 +1,65 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";+import MoveMenuCoordinator from "discourse/ui-kit/d-reorderable-list/-internals/coordinators/move-menu-coordinator";++/**+ * The coordinator is unit-tested because its one race cannot be staged through+ * rendering: in production the service's close awaits FloatKit's closing+ * animation, so an earlier menu's `onClose` can land after a later menu has+ * already opened — and that animation is short-circuited under `isTesting`,+ * which is exactly why no rendering test can see the ordering.+ */+module(+ "Unit | ui-kit | DReorderableList | MoveMenuCoordinator",+ function (hooks) {+ setupTest(hooks);++ /** Builds a coordinator whose menu service records each show's onClose. */+ function buildCoordinator() {+ const closeCallbacks = [];+ const menu = {+ async show(trigger, options) {+ closeCallbacks.push(options.onClose);+ return { destroy: sinon.spy(), expanded: false, close: sinon.spy() };+ },+ };+ const handles = new Map();+ const coordinator = new MoveMenuCoordinator({+ menu,+ args: () => ({}),+ listId: () => "default",+ handleFor: (key) => {+ if (!handles.has(key)) {+ handles.set(key, document.createElement("button"));+ }+ return handles.get(key);+ },+ rowFor: () => undefined,+ siblings: () => [],+ move: () => {},+ canSpill: () => false,+ onRefusedMove: () => {},+ });+ return { coordinator, closeCallbacks };+ }++ test("rev42618 a stale menu close does not clear the open row", async function (assert) {+ const { coordinator, closeCallbacks } = buildCoordinator();++ await coordinator.openMenu("a");+ await coordinator.openMenu("b");++ // The first menu's close arriving only now, after the second menu has+ // opened, as it does in production when its closing animation resolves+ // late.+ closeCallbacks[0]();++ assert.strictEqual(+ coordinator.openKey,+ "b",+ "a close belonging to an already-replaced menu leaves the record of the currently open row alone"+ );+ });+ }+);diff --git a/frontend/discourse/type-tests/ui-kit/d-reorderable-list-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-reorderable-list-errors-test.gtsnew file mode 100644index 00000000000..b64220f8c58--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/d-reorderable-list-errors-test.gts@@ -0,0 +1,62 @@+import DReorderableList, {+ type ReorderableMove,+} from "discourse/ui-kit/d-reorderable-list";+import DReorderableListGroup from "discourse/ui-kit/d-reorderable-list-group";++interface Section {+ id: string;+ name: string;+}++interface Tag {+ slug: string;+}++declare const sections: Section[];+declare const tags: Tag[];+declare function applySectionMove(move: ReorderableMove<Section>): void;+declare function label(section: Section): string;+declare function tagLabel(tag: Tag): string;++const Test = <template>+ <DReorderableList+ {{! @glint-expect-error - @controls is a closed union; "split" is not a member }}+ @controls="split"+ @items={{sections}}+ @label={{label}}+ >+ <:row as |section|>{{section.name}}</:row>+ </DReorderableList>++ <DReorderableList+ {{! @glint-expect-error - @allowCreate is a flag, not a string }}+ @allowCreate="yes"+ @items={{sections}}+ @label={{label}}+ >+ <:row as |section|>{{section.name}}</:row>+ </DReorderableList>++ <DReorderableList+ @items={{sections}}+ @label={{label}}+ {{! @glint-expect-error - @removeIcon names an icon, so it is a string }}+ @removeIcon={{true}}+ >+ <:row as |section|>{{section.name}}</:row>+ </DReorderableList>++ <DReorderableListGroup @onMove={{applySectionMove}} as |groupApi|>+ <DReorderableList+ {{! @glint-expect-error - a member's items must be what the group's handler takes }}+ @group={{groupApi}}+ @items={{tags}}+ @label={{tagLabel}}+ @listId="tags"+ >+ <:row as |tag|>{{tag.slug}}</:row>+ </DReorderableList>+ </DReorderableListGroup>+</template>;++export { Test };diff --git a/frontend/discourse/type-tests/ui-kit/d-reorderable-list-test.gts b/frontend/discourse/type-tests/ui-kit/d-reorderable-list-test.gtsnew file mode 100644index 00000000000..62ed4f0f77d--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/d-reorderable-list-test.gts@@ -0,0 +1,128 @@+// Keep this file free of @glint-expect-error directives so broken positive+// invocations cannot be masked by a negative assertion. Rejections live in+// d-reorderable-list-errors-test.gts.+import DReorderableList, {+ type ReorderableGroupApi,+ type ReorderableGroupMember,+ type ReorderableMove,+ type ReorderableRowApi,+} from "discourse/ui-kit/d-reorderable-list";+import DReorderableListGroup from "discourse/ui-kit/d-reorderable-list-group";++interface Section {+ id: string;+ name: string;+}++declare const sections: Section[];+declare function applyMove(move: ReorderableMove<Section>): void;+declare function label(section: Section): string;+declare function movable(section: Section): boolean;+declare function removeSection(section: Section, index: number): void;+declare const group: ReorderableGroupApi;++// The four interfaces are re-exported from the component's own module path,+// which is the only thing keeping the group's `import type` working. Nothing+// else in the repo pins that, so these two lines are the guard.+declare const member: ReorderableGroupMember;+declare const rowApi: ReorderableRowApi;+declare const someMove: ReorderableMove;++const usesNamedExports: string = [+ member.listId,+ someMove.fromList,+ rowApi.index.toString(),+].join("");++const Test = <template>+ {{! The minimum: items, a label, and somewhere to report the move }}+ <DReorderableList @items={{sections}} @label={{label}} @onMove={{applyMove}}>+ <:row as |section|>+ <span>{{section.name}}</span>+ </:row>+ </DReorderableList>++ {{! The row block yields the item first, then its controls }}+ <DReorderableList+ @items={{sections}}+ @key="id"+ @label={{label}}+ @movable={{movable}}+ @onMove={{applyMove}}+ @onRemove={{removeSection}}+ @removeIcon="trash-can"+ >+ <:row as |section controls|>+ <span>{{section.name}} {{controls.index}}</span>+ </:row>+ </DReorderableList>++ {{! Manual placement yields the pre-wired controls on the same block param }}+ <DReorderableList+ @controls="manual"+ @items={{sections}}+ @key="id"+ @label={{label}}+ @onMove={{applyMove}}+ @onRemove={{removeSection}}+ >+ <:row as |section controls|>+ <controls.handle />+ <span>{{section.name}}</span>+ {{! Manual mode lets the yielded remove control take its own buttonClass }}+ {{#if controls.remove}}+ <controls.remove @buttonClass="btn-default" />+ {{/if}}+ </:row>+ </DReorderableList>++ {{! The optional blocks, and the shell arguments that retag the elements }}+ <DReorderableList+ class="styled"+ @allowCreate={{true}}+ @items={{sections}}+ @itemTag="tr"+ @key="id"+ @label={{label}}+ @onMove={{applyMove}}+ @tag="tbody"+ >+ <:hint>Drag to reorder</:hint>+ <:header>Sections</:header>+ <:row as |section|>+ <td>{{section.name}}</td>+ </:row>+ <:empty>Nothing yet</:empty>+ </DReorderableList>++ {{! A member list routes its moves through the group instead }}+ <DReorderableListGroup @onMove={{applyMove}} as |groupApi|>+ <DReorderableList+ @group={{groupApi}}+ @items={{sections}}+ @key="id"+ @label={{label}}+ @listId="primary"+ @listLabel="Primary"+ >+ <:row as |section|>+ <span>{{section.name}}</span>+ </:row>+ </DReorderableList>+ </DReorderableListGroup>++ {{! A group API obtained elsewhere satisfies the same argument }}+ <DReorderableList+ @group={{group}}+ @items={{sections}}+ @key="id"+ @label={{label}}+ @listId="secondary"+ >+ <:row as |section|>+ <span>{{section.name}}</span>+ </:row>+ </DReorderableList>+</template>;++export { Test, usesNamedExports };diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/basic.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/basic.gjsnew file mode 100644index 00000000000..c208ccd58b2--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/basic.gjs@@ -0,0 +1,34 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { trackedArray } from "@ember/reactive/collections";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";++export default class ReorderableListBasicExample extends Component {+ items = trackedArray([+ { id: "inbox", name: "Inbox" },+ { id: "starred", name: "Starred" },+ { id: "drafts", name: "Drafts" },+ { id: "archive", name: "Archive" },+ ]);++ itemLabel = (item) => item.name;++ @action+ applyMove({ proposedToItems }) {+ this.items.splice(0, this.items.length, ...proposedToItems);+ }++ <template>+ <DReorderableList+ class="styleguide-reorderable-list"+ @items={{this.items}}+ @key="id"+ @label={{this.itemLabel}}+ @onMove={{this.applyMove}}+ >+ <:row as |item|>+ <span>{{item.name}}</span>+ </:row>+ </DReorderableList>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/create.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/create.gjsnew file mode 100644index 00000000000..4dbdba0e75d--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/create.gjs@@ -0,0 +1,38 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { trackedArray } from "@ember/reactive/collections";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";++export default class ReorderableListCreateExample extends Component {+ values = trackedArray(["apples", "bananas", "cherries"]);++ indexKey = "@index";++ valueLabel = (value) => value;++ @action+ applyMove({ proposedToItems }) {+ this.values.splice(0, this.values.length, ...proposedToItems);+ }++ @action+ addValue(value) {+ this.values.push(value);+ }++ <template>+ <DReorderableList+ class="styleguide-reorderable-list"+ @allowCreate={{true}}+ @items={{this.values}}+ @key={{this.indexKey}}+ @label={{this.valueLabel}}+ @onCreate={{this.addValue}}+ @onMove={{this.applyMove}}+ >+ <:row as |value|>+ <span>{{value}}</span>+ </:row>+ </DReorderableList>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/cross-list.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/cross-list.gjsnew file mode 100644index 00000000000..3d2da848c15--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/cross-list.gjs@@ -0,0 +1,85 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { trackedArray } from "@ember/reactive/collections";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import DReorderableListGroup from "discourse/ui-kit/d-reorderable-list-group";+import { i18n } from "discourse-i18n";++export default class ReorderableListCrossListExample extends Component {+ primary = trackedArray([+ { id: "home", name: "Home" },+ { id: "latest", name: "Latest" },+ { id: "categories", name: "Categories" },+ ]);++ secondary = trackedArray([+ { id: "badges", name: "Badges" },+ { id: "groups", name: "Groups" },+ ]);++ itemLabel = (item) => item.name;++ @action+ applyMove({ fromList, toList, proposedFromItems, proposedToItems }) {+ const listFor = (id) => (id === "primary" ? this.primary : this.secondary);+ const from = listFor(fromList);+ from.splice(0, from.length, ...proposedFromItems);+ if (toList !== fromList) {+ const to = listFor(toList);+ to.splice(0, to.length, ...proposedToItems);+ }+ }++ <template>+ <DReorderableListGroup @onMove={{this.applyMove}} as |group|>+ <div class="styleguide-reorderable-list-group">+ <div class="styleguide-reorderable-list-group__panel">+ <h4>{{i18n+ "styleguide.sections.reorderable_list.cross_list_primary"+ }}</h4>+ <DReorderableList+ class="styleguide-reorderable-list"+ @group={{group}}+ @items={{this.primary}}+ @key="id"+ @label={{this.itemLabel}}+ @listId="primary"+ @listLabel={{i18n+ "styleguide.sections.reorderable_list.cross_list_primary"+ }}+ >+ <:row as |item|>+ <span>{{item.name}}</span>+ </:row>+ <:empty>+ {{i18n "styleguide.sections.reorderable_list.cross_list_empty"}}+ </:empty>+ </DReorderableList>+ </div>+ <div class="styleguide-reorderable-list-group__panel">+ <h4>{{i18n+ "styleguide.sections.reorderable_list.cross_list_secondary"+ }}</h4>+ <DReorderableList+ class="styleguide-reorderable-list"+ @group={{group}}+ @items={{this.secondary}}+ @key="id"+ @label={{this.itemLabel}}+ @listId="secondary"+ @listLabel={{i18n+ "styleguide.sections.reorderable_list.cross_list_secondary"+ }}+ >+ <:row as |item|>+ <span>{{item.name}}</span>+ </:row>+ <:empty>+ {{i18n "styleguide.sections.reorderable_list.cross_list_empty"}}+ </:empty>+ </DReorderableList>+ </div>+ </div>+ </DReorderableListGroup>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/editable.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/editable.gjsnew file mode 100644index 00000000000..b945498425d--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/editable.gjs@@ -0,0 +1,51 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { trackedArray } from "@ember/reactive/collections";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";++export default class ReorderableListEditableExample extends Component {+ items = trackedArray([+ { id: "welcome", value: "Welcome to the community" },+ { id: "rules", value: "Read the rules first" },+ { id: "intro", value: "Introduce yourself" },+ ]);++ itemLabel = (item) => item.value;++ @action+ applyMove({ proposedToItems }) {+ this.items.splice(0, this.items.length, ...proposedToItems);+ }++ @action+ updateValue(item, event) {+ item.value = event.target.value;+ }++ @action+ remove(item, index) {+ this.items.splice(index, 1);+ }++ <template>+ <DReorderableList+ class="styleguide-reorderable-list"+ @items={{this.items}}+ @key="id"+ @label={{this.itemLabel}}+ @onMove={{this.applyMove}}+ @onRemove={{this.remove}}+ >+ <:row as |item|>+ <input+ class="styleguide-reorderable-list__input"+ type="text"+ value={{item.value}}+ {{on "input" (fn this.updateValue item)}}+ />+ </:row>+ </DReorderableList>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/policies.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/policies.gjsnew file mode 100644index 00000000000..332bb44759f--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/policies.gjs@@ -0,0 +1,56 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { trackedArray } from "@ember/reactive/collections";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import { i18n } from "discourse-i18n";++export default class ReorderableListPoliciesExample extends Component {+ items = trackedArray([+ { id: "announcements", name: "Announcements", pinned: true },+ { id: "latest", name: "Latest" },+ { id: "categories", name: "Categories", required: true },+ { id: "top", name: "Top" },+ { id: "bookmarks", name: "Bookmarks", pinned: true },+ ]);++ itemLabel = (item) => item.name;++ movable = (item) => !item.pinned;+ removable = (item) => !item.required;++ @action+ applyMove({ proposedToItems }) {+ this.items.splice(0, this.items.length, ...proposedToItems);+ }++ @action+ remove(item, index) {+ this.items.splice(index, 1);+ }++ <template>+ <DReorderableList+ class="styleguide-reorderable-list"+ @items={{this.items}}+ @key="id"+ @label={{this.itemLabel}}+ @movable={{this.movable}}+ @onMove={{this.applyMove}}+ @onRemove={{this.remove}}+ @removable={{this.removable}}+ >+ <:row as |item|>+ <span class="styleguide-reorderable-list__label">{{item.name}}</span>+ {{#if item.pinned}}+ <span class="styleguide-reorderable-list__note">{{i18n+ "styleguide.sections.reorderable_list.policies_pinned"+ }}</span>+ {{else if item.required}}+ <span class="styleguide-reorderable-list__note">{{i18n+ "styleguide.sections.reorderable_list.policies_required"+ }}</span>+ {{/if}}+ </:row>+ </DReorderableList>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/table.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/table.gjsnew file mode 100644index 00000000000..61580a7ae7e--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/table.gjs@@ -0,0 +1,52 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { trackedArray } from "@ember/reactive/collections";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import { i18n } from "discourse-i18n";++export default class ReorderableListTableExample extends Component {+ fields = trackedArray([+ { id: "name", name: "Full name", type: "Text" },+ { id: "location", name: "Location", type: "Text" },+ { id: "website", name: "Website", type: "URL" },+ ]);++ fieldLabel = (item) => item.name;++ @action+ applyMove({ proposedToItems }) {+ this.fields.splice(0, this.fields.length, ...proposedToItems);+ }++ <template>+ {{! The reorderable list renders the tbody itself, which the static+ table-group rule cannot see from here. }}+ {{! eslint-disable-next-line ember/template-table-groups }}+ <table class="styleguide-reorderable-table">+ <thead>+ <tr>+ <th></th>+ <th>{{i18n "styleguide.sections.reorderable_list.table_field"}}</th>+ <th>{{i18n "styleguide.sections.reorderable_list.table_type"}}</th>+ </tr>+ </thead>+ <DReorderableList+ @controls="manual"+ @items={{this.fields}}+ @itemTag="tr"+ @key="id"+ @label={{this.fieldLabel}}+ @onMove={{this.applyMove}}+ @tag="tbody"+ >+ <:row as |item controls|>+ <td class="styleguide-reorderable-table__reorder">+ <controls.handle />+ </td>+ <td>{{item.name}}</td>+ <td>{{item.type}}</td>+ </:row>+ </DReorderableList>+ </table>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/toggles.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/toggles.gjsnew file mode 100644index 00000000000..d7f1083a1f8--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/reorderable-list/toggles.gjs@@ -0,0 +1,62 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { trackedArray } from "@ember/reactive/collections";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";++export default class ReorderableListTogglesExample extends Component {+ items = trackedArray([+ { id: "summary", name: "Summary", enabled: true },+ { id: "activity", name: "Activity", enabled: true },+ { id: "storage", name: "Storage", enabled: true },+ { id: "backups", name: "Backups", enabled: false },+ { id: "security", name: "Security", enabled: false },+ ]);++ isEnabled = (item) => item.enabled;+ itemLabel = (item) => item.name;++ @action+ applyMove({ proposedToItems }) {+ this.items.splice(0, this.items.length, ...proposedToItems);+ }++ @action+ toggle(item) {+ const next = { ...item, enabled: !item.enabled };+ const rest = this.items.filter((candidate) => candidate !== item);+ const enabled = rest.filter((candidate) => candidate.enabled);+ const disabled = rest.filter((candidate) => !candidate.enabled);+ const reordered = next.enabled+ ? [...enabled, next, ...disabled]+ : [...enabled, ...disabled, next];+ this.items.splice(0, this.items.length, ...reordered);+ }++ <template>+ <DReorderableList+ class="styleguide-reorderable-list"+ @items={{this.items}}+ @key="id"+ @label={{this.itemLabel}}+ @movable={{this.isEnabled}}+ @onMove={{this.applyMove}}+ >+ <:row as |item|>+ <span+ class={{dConcatClass+ "styleguide-reorderable-list__label"+ (unless item.enabled "--static")+ }}+ >{{item.name}}</span>+ <DToggleSwitch+ @state={{item.enabled}}+ {{on "click" (fn this.toggle item)}}+ />+ </:row>+ </DReorderableList>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/reorderable-list.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/reorderable-list.gjsnew file mode 100644index 00000000000..7e73b5495fc--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/reorderable-list.gjs@@ -0,0 +1,152 @@+import Component from "@glimmer/component";+import { i18n } from "discourse-i18n";+import ReorderableListBasicExample from "../../examples/molecules/reorderable-list/basic";+import reorderableListBasicSource from "../../examples/molecules/reorderable-list/basic?source=file";+import ReorderableListCreateExample from "../../examples/molecules/reorderable-list/create";+import reorderableListCreateSource from "../../examples/molecules/reorderable-list/create?source=file";+import ReorderableListCrossListExample from "../../examples/molecules/reorderable-list/cross-list";+import reorderableListCrossListSource from "../../examples/molecules/reorderable-list/cross-list?source=file";+import ReorderableListEditableExample from "../../examples/molecules/reorderable-list/editable";+import reorderableListEditableSource from "../../examples/molecules/reorderable-list/editable?source=file";+import ReorderableListPoliciesExample from "../../examples/molecules/reorderable-list/policies";+import reorderableListPoliciesSource from "../../examples/molecules/reorderable-list/policies?source=file";+import ReorderableListTableExample from "../../examples/molecules/reorderable-list/table";+import reorderableListTableSource from "../../examples/molecules/reorderable-list/table?source=file";+import ReorderableListTogglesExample from "../../examples/molecules/reorderable-list/toggles";+import reorderableListTogglesSource from "../../examples/molecules/reorderable-list/toggles?source=file";+import StyleguideGroups from "../../styleguide-groups";++const GROUPS = ["start", "policies", "content", "layouts", "groups"];++export default class ReorderableList extends Component {+ get groups() {+ return GROUPS.map((id) => ({+ id,+ title: i18n(`styleguide.sections.reorderable_list.groups.${id}.title`),+ description: i18n(+ `styleguide.sections.reorderable_list.groups.${id}.description`+ ),+ }));+ }++ <template>+ <p class="section-description">+ {{i18n "styleguide.sections.reorderable_list.description"}}+ </p>++ <StyleguideGroups+ @active={{@group}}+ @ariaLabel={{i18n+ "styleguide.sections.reorderable_list.groups.aria_label"+ }}+ @groups={{this.groups}}+ @section={{@section}}+ as |Group|+ >+ <Group @id="start" as |Example|>+ <Example+ @code={{reorderableListBasicSource}}+ @description={{i18n+ "styleguide.sections.reorderable_list.basic_description"+ }}+ @title={{i18n "styleguide.sections.reorderable_list.basic_example"}}+ @tryThis={{i18n+ "styleguide.sections.reorderable_list.basic_try_this"+ }}+ >+ <ReorderableListBasicExample />+ </Example>+ </Group>++ <Group @id="policies" as |Example|>+ <Example+ @code={{reorderableListPoliciesSource}}+ @description={{i18n+ "styleguide.sections.reorderable_list.policies_description"+ }}+ @title={{i18n+ "styleguide.sections.reorderable_list.policies_example"+ }}+ @tryThis={{i18n+ "styleguide.sections.reorderable_list.policies_try_this"+ }}+ >+ <ReorderableListPoliciesExample />+ </Example>+ </Group>++ <Group @id="content" as |Example|>+ <Example+ @code={{reorderableListTogglesSource}}+ @description={{i18n+ "styleguide.sections.reorderable_list.toggles_description"+ }}+ @title={{i18n "styleguide.sections.reorderable_list.toggles_example"}}+ @tryThis={{i18n+ "styleguide.sections.reorderable_list.toggles_try_this"+ }}+ >+ <ReorderableListTogglesExample />+ </Example>+ <Example+ @code={{reorderableListEditableSource}}+ @description={{i18n+ "styleguide.sections.reorderable_list.editable_description"+ }}+ @title={{i18n+ "styleguide.sections.reorderable_list.editable_example"+ }}+ @tryThis={{i18n+ "styleguide.sections.reorderable_list.editable_try_this"+ }}+ >+ <ReorderableListEditableExample />+ </Example>+ <Example+ @code={{reorderableListCreateSource}}+ @description={{i18n+ "styleguide.sections.reorderable_list.create_description"+ }}+ @title={{i18n "styleguide.sections.reorderable_list.create_example"}}+ @tryThis={{i18n+ "styleguide.sections.reorderable_list.create_try_this"+ }}+ >+ <ReorderableListCreateExample />+ </Example>+ </Group>++ <Group @id="layouts" as |Example|>+ <Example+ @code={{reorderableListTableSource}}+ @description={{i18n+ "styleguide.sections.reorderable_list.table_description"+ }}+ @title={{i18n "styleguide.sections.reorderable_list.table_example"}}+ @tryThis={{i18n+ "styleguide.sections.reorderable_list.table_try_this"+ }}+ >+ <ReorderableListTableExample />+ </Example>+ </Group>++ <Group @id="groups" as |Example|>+ <Example+ @code={{reorderableListCrossListSource}}+ @description={{i18n+ "styleguide.sections.reorderable_list.cross_list_description"+ }}+ @title={{i18n+ "styleguide.sections.reorderable_list.cross_list_example"+ }}+ @tryThis={{i18n+ "styleguide.sections.reorderable_list.cross_list_try_this"+ }}+ >+ <ReorderableListCrossListExample />+ </Example>+ </Group>+ </StyleguideGroups>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.jsindex 7fa134b1cdd..25e0152fd38 100644--- a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js+++ b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js@@ -24,6 +24,7 @@ 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 reorderableList from "../components/sections/molecules/reorderable-list";import rovingFocus from "../components/sections/molecules/roving-focus";import segmentedControl from "../components/sections/molecules/segmented-control";import signupCta from "../components/sections/molecules/signup-cta";@@ -95,6 +96,7 @@ const SECTIONS = [{ component: menus, category: "molecules", id: "menus" },{ component: contextMenu, category: "molecules", id: "context-menu" },{ component: multiselect, category: "molecules", id: "multi-select" },+ { component: reorderableList, category: "molecules", id: "reorderable-list" },{ component: toasts, category: "molecules", id: "toasts" },{ component: dialog, category: "molecules", id: "dialog" },{ component: dragAndDrop, category: "molecules", id: "drag-and-drop" },diff --git a/plugins/styleguide/assets/stylesheets/styleguide.scss b/plugins/styleguide/assets/stylesheets/styleguide.scssindex 63b311e7b62..93ae78bfc7c 100644--- a/plugins/styleguide/assets/stylesheets/styleguide.scss+++ b/plugins/styleguide/assets/stylesheets/styleguide.scss@@ -956,6 +956,88 @@}}+.styleguide-reorderable-list {+ max-width: 22em;+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);++ &__label {+ flex: 1 1 auto;+ }++ &__input {+ flex: 1 1 auto;+ min-width: 0;+ }++ &__note {+ flex: 0 0 auto;+ color: var(--primary-medium);+ font-size: var(--font-down-2);+ }++ .d-reorderable-list__row {+ padding: 0.35em 0.75em;++ &:hover {+ background: var(--d-hover);+ }++ /* Inputs carry a default bottom margin, which pushes the box above the+ row's centre line and leaves it out of step with the controls. Scoped to+ the row so it outranks the attribute selector that sets it. */++ input {+ margin-bottom: 0;+ }+ }++ .d-reorderable-list__create {+ padding: 0.35em 0.75em;+ }+}++.styleguide-reorderable-list-group {+ display: flex;+ flex-wrap: wrap;+ gap: 1.5em;++ &__panel {+ flex: 1 1 14em;+ max-width: 22em;++ h4 {+ margin-bottom: 0.5em;+ }+ }+}++.styleguide-reorderable-table {+ width: 100%;+ max-width: 30em;+ border-collapse: collapse;++ /* The grip's column, sized to the grip. A table shares its free width out+ among the columns, so without a width of its own this one takes a third of+ the table to hold a 24px control. A width below the content's minimum is+ raised to it, which is what makes `1px` mean "no wider than the grip". */++ &__reorder {+ width: 1px;+ white-space: nowrap;+ }++ th {+ padding: 0.35em 0.5em;+ border-block-end: 1px solid var(--primary-low);+ text-align: start;+ }++ td {+ padding: 0.35em 0.5em;+ }+}+.styleguide-shortcut-spellings {th,td {diff --git a/plugins/styleguide/config/locales/client.en.yml b/plugins/styleguide/config/locales/client.en.ymlindex 5b8993f3717..7d86ac5a892 100644--- a/plugins/styleguide/config/locales/client.en.yml+++ b/plugins/styleguide/config/locales/client.en.yml@@ -61,6 +61,54 @@ en:declined: "Last right-click: declined, the browser took it"multi_select:title: "Multi select"+ reorderable_list:+ title: "Reorderable list"+ groups:+ aria_label: "Reorderable list example groups"+ start:+ title: "Start here"+ description: "The default shell: one handle per row that drags, opens the move menu, and takes the keyboard."+ policies:+ title: "Row policies"+ description: "Which rows may move and which may go: pinned rows that keep their slot, and protected rows that offer no way out."+ content:+ title: "Interactive row content"+ description: "Rows carrying their own live controls — toggles and inputs. They keep their normal focus and clicks; the list only claims the handle."+ layouts:+ title: "Cell layouts"+ description: "Manual placement for table-shaped rows: the list renders the rows, and the pre-wired controls go wherever a cell needs them."+ groups:+ title: "Multiple lists"+ description: "Lists registered under one group accept each other's rows, by drag or from the move menu."+ description: "Interactive examples of DReorderableList: dragging, the move menu behind each handle, the keyboard accelerators, pinned rows, cross-list groups, removal, and inline creation."+ basic_example: "Default list"+ basic_description: "The out-of-the-box shell. Each row has one control, the handle: it is the drag grip, and it opens a menu of move destinations. Tab reaches every handle in document order alongside the rows' own controls, and the arrow keys walk between handles as a shortcut. Every real move announces the new position, and a move refused at either end says so rather than doing nothing."+ basic_try_this: "Tab to a handle and press Enter for the move menu, or press the arrow keys to walk the list. Alt with an arrow moves the row itself; Alt with Home or End sends it to an end."+ policies_example: "Pinned and required rows"+ policies_description: "Two predicates, two policies, both subtractive. A row the movable predicate excludes renders no handle and keeps its exact slot, wherever it sits — this list pins its first and last rows, and the rows around them move within the slots that are left. A row the removable predicate excludes renders no remove control, so a protected row offers nothing that cannot be acted on."+ policies_try_this: "Send the first movable row to the bottom from its menu: neither pinned row shifts. The required row has no remove control at all."+ policies_pinned: "Pinned"+ policies_required: "Required"+ toggles_example: "Rows with toggles"+ toggles_description: "The admin-dashboard pattern: rows carry their own interactive controls, which keep their normal focus and clicks. Rows toggled off stay in the list but stop being movable — they keep their slot and lose their handle, rather than disappearing into a separate block."+ toggles_try_this: "Turn a toggle off and the row keeps its place but can no longer be moved. Reorder the rows around it and watch it stay put."+ editable_example: "Editable rows"+ editable_description: "The settings value-list pattern with stable identity: an input per row, the handle leading and the list's own remove control trailing. Typing stays in the input, and Tab moves through the row's own controls the way it does anywhere else."+ editable_try_this: "Edit a value, then remove a row — the removal is announced and focus lands on the row that took its place."+ table_example: "Native table rows, manual placement"+ table_description: "Manual placement for cell layouts: the list renders the table body and its rows, and yields pre-wired controls for the row to place — here the handle occupies the first column."+ table_try_this: "Drag a handle, or press Enter on one: the reorder control lives in the first cell and the whole row moves."+ table_field: "Field"+ table_type: "Type"+ cross_list_example: "Cross-list moves"+ cross_list_description: "Lists registered under one group accept each other's rows. Dragging carries a row across, and each handle's menu lists the sibling lists by name, so the move is reachable without a pointer. An emptied list keeps accepting drops."+ cross_list_try_this: "Drag a row from Primary into Secondary, or open a row's menu and choose the other list by name."+ cross_list_empty: "Drop a row here"+ cross_list_primary: "Primary"+ cross_list_secondary: "Secondary"+ create_example: "Create affordance"+ create_description: "With create enabled the list renders an input after the rows, so appending belongs to the same component that reorders."+ create_try_this: "Type a fruit name and press Enter."toasts:title: "Toasts"font_scale:diff --git a/plugins/styleguide/spec/system/smoke_test_spec.rb b/plugins/styleguide/spec/system/smoke_test_spec.rbindex ffe17df6ba3..5d43b54d07f 100644--- a/plugins/styleguide/spec/system/smoke_test_spec.rb+++ b/plugins/styleguide/spec/system/smoke_test_spec.rb@@ -36,6 +36,7 @@ RSpec.describe "Styleguide Smoke Test" do{ href: "/molecules/navigation-bar", title: "Navigation Bar" },{ href: "/molecules/navigation-stacked", title: "Navigation Stacked" },{ href: "/molecules/post-menu", title: "Post Menu" },+ { href: "/molecules/reorderable-list", title: "Reorderable list" },{ href: "/molecules/roving-focus", title: "Roving focus" },{ href: "/molecules/signup-cta", title: "Signup CTA" },{ href: "/molecules/multi-select", title: "Multi select" },diff --git a/plugins/styleguide/test/javascripts/integration/components/reorderable-list-examples-test.gjs b/plugins/styleguide/test/javascripts/integration/components/reorderable-list-examples-test.gjsnew file mode 100644index 00000000000..b78b72eb827--- /dev/null+++ b/plugins/styleguide/test/javascripts/integration/components/reorderable-list-examples-test.gjs@@ -0,0 +1,187 @@+import { click, fillIn, findAll, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import DMenus from "discourse/float-kit/components/d-menus";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import ReorderableListBasicExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/reorderable-list/basic";+import ReorderableListCreateExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/reorderable-list/create";+import ReorderableListCrossListExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/reorderable-list/cross-list";+import ReorderableListEditableExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/reorderable-list/editable";+import ReorderableListPoliciesExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/reorderable-list/policies";+import ReorderableListTableExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/reorderable-list/table";+import ReorderableListTogglesExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/reorderable-list/toggles";++module(+ "Styleguide | Integration | reorderable-list examples",+ function (hooks) {+ setupRenderingTest(hooks);++ test("the basic example renders and commits a menu move", async function (assert) {+ await render(+ <template><DMenus /><ReorderableListBasicExample /></template>+ );++ assert+ .dom(".d-reorderable-list__row")+ .exists({ count: 4 }, "every fixture row renders");++ await click("[data-reorderable-key='inbox'] .d-reorderable-list__handle");+ assert+ .dom(".d-reorderable-list__move-item")+ .exists(+ { count: 2 },+ "the handle opens its move menu, holding what the first row can reach"+ );++ await click(".d-reorderable-list__move-item.--down");+ assert.deepEqual(+ findAll(".d-reorderable-list__row")+ .map((row) => row.dataset.reorderableKey)+ .slice(0, 2),+ ["starred", "inbox"],+ "the chosen destination applies the proposed order"+ );+ });++ test("the policies example subtracts the control each policy refuses", async function (assert) {+ await render(+ <template><DMenus /><ReorderableListPoliciesExample /></template>+ );++ assert+ .dom(+ "[data-reorderable-key='announcements'] .d-reorderable-list__handle"+ )+ .doesNotExist("a pinned row renders no handle");+ assert+ .dom("[data-reorderable-key='bookmarks'] .d-reorderable-list__handle")+ .doesNotExist("at either end of the list");+ assert+ .dom("[data-reorderable-key='categories'] .d-reorderable-list__remove")+ .doesNotExist(+ "and a protected row renders no remove control rather than a dead one"+ );+ assert+ .dom("[data-reorderable-key='categories'] .d-reorderable-list__handle")+ .exists("while still being movable, since the policies are separate");+ assert+ .dom(".d-reorderable-list__row:last-child")+ .hasAttribute(+ "data-reorderable-key",+ "bookmarks",+ "the bottom-pinned row keeps the last slot"+ );+ });++ test("the basic example gives every row a reachable handle", async function (assert) {+ await render(+ <template><DMenus /><ReorderableListBasicExample /></template>+ );++ assert+ .dom("button.d-reorderable-list__handle")+ .exists({ count: 4 }, "every row renders a real handle button");+ assert+ .dom("button.d-reorderable-list__handle[tabindex='-1']")+ .doesNotExist("none is held out of the tab sequence");+ assert+ .dom(".d-reorderable-list__row[tabindex]")+ .doesNotExist("and the row itself is not a focus target");+ });++ test("the cross-list example renders both grouped members", async function (assert) {+ await render(+ <template><DMenus /><ReorderableListCrossListExample /></template>+ );++ assert+ .dom(".d-reorderable-list")+ .exists({ count: 2 }, "both member lists render");+ });++ test("the toggles example moves rows between the order and the static block", async function (assert) {+ await render(+ <template><DMenus /><ReorderableListTogglesExample /></template>+ );++ assert+ .dom(".d-reorderable-list__row .d-reorderable-list__handle")+ .exists({ count: 3 }, "the enabled rows carry reorder controls");+ assert+ .dom("[data-reorderable-key='backups'] .d-reorderable-list__handle")+ .doesNotExist("a static row carries no controls");++ await click(+ "[data-reorderable-key='backups'] .d-toggle-switch__checkbox"+ );+ assert+ .dom("[data-reorderable-key='backups'] .d-reorderable-list__handle")+ .exists("toggling a static row on makes it reorderable");++ await click(+ "[data-reorderable-key='summary'] .d-toggle-switch__checkbox"+ );+ assert+ .dom("[data-reorderable-key='summary'] .d-reorderable-list__handle")+ .doesNotExist("toggling an enabled row off drops it out of the order");+ });++ test("the editable example keeps typing in the input and removes rows", async function (assert) {+ await render(+ <template><DMenus /><ReorderableListEditableExample /></template>+ );++ await fillIn(+ "[data-reorderable-key='rules'] input",+ "Read the guidelines"+ );+ assert+ .dom("[data-reorderable-key='rules'] input")+ .hasValue("Read the guidelines", "typing lands in the row's input");++ await click("[data-reorderable-key='rules'] .d-reorderable-list__remove");+ assert+ .dom("[data-reorderable-key='rules']")+ .doesNotExist("the remove button deletes the row");+ assert+ .dom(".d-reorderable-list__row")+ .exists({ count: 2 }, "the remaining rows survive");+ });++ test("the table example reorders native rows with manual cell controls", async function (assert) {+ await render(+ <template><DMenus /><ReorderableListTableExample /></template>+ );++ assert+ .dom("tbody.d-reorderable-list tr.d-reorderable-list__row")+ .exists({ count: 3 }, "the list renders native table rows");+ assert+ .dom(+ "tr[data-reorderable-key='name'] td:first-child .d-reorderable-list__handle"+ )+ .exists("the controls sit in the first cell");++ await click(+ "tr[data-reorderable-key='name'] .d-reorderable-list__handle"+ );+ await click(".d-reorderable-list__move-item.--down");+ assert.deepEqual(+ findAll("tr.d-reorderable-list__row").map(+ (row) => row.dataset.reorderableKey+ ),+ ["location", "name", "website"],+ "the chosen destination reorders the table rows"+ );+ });++ test("the create example renders the create affordance", async function (assert) {+ await render(+ <template><DMenus /><ReorderableListCreateExample /></template>+ );++ assert+ .dom(".d-reorderable-list__create-input")+ .exists("the create input renders");+ });+ }+);diff --git a/spec/system/page_objects/components/reorderable_list.rb b/spec/system/page_objects/components/reorderable_list.rbnew file mode 100644index 00000000000..8060b9229ad--- /dev/null+++ b/spec/system/page_objects/components/reorderable_list.rb@@ -0,0 +1,68 @@+# frozen_string_literal: true++module PageObjects+ module Components+ # Drives a `DReorderableList` row.+ #+ # A move is two interactions rather than one — open the row's handle menu,+ # then choose a destination — so every surface that reorders would+ # otherwise repeat the pair. Naming the destination also keeps a page+ # object readable when a grouped list adds cross-list entries and the+ # menu's positions shift.+ class ReorderableList < PageObjects::Components::Base+ HANDLE = ".d-reorderable-list__handle"++ # @param row_selector [String] CSS reaching the row to operate on.+ # @param handle [String] CSS reaching that row's own handle, relative to+ # it. The default descendant selector is ambiguous for a row hosting a+ # list of its own, whose rows carry handles of the same class; pass+ # "> #{HANDLE}" there, or whatever names the row's own.+ def initialize(row_selector, handle: HANDLE)+ @row_selector = row_selector+ @handle = handle+ end++ def open_menu+ find("#{@row_selector} #{@handle}").click+ self+ end++ # @param target [Symbol, String] :top, :up, :down, :bottom, or :list.+ def move(target)+ open_menu+ find(destination_selector(target)).click+ self+ end++ # A destination the row cannot take is not rendered, so the menu holds+ # only what it can reach and the set it publishes matches it.+ def has_destination?(target)+ open_menu+ result = has_css?(destination_selector(target))+ close_menu+ result+ end++ def has_no_destination?(target)+ open_menu+ result = has_no_css?(destination_selector(target))+ close_menu+ result+ end++ def has_handle?+ has_css?("#{@row_selector} #{@handle}")+ end++ private++ def close_menu+ send_keys(:escape)+ end++ def destination_selector(target)+ ".d-reorderable-list__move-item.--#{target}"+ end+ end+ end+end