A platform for community discussion. Free, open, simple.
DEV: Move core's reorder surfaces onto `DReorderableList` (#42995)
Sérgio Saquetim8a6ab1be0657
diff --git a/app/assets/stylesheets/admin/admin_base.scss b/app/assets/stylesheets/admin/admin_base.scssindex 8e428e6972c..64396d60739 100644--- a/app/assets/stylesheets/admin/admin_base.scss+++ b/app/assets/stylesheets/admin/admin_base.scss@@ -1402,3 +1402,37 @@ a.inline-editable-field {@import "admin/discourse_id";@import "admin/admin_new_category_setup";@import "admin/admin_emoji";++/* The reordering surface behind `enable_new_reordering_controls`. These class+ names exist only in the new markup, so the rules are inert while the legacy+ value lists render and the legacy rules above stay untouched.++ TODO (ui-kit-reorderable-list-cleanup) fold back into the `.value-list` block+ above once the change ships. */++.value-list .value {+ .d-reorderable-list__remove {+ margin-left: 0.25em;+ flex: 0 0 auto;++ @include value-btn;+ }++ /* A closed set is reordered and removed, never typed into. It keeps the+ field's footprint so rows line up with the free-text variant, but reads as+ filled rather than editable. */++ .value-input.--readonly {+ display: flex;+ align-items: center;+ min-height: 2em;+ padding: 0 0.5em;+ background: var(--primary-very-low);+ border: 1px solid var(--primary-low);+ color: var(--primary);+ cursor: default;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+}diff --git a/app/assets/stylesheets/admin/admin_dashboard.scss b/app/assets/stylesheets/admin/admin_dashboard.scssindex 1227087013d..ee48f96942b 100644--- a/app/assets/stylesheets/admin/admin_dashboard.scss+++ b/app/assets/stylesheets/admin/admin_dashboard.scss@@ -632,3 +632,54 @@ $db-bar-height: var(--space-2);}}}++/* The reordering surface behind `enable_new_reordering_controls`. Keyed on the+ classes the shared list puts on its own root and rows, so these rules are+ inert while the legacy rows render and need no flag scoping.++ TODO (ui-kit-reorderable-list-cleanup) fold back into the blocks above once+ the change ships. */++.db-configure__list.d-reorderable-list {+ /* Rows tile edge to edge instead. A gap belongs to the container, so a drag+ crossing it reaches no drop target and the above/below zones stop meeting. */+ gap: normal;+}++.db-configure__row.d-reorderable-list__row {+ padding: calc(var(--space-3) / 2 + var(--space-half)) 0;++ /* The grip carries its own cursor; promising the whole row drags would+ misdescribe a press on the label, which selects. */+ cursor: auto;++ @include viewport.until(sm) {+ padding: calc(var(--space-5) / 2 + var(--space-half)) 0;+ }++ /* One boundary, one line. A row's own top border and its predecessor's bottom+ border are adjacent bands rather than the same pixels, so drawing each state+ on its own row would shift the indicator by its own width as the pointer+ crossed the midpoint. "Above row N" is drawn on row N-1's bottom edge, and+ the shared primitive's inserted line is dropped rather than overridden so+ both never show at once. */++ &.--drag-below,+ &:not(.--dragging):has(+ .db-configure__row.--drag-above) {+ border-bottom-color: var(--d-drag-indicator-color);+ }++ /* No predecessor to borrow an edge from. */+ &.--drag-above:first-child {+ border-top-color: var(--d-drag-indicator-color);+ }++ &.--drag-above::before,+ &.--drag-below::after {+ content: none;+ }++ .d-reorderable-list__handle {+ color: var(--primary-low-mid);+ }+}diff --git a/app/assets/stylesheets/admin/badges.scss b/app/assets/stylesheets/admin/badges.scssindex d9752b49223..aab7e5570c9 100644--- a/app/assets/stylesheets/admin/badges.scss+++ b/app/assets/stylesheets/admin/badges.scss@@ -257,3 +257,34 @@}}}++/* The reordering surface behind `enable_new_reordering_controls`.+ TODO (ui-kit-reorderable-list-cleanup) fold back above once the change+ ships. */++.badge-groupings-modal {+ .badge-groupings-list {+ /* The name takes the slack, so the actions stay against the row's end while+ the grip stays against its start. */++ .badge-grouping-item.d-reorderable-list__row {+ justify-content: normal;+ gap: 0.5em;++ .badge-grouping {+ flex: 1 1 auto;+ }++ .badge-grouping-name-input {+ margin: 0;+ }++ /* Keeps the row's buttons on one line rather than stacking them. */+ .actions {+ display: flex;+ align-items: center;+ gap: 0.25em;+ }+ }+ }+}diff --git a/app/assets/stylesheets/common/base/directory.scss b/app/assets/stylesheets/common/base/directory.scssindex 203ed2d669e..52a34f1b5ec 100644--- a/app/assets/stylesheets/common/base/directory.scss+++ b/app/assets/stylesheets/common/base/directory.scss@@ -377,3 +377,24 @@}}}++/* The reordering surface behind `enable_new_reordering_controls`.+ TODO (ui-kit-reorderable-list-cleanup) fold back above once the change+ ships. */++.edit-user-directory-columns-modal {+ .edit-directory-columns-container {+ .edit-directory-column.d-reorderable-list__row {+ justify-content: normal;+ align-items: center;+ gap: var(--space-2);++ /* The global nudge on checkboxes aligns them to a text baseline; in a+ centred flex row it only sits the box below the label and the grip. */++ input[type="checkbox"] {+ margin-top: 0;+ }+ }+ }+}diff --git a/app/assets/stylesheets/common/base/sidebar.scss b/app/assets/stylesheets/common/base/sidebar.scssindex d2d13f8ebef..2f11c8bf17f 100644--- a/app/assets/stylesheets/common/base/sidebar.scss+++ b/app/assets/stylesheets/common/base/sidebar.scss@@ -581,3 +581,101 @@height: 0.85em;}}++/* The section form's links region behind `enable_new_reordering_controls`.+ Keyed on the classes the shared list puts on its own root and rows, so every+ rule here outranks the legacy one it replaces without depending on stylesheet+ order, and none of it applies while the legacy rows render.++ TODO (ui-kit-reorderable-list-cleanup) fold back into the blocks above once+ the change ships. */++.sidebar-section-form-modal {+ /* The tracks live on the wrapper and every row reaches them through subgrid,+ so the header and the rows resolve one set of columns. */++ .sidebar-section-form__links-wrapper.d-reorderable-list {+ display: grid;+ grid-template-columns: 2em 4.5em repeat(2, 1fr) 2em;++ @include viewport.until(sm) {+ /* grip, icon, name, delete; the url line spans beneath them. */+ grid-template-columns: auto 4em 1fr min-content;+ }+ }++ .row-wrapper.d-reorderable-list__row {+ grid-column: 1 / -1;+ grid-template-columns: subgrid;++ /* One midline for every cell, which otherwise stretch and each settle at+ their own height. */+ align-items: center;++ .link-icon {+ grid-column: 2;+ }++ @include viewport.until(sm) {+ row-gap: 0.5em;++ /* A phone-width row cannot fit every column, so the url takes a second+ line and the controls flank both. */++ .d-reorderable-list__handle {+ grid-row: 1 / 3;+ }++ .link-url {+ grid-row: 2;+ grid-column: 2 / -1;+ }++ .delete-link {+ grid-row: 1;+ grid-column: 4;+ }+ }++ /* Drawn on the row's own reserved border so adjacent rows keep sharing one+ gutter. The shared primitive's inserted line is dropped rather than+ overridden, or both would show at once. */++ &.--drag-above {+ border-top: 2px solid var(--d-drag-indicator-color);++ &::before {+ content: none;+ }+ }++ &.--drag-below {+ border-bottom: 2px solid var(--d-drag-indicator-color);++ &::after {+ content: none;+ }+ }+ }++ /* The header is the list's own block, not one of its rows, so it is reached+ through the list root rather than the row selector.++ Two-line rows have no columns for these to head; each control names itself,+ and the picker shows its icon. */++ .d-reorderable-list .row-wrapper.header {+ /* The tracks live on the wrapper, so the header has to reach them the same+ way a row does or its labels stop sitting over the columns they name. */+ grid-column: 1 / -1;+ grid-template-columns: subgrid;++ @include viewport.until(sm) {+ display: none;+ }+ }++ [data-drag-source].--dragging {+ opacity: 0.4;+ }+}diff --git a/app/assets/stylesheets/common/components/table-layout.scss b/app/assets/stylesheets/common/components/table-layout.scssindex 324ea1e7fbc..610943b8fe5 100644--- a/app/assets/stylesheets/common/components/table-layout.scss+++ b/app/assets/stylesheets/common/components/table-layout.scss@@ -206,6 +206,17 @@}}+/* The drag handle's column, sized to the handle. A table shares its free width+ out among its columns, so without a width of its own this one takes a share 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 handle". */++.d-table__cell.--drag-handle,+.d-table__header-cell.--drag-handle {+ width: 1px;+ white-space: nowrap;+}+.d-table__cell.--controls {text-align: right;width: auto;diff --git a/app/assets/stylesheets/common/modal/manageable-row-list.scss b/app/assets/stylesheets/common/modal/manageable-row-list.scssindex db516115468..eea4afa47f7 100644--- a/app/assets/stylesheets/common/modal/manageable-row-list.scss+++ b/app/assets/stylesheets/common/modal/manageable-row-list.scss@@ -144,3 +144,33 @@font-size: var(--font-down-1);}}++/* The reordering surface behind `enable_new_reordering_controls`.+ TODO (ui-kit-reorderable-list-cleanup) fold back above once the change+ ships. */++.manageable-row-list {+ &__row-content {+ display: flex;+ flex: 1 1 auto;+ align-items: center;+ gap: var(--space-3);+ min-width: 0;+ }++ /* The grip carries its own cursor; promising the whole row drags would+ misdescribe a press on the label, which selects. */++ &__row.d-reorderable-list__row[draggable="true"] {+ cursor: auto;+ }++ /* A row that cannot move renders no grip at all, so its text would start at+ the row's own edge while a movable neighbour's starts past the grip, and+ the column reads ragged. Reserve the grip's footprint instead: 24px is the+ size the shared list gives it, plus the row's own gap. */++ &__row.d-reorderable-list__row:not(:has(.d-reorderable-list__handle)) {+ padding-inline-start: calc(var(--space-6) + 24px + var(--space-3));+ }+}diff --git a/app/controllers/admin/config/flags_controller.rb b/app/controllers/admin/config/flags_controller.rbindex 815535dfd2c..11830a4519e 100644--- a/app/controllers/admin/config/flags_controller.rb+++ b/app/controllers/admin/config/flags_controller.rb@@ -74,6 +74,22 @@ class Admin::Config::FlagsController < Admin::AdminControllerendend+ def move+ Flags::MoveFlag.call(service_params) do+ on_success do+ Discourse.request_refresh!+ head :no_content+ end+ on_failure { render(json: failed_json, status: :unprocessable_entity) }+ on_model_not_found(:flag) { raise Discourse::NotFound }+ on_failed_policy(:invalid_access) { raise Discourse::InvalidAccess }+ on_failed_policy(:invalid_move) { render_json_error(I18n.t("flags.errors.wrong_move")) }+ on_failed_contract do |contract|+ render(json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request)+ end+ end+ end+def destroyFlags::DestroyFlag.call(service_params) doon_success dodiff --git a/app/services/flags/move_flag.rb b/app/services/flags/move_flag.rbnew file mode 100644index 00000000000..de93e6c2bcd--- /dev/null+++ b/app/services/flags/move_flag.rb@@ -0,0 +1,57 @@+# frozen_string_literal: true++class Flags::MoveFlag+ include Service::Base++ params do+ attribute :flag_id, :integer+ attribute :position, :integer++ validates :flag_id, presence: true+ validates :position, numericality: { only_integer: true, greater_than_or_equal_to: 0 }+ end++ model :flag+ policy :invalid_access+ model :reorderable_flags+ policy :invalid_move++ transaction do+ step :move+ step :log+ end++ private++ def fetch_flag(params:)+ Flag.find_by(id: params.flag_id)+ end++ def invalid_access(guardian:, flag:)+ guardian.can_reorder_flag?(flag)+ end++ def fetch_reorderable_flags+ Flag.where.not(name_key: "notify_user").order(:position).to_a+ end++ def invalid_move(params:, reorderable_flags:)+ params.position < reorderable_flags.size+ end++ def move(flag:, params:, reorderable_flags:)+ positions = reorderable_flags.map(&:position)+ reordered_flags = (reorderable_flags - [flag]).insert(params.position, flag)++ reordered_flags+ .zip(positions)+ .each { |reordered_flag, position| reordered_flag.update!(position:) }+ end++ def log(guardian:, flag:, params:)+ StaffActionLogger.new(guardian.user).log_custom(+ "move_flag",+ { flag: flag.name, position: params.position },+ )+ end+enddiff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex ab33af79434..cacaf53b017 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -3155,6 +3155,7 @@ en:enable_auto_grid_images: "Automatically wraps images in [grid] tags when 3 or more images are uploaded in the composer."enable_new_checkbox_style: "Enable the redesigned checkbox style for FormKit checkboxes."enable_composer_redesign: "Enable the redesigned composer."+ enable_new_reordering_controls: "Use the shared reordering controls on list settings, admin lists, the user directory columns and sidebar links, giving each one the same drag handle, move menu and keyboard support."enable_main_outlet_grid_layout_change: "Place the composer inside the main layout grid so themes can position it in a grid column, and use a narrower sidebar."enable_composer_toolbar_customization: "Let members choose which buttons appear in their composer toolbar, from their interface preferences."prioritize_recently_used_tags: "When adding tags while creating or editing a topic, show the tags the member has recently used on their own topics at the top of the list, before the most popular tags of the forum."diff --git a/config/routes.rb b/config/routes.rbindex e5ab357bc9a..e94c02fd048 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -530,6 +530,7 @@ Discourse::Application.routes.draw doresources :flags, only: %i[index new create update destroy] doput "toggle"put "reorder/:direction" => "flags#reorder"+ put "move"member { get "/" => "flags#edit" }enddiff --git a/config/site_settings.yml b/config/site_settings.ymlindex 1d741a36d82..5d8f8c6751e 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -4829,6 +4829,15 @@ experimental:impact: "feature,all_members"learn_more_url: "https://meta.discourse.org/t/-/403284"body_class: true+ enable_new_reordering_controls:+ default: false+ client: true+ hidden: true+ area: "experimental"+ upcoming_change:+ status: "alpha"+ impact: "feature,all_members"+ learn_more_url: "https://meta.discourse.org/t/-/414613"enable_composer_redesign:default: falseclient: truediff --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 29575bd92c6..f94a49ca857 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@@ -100,6 +100,7 @@ Form-level composition belongs to [FormKit](22-form-kit.md). These are the under| `DTabs` | Tab panels switched in place, with the strip, keyboard cursor, and ARIA pairing built in. | [Tabs](https://meta.discourse.org/styleguide/molecules/tabs) || `DResponsiveTable`, `DTableHeaderToggle` | Tables that stay usable on narrow viewports, with sortable column headers. | || `DVirtualList` | Long lists that render only the rows in view. | [Virtual list](https://meta.discourse.org/styleguide/molecules/virtual-list) |+| `DReorderableList`, `DReorderableListGroup` | Lists the user can reorder by drag, a move menu, or the keyboard. The group lets a row move between lists. | [Reorderable list](https://meta.discourse.org/styleguide/molecules/reorderable-list) || `DStatTiles` | Rows of headline numbers. | || `DTapTileGrid`, `DTapTile` | Grids of tappable choices. | || `DPostAccordion`, `DPostAccordionItem` | Collapsible sections. | |diff --git a/docs/developer-guides/docs/03-code-internals/30-drag-and-gesture-primitives.md b/docs/developer-guides/docs/03-code-internals/30-drag-and-gesture-primitives.mdindex 2ce01c31f28..b8e7c783109 100644--- a/docs/developer-guides/docs/03-code-internals/30-drag-and-gesture-primitives.md+++ b/docs/developer-guides/docs/03-code-internals/30-drag-and-gesture-primitives.md@@ -548,6 +548,10 @@ someone change a size, use one of the resize primitives above.drag with a keyboard path, and every resize between regions should use thekeyboard support already in `DResizeSeparator` or `dResizeEdge`.+**For a list the user puts in order, use `DReorderableList`.** It pairs the+drag with a move menu and keyboard shortcuts, and it announces each completed+move. See the [UI kit guide](02-ui-kit.md).+**Announce the outcome, not the movement.** A completed reorder reports theitem's new visible position once through `a11y.announce()`. A no-op announcesnothing, and moving the pointer across drop indicators announces nothing.diff --git a/frontend/discourse/admin/components/admin-badges.gjs b/frontend/discourse/admin/components/admin-badges.gjsindex 6a350aaa67e..d07db8cab57 100644--- a/frontend/discourse/admin/components/admin-badges.gjs+++ b/frontend/discourse/admin/components/admin-badges.gjs@@ -2,6 +2,7 @@ import Component from "@glimmer/component";import { action } from "@ember/object";import { service } from "@ember/service";import EditBadgeGroupingsModal from "discourse/admin/components/modal/edit-badge-groupings";+import EditBadgeGroupingsModalReorderable from "discourse/admin/components/modal/edit-badge-groupings-reorderable";import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";import DNavItem from "discourse/ui-kit/d-nav-item";import DPageHeader from "discourse/ui-kit/d-page-header";@@ -10,6 +11,7 @@ import { i18n } from "discourse-i18n";export default class AdminBadges extends Component {@service adminBadges;@service modal;+ @service siteSettings;get badges() {return this.adminBadges.badges;@@ -17,7 +19,13 @@ export default class AdminBadges extends Component {@actioneditGroupings() {- this.modal.show(EditBadgeGroupingsModal, {+ // TODO (ui-kit-reorderable-list-cleanup) drop the branch and the legacy+ // component once the change ships.+ const Modal = this.siteSettings.enable_new_reordering_controls+ ? EditBadgeGroupingsModalReorderable+ : EditBadgeGroupingsModal;++ this.modal.show(Modal, {model: {badgeGroupings: this.adminBadges.badgeGroupings,updateGroupings: (groupings) => {diff --git a/frontend/discourse/admin/components/admin-config-areas/flags-reorderable.gjs b/frontend/discourse/admin/components/admin-config-areas/flags-reorderable.gjsnew file mode 100644index 00000000000..2d489298a27--- /dev/null+++ b/frontend/discourse/admin/components/admin-config-areas/flags-reorderable.gjs@@ -0,0 +1,137 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { service } from "@ember/service";+import AdminFlagItemReorderable from "discourse/admin/components/admin-flag-item-reorderable";+import { SYSTEM_FLAG_IDS } from "discourse/admin/lib/constants";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { removeValueFromArray } from "discourse/lib/array-tools";+import { autoTrackedArray } from "discourse/lib/tracked-tools";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import { i18n } from "discourse-i18n";++/**+ * The reordering surface behind `enable_new_reordering_controls`. Mirrors+ * `admin-config-areas/flags.gjs`, over the shared reorderable list.+ *+ * TODO (ui-kit-reorderable-list-cleanup) rename this over `admin-config-areas/flags.gjs`+ * and drop the branch in the flags config template.+ */+export default class AdminConfigAreasFlags extends Component {+ @service site;++ /**+ * Flags with a request in flight, so their rows can drop the `saved`+ * marker while a toggle, delete, or reorder is being persisted. Held here+ * because the list owns the row elements the marker paints.+ */+ @tracked pendingIds = new Set();+ @autoTrackedArray flags = this.site.flagTypes;++ flagLabel = (flag) => flag.name;++ movable = (flag) => flag.id !== SYSTEM_FLAG_IDS.notify_user;++ rowClass = (flag) =>+ dConcatClass(+ "d-table__row admin-flag-item",+ flag.name_key,+ this.pendingIds.has(flag.id) ? null : "saved"+ );++ @action+ setPending(flag, pending) {+ const next = new Set(this.pendingIds);+ if (pending) {+ next.add(flag.id);+ } else {+ next.delete(flag.id);+ }+ this.pendingIds = next;+ }++ /**+ * Applies a committed move optimistically and persists where the flag+ * landed, rolling back on failure. The server orders only the flags that+ * can move, so the position sent is the flag's place among those.+ *+ * @param {Object} move - The normalized move from the list.+ */+ @action+ async handleMove(move) {+ const fallbackFlags = [...this.flags];+ this.setPending(move.item, true);+ this.flags.splice(0, this.flags.length, ...move.proposedToItems);++ try {+ await ajax(`/admin/config/flags/${move.item.id}/move`, {+ type: "PUT",+ data: {+ position: move.proposedToItems+ .filter(this.movable)+ .indexOf(move.item),+ },+ });+ } catch (error) {+ this.flags.splice(0, this.flags.length, ...fallbackFlags);+ return popupAjaxError(error);+ } finally {+ this.setPending(move.item, false);+ }+ }++ @action+ async deleteFlagCallback(flag) {+ try {+ await ajax(`/admin/config/flags/${flag.id}`, {+ type: "DELETE",+ });++ removeValueFromArray(this.flags, flag);+ } catch (error) {+ popupAjaxError(error);+ }+ }++ <template>+ <div class="container admin-flags">+ {{! 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="d-table admin-flags__items">+ <thead class="d-table__header">+ <th class="d-table__header-cell --drag-handle"></th>+ <th class="d-table__header-cell">{{i18n+ "admin.config_areas.flags.description"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "admin.config_areas.flags.enabled"+ }}</th>+ </thead>+ <DReorderableList+ class="d-table__body"+ @controls="manual"+ @items={{this.flags}}+ @itemTag="tr"+ @key="id"+ @label={{this.flagLabel}}+ @movable={{this.movable}}+ @onMove={{this.handleMove}}+ @rowClass={{this.rowClass}}+ @tag="tbody"+ >+ <:row as |flag controls|>+ <AdminFlagItemReorderable+ @controls={{controls}}+ @deleteFlagCallback={{this.deleteFlagCallback}}+ @flag={{flag}}+ @setPending={{this.setPending}}+ />+ </:row>+ </DReorderableList>+ </table>+ </div>+ </template>+}diff --git a/frontend/discourse/admin/components/admin-config-areas/flags.gjs b/frontend/discourse/admin/components/admin-config-areas/flags.gjsindex 80defd96238..e3b6ad812ba 100644--- a/frontend/discourse/admin/components/admin-config-areas/flags.gjs+++ b/frontend/discourse/admin/components/admin-config-areas/flags.gjs@@ -9,6 +9,8 @@ import { bind } from "discourse/lib/decorators";import { autoTrackedArray } from "discourse/lib/tracked-tools";import { i18n } from "discourse-i18n";+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `flags-reorderable.gjs` replaces it.export default class AdminConfigAreasFlags extends Component {@service site;diff --git a/frontend/discourse/admin/components/admin-config-areas/user-fields-list-reorderable.gjs b/frontend/discourse/admin/components/admin-config-areas/user-fields-list-reorderable.gjsnew file mode 100644index 00000000000..58d850e4faa--- /dev/null+++ b/frontend/discourse/admin/components/admin-config-areas/user-fields-list-reorderable.gjs@@ -0,0 +1,135 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { service } from "@ember/service";+import AdminConfigAreaEmptyList from "discourse/admin/components/admin-config-area-empty-list";+import AdminUserFieldItemReorderable from "discourse/admin/components/admin-user-field-item-reorderable";+import UserField from "discourse/admin/models/user-field";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { removeValueFromArray } from "discourse/lib/array-tools";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import { i18n } from "discourse-i18n";++/**+ * The reordering surface behind `enable_new_reordering_controls`. Mirrors+ * `admin-config-areas/user-fields-list.gjs`, over the shared reorderable list.+ *+ * TODO (ui-kit-reorderable-list-cleanup) rename this over `admin-config-areas/user-fields-list.gjs`+ * and drop the branch in the user-fields template.+ */+export default class AdminConfigAreasUserFieldsList extends Component {+ @service dialog;+ @service toasts;+ @service adminUserFields;++ /** @type {any} */+ fieldTypes = UserField.fieldTypes();++ fieldLabel = (field) => field.name;++ get fields() {+ return this.adminUserFields.userFields;+ }++ get sortedFields() {+ return this.adminUserFields.sortedUserFields;+ }++ /**+ * Applies a committed move by renumbering every displaced field from its+ * new slot — a drag can jump several rows, which the old adjacent-swap+ * persistence could not express.+ *+ * @param {Object} move - The normalized move from the list.+ */+ @action+ async handleMove(move) {+ try {+ await Promise.all(+ move.proposedToItems.map((field, index) => {+ const position = index + 1;+ if (field.get("position") === position) {+ return null;+ }+ return field.update({ position });+ })+ );+ } catch (error) {+ popupAjaxError(error);+ }+ }++ @action+ destroyField(field) {+ this.dialog.deleteConfirm({+ title: i18n("admin.user_fields.delete_confirm"),+ didConfirm: () => {+ this.#deleteField(field);+ },+ });+ }++ async #deleteField(field) {+ try {+ await field.destroyRecord();+ removeValueFromArray(this.fields, field);+ this.toasts.success({+ duration: "short",+ data: {+ message: i18n("admin.config_areas.user_fields.delete_successful"),+ },+ });+ } catch (error) {+ popupAjaxError(error);+ }+ }++ <template>+ <div class="container admin-user_fields">+ {{#if this.fields}}+ {{! 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="d-table user-fields">+ <thead class="d-table__header">+ <tr class="d-table__row">+ <th class="d-table__header-cell --drag-handle"></th>+ <th class="d-table__header-cell">{{i18n+ "admin.config_areas.user_fields.field"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "admin.config_areas.user_fields.type"+ }}</th>+ </tr>+ </thead>+ <DReorderableList+ class="d-table__body"+ @controls="manual"+ @items={{this.sortedFields}}+ @itemTag="tr"+ @key="id"+ @label={{this.fieldLabel}}+ @onMove={{this.handleMove}}+ @rowClass="d-table__row admin-user_field-item"+ @tag="tbody"+ >+ <:row as |field controls|>+ <AdminUserFieldItemReorderable+ @controls={{controls}}+ @destroyAction={{this.destroyField}}+ @fieldTypes={{this.fieldTypes}}+ @userField={{field}}+ />+ </:row>+ </DReorderableList>+ </table>+ {{else}}+ <AdminConfigAreaEmptyList+ @ctaClass="admin-user_fields__add-emoji"+ @ctaLabel="admin.user_fields.add"+ @ctaRoute="adminUserFields.new"+ @emptyLabel="admin.user_fields.no_user_fields"+ />+ {{/if}}+ </div>+ </template>+}diff --git a/frontend/discourse/admin/components/admin-config-areas/user-fields-list.gjs b/frontend/discourse/admin/components/admin-config-areas/user-fields-list.gjsindex 804fb04f720..d4e21ccdb9f 100644--- a/frontend/discourse/admin/components/admin-config-areas/user-fields-list.gjs+++ b/frontend/discourse/admin/components/admin-config-areas/user-fields-list.gjs@@ -8,6 +8,8 @@ import { popupAjaxError } from "discourse/lib/ajax-error";import { removeValueFromArray } from "discourse/lib/array-tools";import { i18n } from "discourse-i18n";+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `user-fields-list-reorderable.gjs` replaces it.export default class AdminConfigAreasUserFieldsList extends Component {@service dialog;@service toasts;diff --git a/frontend/discourse/admin/components/admin-flag-item-reorderable.gjs b/frontend/discourse/admin/components/admin-flag-item-reorderable.gjsnew file mode 100644index 00000000000..e213e7288fe--- /dev/null+++ b/frontend/discourse/admin/components/admin-flag-item-reorderable.gjs@@ -0,0 +1,186 @@+/* eslint-disable ember/no-tracked-properties-from-args */+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { LinkTo } from "@ember/routing";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import { SYSTEM_FLAG_IDS } from "discourse/admin/lib/constants";+import DMenu from "discourse/float-kit/components/d-menu";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { not } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";+import { i18n } from "discourse-i18n";++/**+ * The reordering surface behind `enable_new_reordering_controls`. Mirrors+ * `admin-flag-item.gjs`, over the shared reorderable list.+ *+ * TODO (ui-kit-reorderable-list-cleanup) rename this over `admin-flag-item.gjs`+ * and drop the branch in flags-reorderable.gjs.+ */+export default class AdminFlagItem extends Component {+ @service dialog;+ @service router;++ @tracked enabled = this.args.flag.enabled;++ get canMove() {+ return this.args.flag.id !== SYSTEM_FLAG_IDS.notify_user;+ }++ get canEdit() {+ return !this.args.flag.system;+ }++ get canDelete() {+ return this.canEdit && !this.args.flag.is_used;+ }++ get editTitle() {+ return this.canEdit+ ? "admin.config_areas.flags.form.edit_flag"+ : "admin.config_areas.flags.form.non_editable";+ }++ get deleteTitle() {+ return this.canDelete+ ? "admin.config_areas.flags.form.delete_flag"+ : "admin.config_areas.flags.form.non_deletable";+ }++ @action+ toggleFlagEnabled(flag) {+ this.enabled = !this.enabled;+ this.args.setPending(flag, true);++ return ajax(`/admin/config/flags/${flag.id}/toggle`, {+ type: "PUT",+ })+ .then(() => {+ this.args.flag.enabled = this.enabled;+ })+ .catch((error) => {+ this.enabled = !this.enabled;+ return popupAjaxError(error);+ })+ .finally(() => {+ this.args.setPending(flag, false);+ });+ }++ @action+ onRegisterApi(api) {+ this.dMenu = api;+ }++ @action+ edit() {+ this.router.transitionTo("adminConfig.flags.edit", this.args.flag);+ }++ @action+ delete() {+ this.args.setPending(this.args.flag, true);+ this.dialog.yesNoConfirm({+ message: i18n("admin.config_areas.flags.delete_confirm", {+ name: this.args.flag.name,+ }),+ didConfirm: async () => {+ try {+ await this.args.deleteFlagCallback(this.args.flag);+ this.args.setPending(this.args.flag, false);+ this.dMenu.close();+ } catch (error) {+ popupAjaxError(error);+ }+ },+ didCancel: () => {+ this.args.setPending(this.args.flag, false);+ this.dMenu.close();+ },+ });+ }++ <template>+ <td class="d-table__cell --drag-handle">+ {{#if @controls.handle}}<@controls.handle />{{/if}}+ </td>+ <td class="d-table__cell --overview">+ {{#if this.canEdit}}+ <LinkTo+ class="d-table__overview-link"+ @model={{@flag}}+ @route="adminConfig.flags.edit"+ >+ <div+ class="d-table__overview-name admin-flag-item__name"+ >{{@flag.name}}</div>+ <div class="d-table__overview-about">{{trustHTML+ @flag.description+ }}</div>+ </LinkTo>+ {{else}}+ <div+ class="d-table__overview-name admin-flag-item__name"+ >{{@flag.name}}</div>+ <div class="d-table__overview-about">{{trustHTML+ @flag.description+ }}</div>+ {{/if}}+ </td>+ <td class="d-table__cell --detail">+ <div class="d-table__mobile-label">+ {{i18n "admin.config_areas.flags.enabled"}}+ </div>+ <DToggleSwitch+ class="admin-flag-item__toggle {{@flag.name_key}}"+ @state={{this.enabled}}+ {{on "click" (fn this.toggleFlagEnabled @flag)}}+ />+ </td>+ <td class="d-table__cell --controls">+ <div class="d-table__cell-actions">++ <DButton+ class="btn-default btn-small admin-flag-item__edit"+ @action={{this.edit}}+ @disabled={{not this.canEdit}}+ @label="admin.config_areas.flags.edit"+ @title={{this.editTitle}}+ />++ {{#if this.canMove}}+ <DMenu+ @icon="ellipsis-vertical"+ @identifier="flag-menu"+ @onRegisterApi={{this.onRegisterApi}}+ @title={{i18n "admin.config_areas.flags.more_options.title"}}+ @triggerClass="btn-default"+ >+ <:content>+ <DDropdownMenu as |dropdown|>++ <dropdown.item>+ <DButton+ class="btn-transparent --danger admin-flag-item__delete"+ @action={{this.delete}}+ @disabled={{not this.canDelete}}+ @icon="trash-can"+ @label="admin.config_areas.flags.delete"+ @title={{this.deleteTitle}}+ />+ </dropdown.item>+ </DDropdownMenu>+ </:content>+ </DMenu>+ {{/if}}+ </div>+ </td>+ </template>+}diff --git a/frontend/discourse/admin/components/admin-flag-item.gjs b/frontend/discourse/admin/components/admin-flag-item.gjsindex 897c015345e..6cfe34a8303 100644--- a/frontend/discourse/admin/components/admin-flag-item.gjs+++ b/frontend/discourse/admin/components/admin-flag-item.gjs@@ -18,6 +18,8 @@ import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import { i18n } from "discourse-i18n";+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `admin-flag-item-reorderable.gjs` replaces it.export default class AdminFlagItem extends Component {@service dialog;@service router;diff --git a/frontend/discourse/admin/components/admin-user-field-item-reorderable.gjs b/frontend/discourse/admin/components/admin-user-field-item-reorderable.gjsnew file mode 100644index 00000000000..95bed33fe37--- /dev/null+++ b/frontend/discourse/admin/components/admin-user-field-item-reorderable.gjs@@ -0,0 +1,106 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { LinkTo } from "@ember/routing";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import { USER_FIELD_FLAGS } from "discourse/admin/lib/constants";+import UserField from "discourse/admin/models/user-field";+import DMenu from "discourse/float-kit/components/d-menu";+import DButton from "discourse/ui-kit/d-button";+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";+import { i18n } from "discourse-i18n";++/**+ * The reordering surface behind `enable_new_reordering_controls`. Mirrors+ * `admin-user-field-item.gjs`, over the shared reorderable list.+ *+ * TODO (ui-kit-reorderable-list-cleanup) rename this over `admin-user-field-item.gjs`+ * and drop the branch in user-fields-list-reorderable.gjs.+ */+export default class AdminUserFieldItem extends Component {+ @service router;++ get fieldName() {+ return UserField.fieldTypeById(this.fieldType)?.name;+ }++ get flags() {+ return USER_FIELD_FLAGS.map((flag) => {+ if (this.args.userField[flag]) {+ return i18n(`admin.user_fields.${flag}.enabled`);+ }+ })+ .filter(Boolean)+ .join(", ");+ }++ @action+ destroy() {+ this.args.destroyAction(this.args.userField);+ this.dMenu.close();+ }++ @action+ onRegisterApi(api) {+ this.dMenu = api;+ }++ @action+ edit() {+ this.router.transitionTo("adminUserFields.edit", this.args.userField);+ }++ <template>+ <td class="d-table__cell --drag-handle">+ <@controls.handle />+ </td>+ <td class="d-table__cell --overview">+ <LinkTo+ class="d-table__overview-link"+ @model={{@userField}}+ @route="adminUserFields.edit"+ >+ <div class="d-table__overview-name admin-user_field-item__name">+ {{@userField.name}}+ </div>+ <div class="d-table__overview-about">{{trustHTML+ @userField.description+ }}</div>+ </LinkTo>+ <div class="d-table__overview-flags">{{this.flags}}</div>+ </td>+ <td class="d-table__cell --detail">+ {{@userField.fieldTypeName}}+ </td>+ <td class="d-table__cell --controls">+ <div class="d-table__cell-actions">+ <DButton+ class="btn-default btn-small admin-user_field-item__edit"+ @action={{this.edit}}+ @label="admin.user_fields.edit"+ />++ <DMenu+ @icon="ellipsis-vertical"+ @identifier="user_field-menu"+ @onRegisterApi={{this.onRegisterApi}}+ @title={{i18n "admin.config_areas.user_fields.more_options.title"}}+ @triggerClass="btn-default"+ >+ <:content>+ <DDropdownMenu as |dropdown|>+ <dropdown.item>+ <DButton+ class="btn-transparent --danger admin-user_field-item__delete"+ @action={{this.destroy}}+ @icon="trash-can"+ @label="admin.config_areas.user_fields.delete"+ />+ </dropdown.item>+ </DDropdownMenu>+ </:content>+ </DMenu>+ </div>+ </td>+ </template>+}diff --git a/frontend/discourse/admin/components/admin-user-field-item.gjs b/frontend/discourse/admin/components/admin-user-field-item.gjsindex 03a04d148b4..84984842c58 100644--- a/frontend/discourse/admin/components/admin-user-field-item.gjs+++ b/frontend/discourse/admin/components/admin-user-field-item.gjs@@ -10,6 +10,8 @@ import DButton from "discourse/ui-kit/d-button";import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";import { i18n } from "discourse-i18n";+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `admin-user-field-item-reorderable.gjs` replaces it.export default class AdminUserFieldItem extends Component {@service adminUserFields;@service router;diff --git a/frontend/discourse/admin/components/dashboard/configure-menu-reorderable.gjs b/frontend/discourse/admin/components/dashboard/configure-menu-reorderable.gjsnew file mode 100644index 00000000000..2b27103506a--- /dev/null+++ b/frontend/discourse/admin/components/dashboard/configure-menu-reorderable.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 DReorderableList from "discourse/ui-kit/d-reorderable-list";+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";+import { i18n } from "discourse-i18n";++/**+ * The reordering surface behind `enable_new_reordering_controls`. Renders the+ * same sections as `configure-menu.gjs`, over the shared reorderable list.+ *+ * TODO (ui-kit-reorderable-list-cleanup) rename this over `configure-menu.gjs`+ * and drop the branch in `redesigned-admin-dashboard.gjs`.+ */+export default class ConfigureMenu extends Component {+ sectionLabel = (section) =>+ i18n(`admin.dashboard.sections.${section.id}.title`);++ toggleLabel = (section) =>+ i18n("admin.dashboard.configure.toggle_visibility", {+ label: this.sectionLabel(section),+ });++ /**+ * Forwards a committed move to the controlled owner. The list has already+ * normalized both input paths, suppressed no-ops, and announced, so what+ * remains is the owner's own index-based contract.+ *+ * @param {Object} move - The normalized move.+ */+ @action+ handleMove(move) {+ this.args.onReorder(move.fromIndex, move.toIndex);+ }++ <template>+ <div class="db-configure">+ <DReorderableList+ aria-label={{i18n "admin.dashboard.configure.menu_title"}}+ class="db-configure__list"+ @items={{@sections}}+ @key="id"+ @label={{this.sectionLabel}}+ @onMove={{this.handleMove}}+ @rowClass="db-configure__row"+ >+ <:row as |section|>+ <span class="db-configure__section-name">+ {{this.sectionLabel section}}+ </span>++ <DToggleSwitch+ aria-label={{this.toggleLabel section}}+ @state={{section.visible}}+ {{on "click" (fn @onToggleVisibility section.id)}}+ />+ </:row>+ </DReorderableList>+ </div>+ </template>+}diff --git a/frontend/discourse/admin/components/dashboard/configure-menu.gjs b/frontend/discourse/admin/components/dashboard/configure-menu.gjsindex a49edb0c556..e6da1eda4a0 100644--- a/frontend/discourse/admin/components/dashboard/configure-menu.gjs+++ b/frontend/discourse/admin/components/dashboard/configure-menu.gjs@@ -12,6 +12,9 @@ import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `configure-menu-reorderable.gjs`+// replaces it.class ConfigureRow extends Component {@service site;diff --git a/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjs b/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjsindex f243db5f679..2901b9388f3 100644--- a/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjs+++ b/frontend/discourse/admin/components/dashboard/engagement/whos-posting.gjs@@ -7,6 +7,7 @@ import { LinkTo } from "@ember/routing";import { service } from "@ember/service";import { trustHTML } from "@ember/template";import CompareGroups from "discourse/admin/components/modal/compare-groups";+import CompareGroupsReorderable from "discourse/admin/components/modal/compare-groups-reorderable";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import Category from "discourse/models/category";@@ -33,6 +34,7 @@ export default class WhosPosting extends Component {@service currentUser;@service toasts;@service modal;+ @service siteSettings;@tracked selectedCategories = [];@tracked selectedGroups = [];@@ -131,7 +133,13 @@ export default class WhosPosting extends Component {@actionopenCompareGroups() {- this.modal.show(CompareGroups, {+ // TODO (ui-kit-reorderable-list-cleanup) drop the branch and the legacy+ // component once the change ships.+ const Modal = this.siteSettings.enable_new_reordering_controls+ ? CompareGroupsReorderable+ : CompareGroups;++ this.modal.show(Modal, {model: {currentTokens: this.selectedGroups,footerNote: i18n(diff --git a/frontend/discourse/admin/components/dashboard/reports.gjs b/frontend/discourse/admin/components/dashboard/reports.gjsindex 894bb7f6356..611a3181cfa 100644--- a/frontend/discourse/admin/components/dashboard/reports.gjs+++ b/frontend/discourse/admin/components/dashboard/reports.gjs@@ -10,6 +10,7 @@ import DashboardReportEmptyState from "discourse/admin/components/dashboard/repoimport DashboardReportErrorState from "discourse/admin/components/dashboard/report-error-state";import DashboardSection from "discourse/admin/components/dashboard/section";import ManageReports from "discourse/admin/components/modal/manage-reports";+import ManageReportsReorderable from "discourse/admin/components/modal/manage-reports-reorderable";import { lookupAdminDashboardReportRenderer } from "discourse/admin/lib/admin-dashboard-report-renderers";import { loadDashboardReports } from "discourse/admin/lib/dashboard-reports-loader";import PluginOutlet from "discourse/components/plugin-outlet";@@ -125,6 +126,7 @@ class FollowPointer extends Modifier {export default class DashboardReports extends Component {@service currentUser;@service modal;+ @service siteSettings;@tracked cards = [];@tracked loading = false;@@ -253,7 +255,13 @@ export default class DashboardReports extends Component {@actionopenReportsConfig() {- this.modal.show(ManageReports, {+ // TODO (ui-kit-reorderable-list-cleanup) drop the branch and the legacy+ // component once the change ships.+ const Modal = this.siteSettings.enable_new_reordering_controls+ ? ManageReportsReorderable+ : ManageReports;++ this.modal.show(Modal, {model: { onApplied: this.onLayoutChanged },});}diff --git a/frontend/discourse/admin/components/emoji-value-list.gjs b/frontend/discourse/admin/components/emoji-value-list.gjsindex 467faeac1e4..e8d94b41f05 100644--- a/frontend/discourse/admin/components/emoji-value-list.gjs+++ b/frontend/discourse/admin/components/emoji-value-list.gjs@@ -10,10 +10,16 @@ import { addUniqueValueToArray } from "discourse/lib/array-tools";import { emojiUrlFor } from "discourse/lib/text";import { not } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";import { i18n } from "discourse-i18n";export default class EmojiValueList extends Component {@service menu;+ @service siteSettings;++ emojiLabel = (data) => data.value;++ isEditable = (item) => item.isEditable;@cachedget collection() {@@ -30,6 +36,7 @@ export default class EmojiValueList extends Component {});}+ // TODO (ui-kit-reorderable-list-cleanup) delete with the legacy arm below.get showUpDownButtons() {return this.collection.length > 1;}@@ -94,6 +101,18 @@ export default class EmojiValueList extends Component {this.#saveValues(newCollection);}+ /**+ * Applies a committed move and persists the new order. Wrapping and+ * announcements are the list's own.+ *+ * @param {Object} move - The normalized move from the list.+ */+ @action+ handleMove(move) {+ this.#saveValues([...move.proposedToItems]);+ }++ // TODO (ui-kit-reorderable-list-cleanup) delete with the legacy arm below.@actionshift(operation, index) {const updateCollection = [...this.collection];@@ -146,22 +165,27 @@ export default class EmojiValueList extends Component {<template><div class="value-list emoji-list">{{#if this.collection}}- <ul class="values emoji-value-list">- {{#each this.collection key="value" as |data index|}}- <li class="value" data-index={{index}}>- <DButton- class="btn-default remove-value-btn btn-small"- @action={{fn this.removeValue data}}- @disabled={{not data.isEditable}}- @icon="xmark"- />-+ {{! TODO (ui-kit-reorderable-list-cleanup) drop the branch and the+ legacy arm once the change ships. This component keeps one class+ because a plugin patches it by resolver key. }}+ {{#if this.siteSettings.enable_new_reordering_controls}}+ <DReorderableList+ class="values emoji-value-list"+ @items={{this.collection}}+ @key="value"+ @label={{this.emojiLabel}}+ @onMove={{this.handleMove}}+ @onRemove={{this.removeValue}}+ @removable={{this.isEditable}}+ @rowClass="value"+ >+ <:row as |data controls|><divclass="value-input emoji-details{{if data.isEditable 'can-edit'}}{{if data.isEditing 'd-editor-textarea-wrapper'}}"role="button"- {{on "click" (fn this.editValue index)}}+ {{on "click" (fn this.editValue controls.index)}}><imgclass="emoji-list-emoji"@@ -171,22 +195,51 @@ export default class EmojiValueList extends Component {/><span class="emoji-name">{{data.value}}</span></div>-- {{#if this.showUpDownButtons}}- <DButton- class="btn-default shift-up-value-btn btn-small"- @action={{fn this.shift -1 index}}- @icon="arrow-up"- />+ </:row>+ </DReorderableList>+ {{else}}+ <ul class="values emoji-value-list">+ {{#each this.collection key="value" as |data index|}}+ <li class="value" data-index={{index}}><DButton- class="btn-default shift-down-value-btn btn-small"- @action={{fn this.shift 1 index}}- @icon="arrow-down"+ class="btn-default remove-value-btn btn-small"+ @action={{fn this.removeValue data}}+ @disabled={{not data.isEditable}}+ @icon="xmark"/>- {{/if}}- </li>- {{/each}}- </ul>++ <div+ class="value-input emoji-details+ {{if data.isEditable 'can-edit'}}+ {{if data.isEditing 'd-editor-textarea-wrapper'}}"+ role="button"+ {{on "click" (fn this.editValue index)}}+ >+ <img+ class="emoji-list-emoji"+ height="15px"+ src={{data.emojiUrl}}+ width="15px"+ />+ <span class="emoji-name">{{data.value}}</span>+ </div>++ {{#if this.showUpDownButtons}}+ <DButton+ class="btn-default shift-up-value-btn btn-small"+ @action={{fn this.shift -1 index}}+ @icon="arrow-up"+ />+ <DButton+ class="btn-default shift-down-value-btn btn-small"+ @action={{fn this.shift 1 index}}+ @icon="arrow-down"+ />+ {{/if}}+ </li>+ {{/each}}+ </ul>+ {{/if}}{{/if}}<div class="value">diff --git a/frontend/discourse/admin/components/manageable-row-list-item-reorderable.gjs b/frontend/discourse/admin/components/manageable-row-list-item-reorderable.gjsnew file mode 100644index 00000000000..be8a76e55b1--- /dev/null+++ b/frontend/discourse/admin/components/manageable-row-list-item-reorderable.gjs@@ -0,0 +1,48 @@+import { concat, fn } from "@ember/helper";+import { on } from "@ember/modifier";+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";+import { i18n } from "discourse-i18n";++/**+ * One row of a toggleable, ordered admin list: its text and its enable+ * switch.+ *+ * Reordering is not drawn here. The surrounding reorderable list owns the+ * handle, the drag, the move menu and the announcements, so a row only has to+ * describe itself.+ */+// TODO (ui-kit-reorderable-list-cleanup) rename this over+// `manageable-row-list-item.gjs` once the change ships.+const ManageableRowListItem = <template>+ <div class="manageable-row-list__row-content">+ <div class="manageable-row-list__row-text">+ <div class="manageable-row-list__row-heading">+ <span class="manageable-row-list__title">{{@row.title}}</span>+ {{#if @row.label}}+ <span class="db-report__label">+ {{@row.label}}+ </span>+ {{/if}}+ </div>+ {{#if @row.description}}+ <p class="manageable-row-list__description">{{@row.description}}</p>+ {{/if}}+ </div>++ <DToggleSwitch+ aria-label={{i18n+ (if+ @row.enabled+ (concat @ariaLabelPrefix ".disable")+ (concat @ariaLabelPrefix ".enable")+ )+ }}+ disabled={{@toggleDisabled}}+ @state={{@row.enabled}}+ {{on "click" (fn @onToggle @row)}}+ />+ </div>+</template>;++export default ManageableRowListItem;diff --git a/frontend/discourse/admin/components/manageable-row-list-item.gjs b/frontend/discourse/admin/components/manageable-row-list-item.gjsindex f6ff86dc1ae..9f3add174b8 100644--- a/frontend/discourse/admin/components/manageable-row-list-item.gjs+++ b/frontend/discourse/admin/components/manageable-row-list-item.gjs@@ -11,6 +11,8 @@ import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `manageable-row-list-item-reorderable.gjs` replaces it.export default class ManageableRowListItem extends Component {@service site;diff --git a/frontend/discourse/admin/components/modal/compare-groups-reorderable.gjs b/frontend/discourse/admin/components/modal/compare-groups-reorderable.gjsnew file mode 100644index 00000000000..4027124453c--- /dev/null+++ b/frontend/discourse/admin/components/modal/compare-groups-reorderable.gjs@@ -0,0 +1,220 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { hash } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import ManageableRowListItemReorderable from "discourse/admin/components/manageable-row-list-item-reorderable";+import ToggleableOrderedList from "discourse/admin/lib/toggleable-ordered-list";+import { not } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import DFilterInput from "discourse/ui-kit/d-filter-input";+import DModal from "discourse/ui-kit/d-modal";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import { i18n } from "discourse-i18n";++export const VISIBLE_CAP = 10;+export const SYNTHETIC_KEYS = ["new_members", "returning", "staff"];++const EXCLUDED_AUTO_GROUP_IDS = [0, 3, 4, 5];+const ARIA_LABEL_PREFIX =+ "admin.dashboard.sections.engagement.whos_posting.modal";++export function groupToken(groupId) {+ return `group:${groupId}`;+}++/**+ * The reordering surface behind `enable_new_reordering_controls`. Mirrors+ * `modal/compare-groups.gjs`, over the shared reorderable list.+ *+ * TODO (ui-kit-reorderable-list-cleanup) rename this over `modal/compare-groups.gjs`+ * and drop the branch in whos-posting.gjs and report-filters/groups.gjs.+ */+export default class CompareGroups extends Component {+ @service site;++ @tracked search = "";+ @tracked applying = false;+ list = new ToggleableOrderedList({ cap: VISIBLE_CAP, minSelected: 1 });++ rowsByKey = new Map();++ toggleDisabled = (row) => this.list.toggleDisabled(row.key);++ /** Only an enabled row takes part in the order; the rest keep their slots. */+ isMovable = (row) => row.enabled;++ /** Keeps the row's own class and its enabled modifier on the row element. */+ rowClass = (row) =>+ row.enabled+ ? "manageable-row-list__row --enabled"+ : "manageable-row-list__row";++ /** Names a row wherever the list speaks about it: the handle, the menu, the announcement. */+ rowLabel = (row) => row.title;++ constructor() {+ super(...arguments);+ this.buildRows();++ const currentTokens = this.args.model?.currentTokens ?? [];+ this.list.enabledOrder = currentTokens.filter((key) =>+ this.rowsByKey.has(key)+ );+ }++ get enabledRows() {+ return this.list.enabledOrder+ .map((key) => this.rowsByKey.get(key))+ .filter(Boolean);+ }++ get disabledRows() {+ const enabled = this.list.enabledKeys;+ return [...this.rowsByKey.values()].filter((row) => !enabled.has(row.key));+ }++ get filteredDisabledRows() {+ const query = this.search.trim().toLowerCase();+ if (!query) {+ return this.disabledRows;+ }+ return this.disabledRows.filter((row) =>+ (row.title ?? "").toLowerCase().includes(query)+ );+ }++ get visibleRows() {+ return [+ ...this.enabledRows.map((row) => ({ ...row, enabled: true })),+ ...this.filteredDisabledRows.map((row) => ({ ...row, enabled: false })),+ ];+ }++ get lastEnabledIndex() {+ return this.enabledRows.length - 1;+ }++ buildRows() {+ SYNTHETIC_KEYS.forEach((key) => {+ this.rowsByKey.set(key, {+ key,+ title: i18n(`admin.dashboard.sections.engagement.whos_posting.${key}`),+ description: i18n(+ `admin.dashboard.sections.engagement.whos_posting.modal.descriptions.${key}`+ ),+ });+ });++ (this.site.groups ?? [])+ .filter((group) => !EXCLUDED_AUTO_GROUP_IDS.includes(group.id))+ .forEach((group) => {+ const key = groupToken(group.id);+ this.rowsByKey.set(key, { key, title: group.full_name || group.name });+ });+ }++ @action+ updateSearch(event) {+ this.search = event.target.value;+ }++ @action+ toggle(row) {+ this.list.toggle(row.key);+ }++ @action+ handleMove({ proposedToItems }) {+ this.list.reorderVisible(+ proposedToItems.filter((row) => row.enabled).map((row) => row.key)+ );+ }++ @action+ apply() {+ this.applying = true;+ this.args.model?.onApply?.(this.list.enabledOrder);+ this.args.closeModal?.();+ }++ <template>+ <DModal+ class="compare-groups has-search manageable-row-list"+ @closeModal={{@closeModal}}+ @inline={{@inline}}+ @title={{i18n+ "admin.dashboard.sections.engagement.whos_posting.modal.title"+ }}+ >++ <:belowModalTitle>+ <span class="manageable-row-list__counter">+ {{i18n+ "admin.dashboard.sections.engagement.whos_posting.modal.counter"+ count=this.list.enabledOrder.length+ max=VISIBLE_CAP+ }}+ </span>+ </:belowModalTitle>++ <:belowHeader>+ <div class="manageable-row-list__search-wrapper">+ <DFilterInput+ placeholder={{i18n+ "admin.dashboard.sections.engagement.whos_posting.modal.search_placeholder"+ }}+ @filterAction={{this.updateSearch}}+ @icons={{hash left="magnifying-glass"}}+ @value={{this.search}}+ />+ </div>+ </:belowHeader>++ <:body>+ <DReorderableList+ class="manageable-row-list__list"+ @disabled={{not this.list.reorderable}}+ @items={{this.visibleRows}}+ @key="key"+ @label={{this.rowLabel}}+ @listLabel={{i18n+ "admin.dashboard.sections.engagement.whos_posting.modal.title"+ }}+ @movable={{this.isMovable}}+ @onMove={{this.handleMove}}+ @rowClass={{this.rowClass}}+ >+ <:row as |row|>+ <ManageableRowListItemReorderable+ @ariaLabelPrefix={{ARIA_LABEL_PREFIX}}+ @onToggle={{this.toggle}}+ @row={{row}}+ @toggleDisabled={{this.toggleDisabled row}}+ />+ </:row>+ </DReorderableList>+ </:body>++ <:footer>+ {{#if @model.footerNote}}+ <p class="manageable-row-list__footer-note">{{@model.footerNote}}</p>+ {{/if}}+ <div class="compare-groups__footer-actions">+ <DButton+ class="btn-transparent compare-groups__cancel"+ @action={{@closeModal}}+ @label="js.cancel_value"+ />+ <DButton+ class="btn-primary compare-groups__apply"+ @action={{this.apply}}+ @disabled={{this.applying}}+ @isLoading={{this.applying}}+ @label="admin.dashboard.sections.engagement.whos_posting.modal.apply"+ />+ </div>+ </:footer>+ </DModal>+ </template>+}diff --git a/frontend/discourse/admin/components/modal/compare-groups.gjs b/frontend/discourse/admin/components/modal/compare-groups.gjsindex 2d50f72fb60..c94d5a722ea 100644--- a/frontend/discourse/admin/components/modal/compare-groups.gjs+++ b/frontend/discourse/admin/components/modal/compare-groups.gjs@@ -22,6 +22,8 @@ export function groupToken(groupId) {return `group:${groupId}`;}+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `compare-groups-reorderable.gjs` replaces it.export default class CompareGroups extends Component {@service site;diff --git a/frontend/discourse/admin/components/modal/edit-badge-groupings-reorderable.gjs b/frontend/discourse/admin/components/modal/edit-badge-groupings-reorderable.gjsnew file mode 100644index 00000000000..e859bd413dc--- /dev/null+++ b/frontend/discourse/admin/components/modal/edit-badge-groupings-reorderable.gjs@@ -0,0 +1,156 @@+import Component from "@glimmer/component";+import { Input } from "@ember/component";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { removeValueFromArray } from "discourse/lib/array-tools";+import { autoTrackedArray } from "discourse/lib/tracked-tools";+import DButton from "discourse/ui-kit/d-button";+import DModal from "discourse/ui-kit/d-modal";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import { i18n } from "discourse-i18n";++/**+ * The reordering surface behind `enable_new_reordering_controls`. Mirrors+ * `modal/edit-badge-groupings.gjs`, over the shared reorderable list.+ *+ * TODO (ui-kit-reorderable-list-cleanup) rename this over `modal/edit-badge-groupings.gjs`+ * and drop the branch in admin-badges.gjs.+ */+export default class EditBadgeGroupings extends Component {+ @service dialog;+ @service store;++ @autoTrackedArray workingCopy = this.args.model.badgeGroupings.map((o) =>+ this.store.createRecord("badge-grouping", o)+ );++ groupingLabel = (grouping) => grouping.displayName || grouping.name;+ canDelete = (grouping) => !grouping.system;++ /**+ * Applies a committed move onto the staged working copy.+ *+ * @param {Object} move - The normalized move from the list.+ */+ @action+ handleMove(move) {+ this.workingCopy.splice(+ 0,+ this.workingCopy.length,+ ...move.proposedToItems+ );+ }++ @action+ delete(item) {+ removeValueFromArray(this.workingCopy, item);+ }++ @action+ add() {+ const obj = this.store.createRecord("badge-grouping", {+ editing: true,+ name: i18n("admin.badges.badge_grouping"),+ });+ this.workingCopy.push(obj);+ }++ @action+ async saveAll() {+ const groupIds = this.workingCopy.map((i) => i.id || -1);+ const names = this.workingCopy.map((i) => i.name);+ try {+ const data = await ajax("/admin/badges/badge_groupings", {+ data: { ids: groupIds, names },+ type: "POST",+ });+ this.workingCopy.length = 0;+ data.badge_groupings.forEach((badgeGroup) => {+ this.workingCopy.push(+ this.store.createRecord("badge-grouping", {+ ...badgeGroup,+ editing: false,+ })+ );+ });+ this.args.model.updateGroupings(this.workingCopy);+ this.args.closeModal();+ } catch {+ this.dialog.alert(i18n("generic_error"));+ }+ }++ <template>+ <DModal+ @bodyClass="badge-groupings-modal"+ @closeModal={{@closeModal}}+ @title={{i18n "admin.badges.badge_groupings.modal_title"}}+ >+ <:body>+ <div class="badge-groupings">+ <DReorderableList+ class="badge-groupings-list"+ @controls="manual"+ @items={{this.workingCopy}}+ @label={{this.groupingLabel}}+ @onMove={{this.handleMove}}+ @onRemove={{this.delete}}+ @removable={{this.canDelete}}+ @rowClass="badge-grouping-item"+ >+ <:row as |wc controls|>+ <controls.handle />+ <div class="badge-grouping">+ {{#if wc.editing}}+ <Input class="badge-grouping-name-input" @value={{wc.name}} />+ {{else}}+ <span>{{wc.displayName}}</span>+ {{/if}}+ </div>+ <div class="actions">+ {{#if wc.editing}}+ <DButton+ class="btn-flat"+ @action={{fn (mut wc.editing) false}}+ @icon="check"+ />+ {{else}}+ {{#unless wc.system}}+ <DButton+ class="btn-flat"+ @action={{fn (mut wc.editing) true}}+ @icon="pencil"+ />+ {{/unless}}+ {{/if}}+ {{#if controls.remove}}+ <controls.remove />+ {{/if}}+ </div>+ </:row>+ </DReorderableList>+ </div>+ <DButton+ class="btn-default badge-groupings__add-grouping"+ @action={{this.add}}+ @label="admin.badges.new"+ />+ </:body>+ <:footer>+ <DButton+ class="btn-primary badge-groupings__save"+ @action={{this.saveAll}}+ @disabled={{this.submitDisabled}}+ @label="admin.badges.save"+ />+ <DButton+ class="btn-flat d-modal-cancel"+ @action={{@closeModal}}+ @label="cancel"+ />+ </:footer>+ </DModal>+ </template>+}diff --git a/frontend/discourse/admin/components/modal/edit-badge-groupings.gjs b/frontend/discourse/admin/components/modal/edit-badge-groupings.gjsindex 409f6d559f3..8fc1bfb275e 100644--- a/frontend/discourse/admin/components/modal/edit-badge-groupings.gjs+++ b/frontend/discourse/admin/components/modal/edit-badge-groupings.gjs@@ -10,6 +10,8 @@ import DButton from "discourse/ui-kit/d-button";import DModal from "discourse/ui-kit/d-modal";import { i18n } from "discourse-i18n";+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `edit-badge-groupings-reorderable.gjs` replaces it.export default class EditBadgeGroupings extends Component {@service dialog;@service store;diff --git a/frontend/discourse/admin/components/modal/manage-reports-reorderable.gjs b/frontend/discourse/admin/components/modal/manage-reports-reorderable.gjsnew file mode 100644index 00000000000..300dcdd371a--- /dev/null+++ b/frontend/discourse/admin/components/modal/manage-reports-reorderable.gjs@@ -0,0 +1,313 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { hash } from "@ember/helper";+import { action } from "@ember/object";+import ManageableRowListItemReorderable from "discourse/admin/components/manageable-row-list-item-reorderable";+import ToggleableOrderedList from "discourse/admin/lib/toggleable-ordered-list";+import PluginOutlet from "discourse/components/plugin-outlet";+import lazyHash from "discourse/helpers/lazy-hash";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import discourseDebounce from "discourse/lib/debounce";+import { not } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import DFilterInput from "discourse/ui-kit/d-filter-input";+import DLoadMore from "discourse/ui-kit/d-load-more";+import DModal from "discourse/ui-kit/d-modal";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import { i18n } from "discourse-i18n";++const VISIBLE_CAP = 10;+const SEARCH_DEBOUNCE_MS = 200;+const ARIA_LABEL_PREFIX = "admin.dashboard.reports_section.modal";++/**+ * The reordering surface behind `enable_new_reordering_controls`. Mirrors+ * `modal/manage-reports.gjs`, over the shared reorderable list.+ *+ * TODO (ui-kit-reorderable-list-cleanup) rename this over `modal/manage-reports.gjs`+ * and drop the branch in dashboard/reports.gjs.+ */+export default class ManageReports extends Component {+ @tracked allKeys = [];+ @tracked providers = [];+ @tracked search = "";+ @tracked nextCursor = null;+ @tracked hasMore = false;+ @tracked loading = true;+ @tracked loadingMore = false;+ @tracked applying = false;+ list = new ToggleableOrderedList({ cap: VISIBLE_CAP });++ itemsByKey = new Map();++ toggleDisabled = (row) => this.list.toggleDisabled(row.key);++ /** Only an enabled row takes part in the order; the rest keep their slots. */+ isMovable = (row) => row.enabled;++ /** Keeps the row's own class and its enabled modifier on the row element. */+ rowClass = (row) =>+ row.enabled+ ? "manageable-row-list__row --enabled"+ : "manageable-row-list__row";++ /** Names a row wherever the list speaks about it: the handle, the menu, the announcement. */+ rowLabel = (row) => row.title;++ constructor() {+ super(...arguments);+ this.load();+ }++ get enabledRows() {+ return this.list.enabledOrder+ .map((key) => this.itemsByKey.get(key))+ .filter(Boolean);+ }++ get allRows() {+ return this.allKeys.map((key) => this.itemsByKey.get(key)).filter(Boolean);+ }++ get disabledRows() {+ const enabled = this.list.enabledKeys;+ return this.allRows.filter((row) => !enabled.has(row.key));+ }++ get filteredEnabledRows() {+ const query = this.search.trim().toLowerCase();+ if (!query) {+ return this.enabledRows;+ }+ return this.enabledRows.filter(+ (row) =>+ (row.title ?? "").toLowerCase().includes(query) ||+ (row.description ?? "").toLowerCase().includes(query)+ );+ }++ get visibleRows() {+ return [+ ...this.filteredEnabledRows.map((row) => ({ ...row, enabled: true })),+ ...this.disabledRows.map((row) => ({ ...row, enabled: false })),+ ];+ }++ get lastEnabledIndex() {+ return this.filteredEnabledRows.length - 1;+ }++ cacheItems(items) {+ for (const item of items) {+ this.itemsByKey.set(item.key, item);+ }+ }++ @action+ async load() {+ this.loading = true;+ try {+ const response = await this.fetchAll(null);+ const enabled = response.enabled ?? [];+ const page = response.available ?? [];++ this.providers = response.providers ?? [];+ this.cacheItems(enabled);+ this.cacheItems(page);+ this.list.enabledOrder = enabled.map((item) => item.key);+ this.allKeys = page.map((item) => item.key);+ this.nextCursor = response.cursor ?? null;+ this.hasMore = !!response.has_more;+ } catch (e) {+ popupAjaxError(e);+ } finally {+ this.loading = false;+ }+ }++ @action+ async loadMore() {+ if (this.loadingMore || !this.hasMore || !this.nextCursor) {+ return;+ }+ this.loadingMore = true;+ try {+ const response = await this.fetchAll(this.nextCursor);+ const page = response.available ?? [];+ this.cacheItems(page);+ this.allKeys = [...this.allKeys, ...page.map((item) => item.key)];+ this.nextCursor = response.cursor ?? null;+ this.hasMore = !!response.has_more;+ } catch (e) {+ popupAjaxError(e);+ } finally {+ this.loadingMore = false;+ }+ }++ async fetchAll(cursor) {+ const data = {};+ if (cursor) {+ data.cursor = cursor;+ }+ if (this.search.trim()) {+ data.search = this.search.trim();+ }+ return await ajax("/admin/dashboard/reports/available.json", { data });+ }++ @action+ updateSearch(event) {+ this.search = event.target.value;+ discourseDebounce(this, this.refetchForSearch, SEARCH_DEBOUNCE_MS);+ }++ @action+ async refetchForSearch() {+ try {+ const response = await this.fetchAll(null);+ const enabled = response.enabled ?? [];+ const page = response.available ?? [];+ this.cacheItems(enabled);+ this.cacheItems(page);+ this.allKeys = page.map((item) => item.key);+ this.nextCursor = response.cursor ?? null;+ this.hasMore = !!response.has_more;+ } catch (e) {+ popupAjaxError(e);+ }+ }++ @action+ toggle(row) {+ this.itemsByKey.set(row.key, row);+ this.list.toggle(row.key);+ }++ @action+ handleMove({ proposedToItems }) {+ this.list.reorderVisible(+ proposedToItems.filter((row) => row.enabled).map((row) => row.key)+ );+ }++ @action+ async apply() {+ this.applying = true;+ try {+ await ajax("/admin/dashboard/reports/layout", {+ type: "PUT",+ contentType: "application/json",+ data: JSON.stringify({+ items: this.enabledRows.map(({ source, identifier }) => ({+ source,+ identifier,+ })),+ }),+ });+ this.args.closeModal?.();+ this.args.model?.onApplied?.();+ } catch (e) {+ popupAjaxError(e);+ } finally {+ this.applying = false;+ }+ }++ <template>+ <DModal+ class="manage-reports has-search manageable-row-list"+ @closeModal={{@closeModal}}+ @title={{i18n "admin.dashboard.reports_section.modal.title"}}+ >++ <:belowModalTitle>+ <span class="manageable-row-list__counter">+ {{i18n+ "admin.dashboard.reports_section.modal.counter"+ count=this.list.enabledOrder.length+ max=VISIBLE_CAP+ }}+ </span>+ </:belowModalTitle>++ <:belowHeader>+ <div class="manageable-row-list__search-wrapper">+ <DFilterInput+ placeholder={{i18n+ "admin.dashboard.reports_section.modal.search_placeholder"+ }}+ @filterAction={{this.updateSearch}}+ @icons={{hash left="magnifying-glass"}}+ @value={{this.search}}+ />+ </div>+ </:belowHeader>++ <:body>++ {{#if this.visibleRows.length}}+ <DReorderableList+ class="manageable-row-list__list"+ @disabled={{not this.list.reorderable}}+ @items={{this.visibleRows}}+ @key="key"+ @label={{this.rowLabel}}+ @listLabel={{i18n "admin.dashboard.reports_section.modal.title"}}+ @movable={{this.isMovable}}+ @onMove={{this.handleMove}}+ @rowClass={{this.rowClass}}+ >+ <:row as |row|>+ <ManageableRowListItemReorderable+ @ariaLabelPrefix={{ARIA_LABEL_PREFIX}}+ @onToggle={{this.toggle}}+ @row={{row}}+ @toggleDisabled={{this.toggleDisabled row}}+ />+ </:row>+ </DReorderableList>+ <DLoadMore+ @action={{this.loadMore}}+ @enabled={{this.hasMore}}+ @isLoading={{this.loading}}+ />+ {{/if}}++ </:body>++ <:aboveFooter>+ <PluginOutlet+ @name="admin-dashboard-manage-reports-footer"+ @outletArgs={{lazyHash+ providers=this.providers+ enabled=this.enabledRows+ }}+ />+ </:aboveFooter>++ <:footer>+ <p class="manageable-row-list__footer-note">+ {{i18n "admin.dashboard.reports_section.modal.footer_note"}}+ </p>+ <div class="manage-reports__footer-actions">++ <DButton+ class="btn-transparent manage-reports__cancel"+ @action={{@closeModal}}+ @label="js.cancel_value"+ />+ <DButton+ class="btn-primary manage-reports__apply"+ @action={{this.apply}}+ @disabled={{this.applying}}+ @isLoading={{this.applying}}+ @label="admin.dashboard.reports_section.modal.apply"+ />+ </div>++ </:footer>+ </DModal>+ </template>+}diff --git a/frontend/discourse/admin/components/modal/manage-reports.gjs b/frontend/discourse/admin/components/modal/manage-reports.gjsindex 4aa855f865c..9a53037bd02 100644--- a/frontend/discourse/admin/components/modal/manage-reports.gjs+++ b/frontend/discourse/admin/components/modal/manage-reports.gjs@@ -20,6 +20,8 @@ const VISIBLE_CAP = 10;const SEARCH_DEBOUNCE_MS = 200;const ARIA_LABEL_PREFIX = "admin.dashboard.reports_section.modal";+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `manage-reports-reorderable.gjs` replaces it.export default class ManageReports extends Component {@tracked allKeys = [];@tracked providers = [];diff --git a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjsindex ef51205e105..ae02ee7b57e 100644--- a/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs+++ b/frontend/discourse/admin/components/redesigned-admin-dashboard.gjs@@ -2,6 +2,7 @@ import Component from "@glimmer/component";import { concat } from "@ember/helper";import { service } from "@ember/service";import ConfigureMenu from "discourse/admin/components/dashboard/configure-menu";+import ConfigureMenuReorderable from "discourse/admin/components/dashboard/configure-menu-reorderable";import DashboardDateRange from "discourse/admin/components/dashboard/date-range";import DashboardEngagement from "discourse/admin/components/dashboard/engagement";import DashboardHighlights from "discourse/admin/components/dashboard/highlights";@@ -24,6 +25,7 @@ const sectionComponentFor = (id) => lookupAdminDashboardSection(id);export default class RedesignedAdminDashboard extends Component {@service currentUser;+ @service siteSettings;get configurationSections() {return this.args.loadedSections?.configuration?.sections ?? [];@@ -61,11 +63,21 @@ export default class RedesignedAdminDashboard extends Component {@triggerClass="btn-default"><:content>- <ConfigureMenu- @onReorder={{@reorderSections}}- @onToggleVisibility={{@toggleSection}}- @sections={{this.configurationSections}}- />+ {{! TODO (ui-kit-reorderable-list-cleanup) drop the branch and the+ legacy component once the change ships. }}+ {{#if this.siteSettings.enable_new_reordering_controls}}+ <ConfigureMenuReorderable+ @onReorder={{@reorderSections}}+ @onToggleVisibility={{@toggleSection}}+ @sections={{this.configurationSections}}+ />+ {{else}}+ <ConfigureMenu+ @onReorder={{@reorderSections}}+ @onToggleVisibility={{@toggleSection}}+ @sections={{this.configurationSections}}+ />+ {{/if}}</:content></DMenu>{{/if}}diff --git a/frontend/discourse/admin/components/report-filters/groups.gjs b/frontend/discourse/admin/components/report-filters/groups.gjsindex 5ad10adebb5..e8a2999d1be 100644--- a/frontend/discourse/admin/components/report-filters/groups.gjs+++ b/frontend/discourse/admin/components/report-filters/groups.gjs@@ -1,15 +1,23 @@import { action } from "@ember/object";import { service } from "@ember/service";import CompareGroups from "discourse/admin/components/modal/compare-groups";+import CompareGroupsReorderable from "discourse/admin/components/modal/compare-groups-reorderable";import FilterComponent from "discourse/admin/components/report-filters/filter";import DButton from "discourse/ui-kit/d-button";export default class Groups extends FilterComponent {@service modal;+ @service siteSettings;@actionopenCompareGroups() {- this.modal.show(CompareGroups, {+ // TODO (ui-kit-reorderable-list-cleanup) drop the branch and the legacy+ // component once the change ships.+ const Modal = this.siteSettings.enable_new_reordering_controls+ ? CompareGroupsReorderable+ : CompareGroups;++ this.modal.show(Modal, {model: {currentTokens: this.filter?.default ?? [],onApply: (tokens) => this.applyFilter(this.filter.id, tokens.join(",")),diff --git a/frontend/discourse/admin/components/simple-list.gjs b/frontend/discourse/admin/components/simple-list.gjsindex d6c3bb41bf5..e25579fdd58 100644--- a/frontend/discourse/admin/components/simple-list.gjs+++ b/frontend/discourse/admin/components/simple-list.gjs@@ -4,16 +4,32 @@ import { fn, hash } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";import { trackedArray } from "@ember/reactive/collections";+import { service } from "@ember/service";import withEventValue from "discourse/helpers/with-event-value";import ComboBox from "discourse/select-kit/components/combo-box";import { gt, not } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";import { i18n } from "discourse-i18n";+const INDEX_KEY = "@index";+// args: onChange, inputDelimiter, values, allowAny, choices+/**+ * Renders its rows through the shared reorderable list when+ * `enable_new_reordering_controls` is on, and through the legacy rows+ * otherwise. The branch lives here so every caller follows the change.+ *+ * TODO (ui-kit-reorderable-list-cleanup) delete the legacy arm and the+ * members marked for it once the change ships.+ */export default class SimpleList extends Component {+ @service siteSettings;+@tracked newValue = "";+ valueLabel = (value) => value;+@cachedget collection() {return trackedArray(@@ -55,12 +71,32 @@ export default class SimpleList extends Component {this.args.onChange?.(this.collection);}+ // TODO (ui-kit-reorderable-list-cleanup) delete with the legacy arm below.@actionremoveItem(index) {this.collection.splice(index, 1);this.args.onChange?.(this.collection);}+ @action+ removeValue(value, index) {+ this.collection.splice(index, 1);+ this.args.onChange?.(this.collection);+ }++ /**+ * Applies a committed move onto the delimited collection and reports the+ * new order. Wrapping and announcements are the list's own.+ *+ * @param {Object} move - The normalized move from the list.+ */+ @action+ handleMove(move) {+ this.collection.splice(0, this.collection.length, ...move.proposedToItems);+ this.args.onChange?.(this.collection);+ }++ // TODO (ui-kit-reorderable-list-cleanup) delete with the legacy arm below.@actionshift(index, offset) {let futureIndex = index + offset;@@ -80,39 +116,72 @@ export default class SimpleList extends Component {<template><div class="simple-list value-list" ...attributes>- {{#if this.collection}}- <div class="values">- {{#each this.collection as |value index|}}- <div class="value" data-index={{index}}>- <DButton- class="btn-default remove-value-btn btn-small"- @action={{fn this.removeItem index}}- @icon="xmark"- />-+ {{#if this.siteSettings.enable_new_reordering_controls}}+ <DReorderableList+ class="values"+ @items={{this.collection}}+ @itemTag="div"+ @key={{INDEX_KEY}}+ @label={{this.valueLabel}}+ @onMove={{this.handleMove}}+ @onRemove={{this.removeValue}}+ @rowClass="value"+ @tag="div"+ >+ <:row as |value controls|>+ {{#if this.isPredefinedList}}+ {{! A closed set has nothing to type: the value came from the+ choices and can only be reordered or removed. }}+ <span+ class="value-input --readonly"+ title={{value}}+ >{{value}}</span>+ {{else}}<inputclass="value-input"title={{value}}type="text"value={{value}}- {{on "focusout" (fn this.changeValue index)}}+ {{on "focusout" (fn this.changeValue controls.index)}}/>-- {{#if (gt this.collection.length 1)}}+ {{/if}}+ </:row>+ </DReorderableList>+ {{else}}+ {{#if this.collection}}+ <div class="values">+ {{#each this.collection as |value index|}}+ <div class="value" data-index={{index}}><DButton- class="btn-default shift-up-value-btn btn-small"- @action={{fn this.shift index -1}}- @icon="arrow-up"+ class="btn-default remove-value-btn btn-small"+ @action={{fn this.removeItem index}}+ @icon="xmark"/>- <DButton- class="btn-default shift-down-value-btn btn-small"- @action={{fn this.shift index 1}}- @icon="arrow-down"++ <input+ class="value-input"+ title={{value}}+ type="text"+ value={{value}}+ {{on "focusout" (fn this.changeValue index)}}/>- {{/if}}- </div>- {{/each}}- </div>++ {{#if (gt this.collection.length 1)}}+ <DButton+ class="btn-default shift-up-value-btn btn-small"+ @action={{fn this.shift index -1}}+ @icon="arrow-up"+ />+ <DButton+ class="btn-default shift-down-value-btn btn-small"+ @action={{fn this.shift index 1}}+ @icon="arrow-down"+ />+ {{/if}}+ </div>+ {{/each}}+ </div>+ {{/if}}{{/if}}<div class="simple-list-input">@@ -123,7 +192,18 @@ export default class SimpleList extends Component {@content={{this.validValues}}@nameProperty={{@setting.computedNameProperty}}@onChange={{this.addValue}}- @options={{hash castInteger=true allowAny=false}}+ {{! Without an empty-selection label the closed-set picker renders+ as an empty box under the reorderable list. The free-text branch+ below shows the same string as its placeholder. }}+ @options={{if+ this.siteSettings.enable_new_reordering_controls+ (hash+ castInteger=true+ allowAny=false+ none="admin.site_settings.simple_list.add_item"+ )+ (hash castInteger=true allowAny=false)+ }}@value={{this.newValue}}@valueProperty={{@setting.computedValueProperty}}/>diff --git a/frontend/discourse/admin/components/value-list.gjs b/frontend/discourse/admin/components/value-list.gjsindex 7fe39c31ce2..53873c12042 100644--- a/frontend/discourse/admin/components/value-list.gjs+++ b/frontend/discourse/admin/components/value-list.gjs@@ -4,6 +4,7 @@ import Component, { Input } from "@ember/component";import { fn, hash } from "@ember/helper";import { on } from "@ember/modifier";import { action, computed } from "@ember/object";+import { service } from "@ember/service";import { isEmpty } from "@ember/utils";import { classNames } from "@ember-decorators/component";import {@@ -15,9 +16,22 @@ import { makeArray } from "discourse/lib/helpers";import { autoTrackedArray } from "discourse/lib/tracked-tools";import ComboBox from "discourse/select-kit/components/combo-box";import DButton from "discourse/ui-kit/d-button";-+import DReorderableList from "discourse/ui-kit/d-reorderable-list";++const INDEX_KEY = "@index";++/**+ * Renders its rows through the shared reorderable list when+ * `enable_new_reordering_controls` is on, and through the legacy rows+ * otherwise. The branch lives here so every caller follows the change.+ *+ * TODO (ui-kit-reorderable-list-cleanup) delete the legacy arm and the+ * members marked for it once the change ships.+ */@classNames("value-list")export default class ValueList extends Component {+ @service siteSettings;+@autoTrackedArray collection = null;inputDelimiter = null;@@ -26,6 +40,8 @@ export default class ValueList extends Component {values = null;onChange = null;+ valueLabel = (value) => value;+@tracked _noneKeyOverride;@computed("addKey")@@ -50,6 +66,7 @@ export default class ValueList extends Component {return makeArray(this.choices).filter((i) => !this.collection?.includes(i));}+ // TODO (ui-kit-reorderable-list-cleanup) delete with the legacy arm below.@computed("collection")get showUpDownButtons() {return this.collection.length - 1 ? true : false;@@ -100,6 +117,19 @@ export default class ValueList extends Component {this._addValue(choice);}+ /**+ * Applies a committed move onto the collection and persists the new order.+ * Wrapping and announcements are the list's own.+ *+ * @param {Object} move - The normalized move from the list.+ */+ @action+ handleMove(move) {+ this.collection.splice(0, this.collection.length, ...move.proposedToItems);+ this._saveValues();+ }++ // TODO (ui-kit-reorderable-list-cleanup) delete with the legacy arm below.@actionshift(operation, index) {let futureIndex = index + operation;@@ -173,37 +203,60 @@ export default class ValueList extends Component {<template>{{#if this.collection}}- <div class="values">- {{#each this.collection as |value index|}}- <div class="value" data-index={{index}}>- <DButton- class="btn-default remove-value-btn btn-small"- @action={{fn this.removeValue value}}- @icon="xmark"- />-+ {{#if this.siteSettings.enable_new_reordering_controls}}+ <DReorderableList+ class="values"+ @items={{this.collection}}+ @itemTag="div"+ @key={{INDEX_KEY}}+ @label={{this.valueLabel}}+ @onMove={{this.handleMove}}+ @onRemove={{this.removeValue}}+ @rowClass="value"+ @tag="div"+ >+ <:row as |value controls|><Inputclass="value-input"title={{value}}@value={{value}}- {{on "focusout" (fn this.changeValue index)}}+ {{on "focusout" (fn this.changeValue controls.index)}}/>-- {{#if this.showUpDownButtons}}+ </:row>+ </DReorderableList>+ {{else}}+ <div class="values">+ {{#each this.collection as |value index|}}+ <div class="value" data-index={{index}}><DButton- class="btn-default shift-up-value-btn btn-small"- @action={{fn this.shift -1 index}}- @icon="arrow-up"+ class="btn-default remove-value-btn btn-small"+ @action={{fn this.removeValue value}}+ @icon="xmark"/>- <DButton- class="btn-default shift-down-value-btn btn-small"- @action={{fn this.shift 1 index}}- @icon="arrow-down"++ <Input+ class="value-input"+ title={{value}}+ @value={{value}}+ {{on "focusout" (fn this.changeValue index)}}/>- {{/if}}- </div>- {{/each}}- </div>++ {{#if this.showUpDownButtons}}+ <DButton+ class="btn-default shift-up-value-btn btn-small"+ @action={{fn this.shift -1 index}}+ @icon="arrow-up"+ />+ <DButton+ class="btn-default shift-down-value-btn btn-small"+ @action={{fn this.shift 1 index}}+ @icon="arrow-down"+ />+ {{/if}}+ </div>+ {{/each}}+ </div>+ {{/if}}{{/if}}<ComboBoxdiff --git a/frontend/discourse/admin/lib/toggleable-ordered-list.js b/frontend/discourse/admin/lib/toggleable-ordered-list.jsindex 74af20a9de0..bb45fdcc04c 100644--- a/frontend/discourse/admin/lib/toggleable-ordered-list.js+++ b/frontend/discourse/admin/lib/toggleable-ordered-list.js@@ -44,6 +44,9 @@ export default class ToggleableOrderedList {}}+ // TODO (ui-kit-reorderable-list-cleanup) the members from here to+ // `onDragEnd` serve the pre-DReorderableList consumers only. Delete them+ // with the legacy arms; `reorderVisible` is the replacement.moveUp(key) {const index = this.enabledOrder.indexOf(key);if (index <= 0) {@@ -97,4 +100,23 @@ export default class ToggleableOrderedList {onDragEnd() {this.draggedId = null;}++ /**+ * Adopts a new order for the enabled keys that are currently on screen.+ *+ * A search filter can hide an enabled row, and a hidden row still holds its+ * place in the saved order. So the visible keys are written back into the+ * slots they already occupy and every hidden key keeps its index, rather than+ * the caller's on-screen sequence replacing the whole order and dropping+ * whatever it could not see.+ *+ * @param {string[]} visibleKeys - Enabled keys in their new on-screen order.+ */+ reorderVisible(visibleKeys) {+ const moving = new Set(visibleKeys);+ let next = 0;+ this.enabledOrder = this.enabledOrder.map((key) =>+ moving.has(key) ? visibleKeys[next++] : key+ );+ }}diff --git a/frontend/discourse/admin/templates/admin-config/flags/index.gjs b/frontend/discourse/admin/templates/admin-config/flags/index.gjsindex 3e96eb64625..84b5ad61bbb 100644--- a/frontend/discourse/admin/templates/admin-config/flags/index.gjs+++ b/frontend/discourse/admin/templates/admin-config/flags/index.gjs@@ -1,3 +1,20 @@+import Component from "@glimmer/component";+import { service } from "@ember/service";import Flags from "discourse/admin/components/admin-config-areas/flags";+import FlagsReorderable from "discourse/admin/components/admin-config-areas/flags-reorderable";-export default <template><Flags /></template>+// TODO (ui-kit-reorderable-list-cleanup) delete this switch and render+// `Flags` directly once `enable_new_reordering_controls` ships.+class FlagsSwitch extends Component {+ @service siteSettings;++ <template>+ {{#if this.siteSettings.enable_new_reordering_controls}}+ <FlagsReorderable />+ {{else}}+ <Flags />+ {{/if}}+ </template>+}++export default <template><FlagsSwitch /></template>diff --git a/frontend/discourse/admin/templates/admin-user-fields/index.gjs b/frontend/discourse/admin/templates/admin-user-fields/index.gjsindex a799b9fe867..cfcab97ecc9 100644--- a/frontend/discourse/admin/templates/admin-user-fields/index.gjs+++ b/frontend/discourse/admin/templates/admin-user-fields/index.gjs@@ -1,5 +1,22 @@+import Component from "@glimmer/component";+import { service } from "@ember/service";import UserFieldsList from "discourse/admin/components/admin-config-areas/user-fields-list";+import UserFieldsListReorderable from "discourse/admin/components/admin-config-areas/user-fields-list-reorderable";++// TODO (ui-kit-reorderable-list-cleanup) delete this switch and render+// `UserFieldsList` directly once `enable_new_reordering_controls` ships.+class UserFieldsSwitch extends Component {+ @service siteSettings;++ <template>+ {{#if this.siteSettings.enable_new_reordering_controls}}+ <UserFieldsListReorderable @userFields={{@userFields}} />+ {{else}}+ <UserFieldsList @userFields={{@userFields}} />+ {{/if}}+ </template>+}export default <template>- <UserFieldsList @userFields={{@controller.model}} />+ <UserFieldsSwitch @userFields={{@controller.model}} /></template>diff --git a/frontend/discourse/app/components/modal/edit-user-directory-columns-reorderable.gjs b/frontend/discourse/app/components/modal/edit-user-directory-columns-reorderable.gjsnew file mode 100644index 00000000000..dfd4987b5cc--- /dev/null+++ b/frontend/discourse/app/components/modal/edit-user-directory-columns-reorderable.gjs@@ -0,0 +1,185 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { Input } from "@ember/component";+import { action } from "@ember/object";+import directoryColumnIsAutomatic from "discourse/helpers/directory-column-is-automatic";+import directoryColumnIsUserField from "discourse/helpers/directory-column-is-user-field";+import directoryTableHeaderTitle from "discourse/helpers/directory-table-header-title";+import { reload } from "discourse/helpers/page-reloader";+import { ajax } from "discourse/lib/ajax";+import { extractError, popupAjaxError } from "discourse/lib/ajax-error";+import DButton from "discourse/ui-kit/d-button";+import DModal from "discourse/ui-kit/d-modal";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";+import { i18n } from "discourse-i18n";++/**+ * The reordering surface behind `enable_new_reordering_controls`. Mirrors+ * `modal/edit-user-directory-columns.gjs`, over the shared reorderable list.+ *+ * TODO (ui-kit-reorderable-list-cleanup) rename this over `modal/edit-user-directory-columns.gjs`+ * and drop the branch in app/controllers/users.js.+ */+export default class EditUserDirectoryColumns extends Component {+ @tracked loading = true;+ @tracked columns;+ @tracked flash;++ /**+ * A plain-text name for a column, for the reorder controls and+ * announcements — the rendered header title can carry icon markup, which an+ * accessible name cannot.+ *+ * @param {Object} column - The column to name.+ * @returns {string} The translated column name.+ */+ columnLabel = (column) => {+ if (column.type === "automatic") {+ return i18n(`directory.${column.name}_long`, {+ defaultValue: i18n(`directory.${column.name}`),+ });+ }+ if (column.user_field) {+ return column.user_field.name;+ }+ return i18n(column.name);+ };++ constructor() {+ super(...arguments);+ this.setupColumns();+ }++ @action+ async setupColumns() {+ try {+ const response = await ajax("edit-directory-columns.json");+ this.loading = false;+ this.columns = response.directory_columns+ .sort((a, b) => (a.position > b.position ? 1 : -1))+ .map((c) => ({ ...c, enabled: Boolean(c.enabled) }));+ } catch (e) {+ popupAjaxError(e);+ }+ }++ @action+ async save() {+ this.loading = true;+ this.flash = null;+ const data = {+ directory_columns: this.columns.map((c) => ({+ id: c.id,+ enabled: c.enabled,+ position: c.position,+ })),+ };++ try {+ await ajax("edit-directory-columns.json", { type: "PUT", data });+ reload();+ } catch (e) {+ this.loading = false;+ this.flash = extractError(e);+ }+ }++ @action+ resetToDefault() {+ const resetColumns = this.columns+ .sort((a, b) => {+ const a1 = a.automatic_position || (a.user_field?.position || 0) + 1000;+ const b1 = b.automatic_position || (b.user_field?.position || 0) + 1000;++ if (a1 === b1) {+ return a.name.localeCompare(b.name);+ } else {+ return a1 > b1 ? 1 : -1;+ }+ })+ .map((column, index) => ({+ ...column,+ position: column.automatic_position || index + 1,+ enabled: column.type === "automatic",+ }));++ this.columns = resetColumns;+ }++ /**+ * Applies a committed move and renumbers every column from its new visible+ * slot — the stored order is exactly the displayed one here.+ *+ * @param {Object} move - The normalized move from the list.+ */+ @action+ handleMove(move) {+ this.columns = move.proposedToItems.map((column, index) => ({+ ...column,+ position: index + 1,+ }));+ }++ <template>+ <DModal+ class="edit-user-directory-columns-modal"+ @closeModal={{@closeModal}}+ @flash={{this.flash}}+ @title={{i18n "directory.edit_columns.title"}}+ >+ <:body>+ {{#if this.loading}}+ {{dLoadingSpinner size="large"}}+ {{else}}+ <DReorderableList+ class="edit-directory-columns-container"+ @items={{this.columns}}+ @itemTag="div"+ @key="id"+ @label={{this.columnLabel}}+ @onMove={{this.handleMove}}+ @rowClass="edit-directory-column"+ @tag="div"+ >+ <:row as |column|>+ <div class="left-content">+ <label class="column-name">+ <Input @checked={{column.enabled}} @type="checkbox" />+ {{#if (directoryColumnIsAutomatic column=column)}}+ {{directoryTableHeaderTitle+ field=column.name+ icon=column.icon+ }}+ {{else if (directoryColumnIsUserField column=column)}}+ {{directoryTableHeaderTitle+ field=column.user_field.name+ translated=true+ }}+ {{else}}+ {{directoryTableHeaderTitle+ field=(i18n column.name)+ translated=true+ }}+ {{/if}}+ </label>+ </div>+ </:row>+ </DReorderableList>+ {{/if}}+ </:body>+ <:footer>+ <DButton+ class="btn-primary"+ @action={{this.save}}+ @label="directory.edit_columns.save"+ />+ <DButton+ class="btn-default reset-to-default"+ @action={{this.resetToDefault}}+ @label="directory.edit_columns.reset_to_default"+ />+ </:footer>+ </DModal>+ </template>+}diff --git a/frontend/discourse/app/components/modal/edit-user-directory-columns.gjs b/frontend/discourse/app/components/modal/edit-user-directory-columns.gjsindex 0d2947a0154..f646de11536 100644--- a/frontend/discourse/app/components/modal/edit-user-directory-columns.gjs+++ b/frontend/discourse/app/components/modal/edit-user-directory-columns.gjs@@ -17,6 +17,8 @@ import { i18n } from "discourse-i18n";const UP = "up";const DOWN = "down";+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `edit-user-directory-columns-reorderable.gjs` replaces it.export default class EditUserDirectoryColumns extends Component {@tracked loading = true;@tracked columns;diff --git a/frontend/discourse/app/components/modal/sidebar-section-form.gjs b/frontend/discourse/app/components/modal/sidebar-section-form.gjsindex af5a4e502a6..044821799a4 100644--- a/frontend/discourse/app/components/modal/sidebar-section-form.gjs+++ b/frontend/discourse/app/components/modal/sidebar-section-form.gjs@@ -7,7 +7,8 @@ import { action } from "@ember/object";import { service } from "@ember/service";import { isEmpty } from "@ember/utils";import { tagName } from "@ember-decorators/component";-import SectionFormLink from "discourse/components/sidebar/section-form-link";+import SectionFormLinks from "discourse/components/sidebar/section-form-links";+import SectionFormLinksReorderable from "discourse/components/sidebar/section-form-links-reorderable";import DTooltip from "discourse/float-kit/components/d-tooltip";import withEventValue from "discourse/helpers/with-event-value";import { ajax } from "discourse/lib/ajax";@@ -21,7 +22,7 @@ import { afterRender, bind } from "discourse/lib/decorators";import { isSameLocale } from "discourse/lib/locale-normalizer";import { sanitize } from "discourse/lib/text";import { autoTrackedArray } from "discourse/lib/tracked-tools";-import { eq, has, not } from "discourse/truth-helpers";+import { not } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import DModal from "discourse/ui-kit/d-modal";import DNativeSelect from "discourse/ui-kit/d-native-select";@@ -477,14 +478,6 @@ export default class SidebarSectionForm extends Component {return duplicates;}- get lastActiveLinkIndex() {- return this.activeLinks.length - 1;- }-- get lastActiveSecondaryLinkIndex() {- return (this.activeSecondaryLinks?.length ?? 0) - 1;- }-@cachedget activeLocalizations() {return this.#activeLocalizations(this.transformedModel);@@ -735,49 +728,13 @@ export default class SidebarSectionForm extends Component {@afterRenderfocusNewRowInput(id) {document- .querySelector(`[data-row-id="${id}"] .d-icon-grid-picker-trigger`)+ .querySelector(+ `[data-row-id="${id}"] .d-icon-grid-picker-trigger, ` ++ `[data-reorderable-key="${id}"] .d-icon-grid-picker-trigger`+ ).focus();}- @bind- setDraggedLink(link) {- this.draggedLink = link;- }-- @bind- reorder(targetLink, above) {- if (this.draggedLink === targetLink) {- return;- }-- const source = this.draggedLink.isPrimary- ? this.transformedModel.links- : this.transformedModel.secondaryLinks;- const destination = targetLink.isPrimary- ? this.transformedModel.links- : this.transformedModel.secondaryLinks;-- // Nothing to insert next to, so leave both arrays untouched rather than- // removing the link and dropping it at an arbitrary offset.- if (!destination.includes(targetLink)) {- return;- }-- removeValueFromArray(source, this.draggedLink);-- // Read after the removal: within one segment the two arrays are the same- // one, so a pre-removal index would be off by one when dragging downwards.- const toPosition = destination.indexOf(targetLink);-- this.draggedLink.segment = targetLink.isPrimary ? "primary" : "secondary";-- destination.splice(- above ? toPosition : toPosition + 1,- 0,- this.draggedLink- );- }-@binddeleteLink(link) {if (link.id) {@@ -1362,101 +1319,33 @@ export default class SidebarSectionForm extends Component {{{i18n "sidebar.sections.custom.links.title"}}</div>- <div- aria-labelledby="section-links-label"- aria-rowcount={{this.activeLinks.length}}- class="sidebar-section-form__links-wrapper"- role="table"- >-- <div class="row-wrapper header" role="row">- <div- aria-sort="none"- class="input-group link-icon"- role="columnheader"- >- {{! eslint-disable-next-line ember/template-no-nested-interactive }}- <label>{{i18n- "sidebar.sections.custom.links.icon.label"- }}</label>- </div>-- <div- aria-sort="none"- class="input-group link-name"- role="columnheader"- >- {{! eslint-disable-next-line ember/template-no-nested-interactive }}- <label>{{i18n- "sidebar.sections.custom.links.name.label"- }}</label>- </div>-- <div- aria-sort="none"- class="input-group link-url"- role="columnheader"- >- {{! eslint-disable-next-line ember/template-no-nested-interactive }}- <label>{{i18n- "sidebar.sections.custom.links.value.label"- }}</label>- </div>- </div>-- {{#each this.activeLinks key="objectId" as |link index|}}- <SectionFormLink- @deleteLink={{this.deleteLink}}- @duplicateValue={{has- this.duplicateLinkObjectIds- link.objectId- }}- @focusNameInput={{eq- link.objectId- this.initialFocusLinkObjectId- }}- @index={{index}}- @lastIndex={{this.lastActiveLinkIndex}}- @link={{link}}- @reorderCallback={{this.reorder}}- @setDraggedLinkCallback={{this.setDraggedLink}}- />- {{/each}}-- </div>- <DButton- class="btn-flat btn-text add-link"- @action={{this.addLink}}- @ariaLabel="sidebar.sections.custom.links.add"- @icon="plus"- @label="sidebar.sections.custom.links.add"- @title="sidebar.sections.custom.links.add"- />-- {{#if this.transformedModel.sectionType}}- <hr />- <h3>{{i18n "sidebar.sections.custom.more_menu"}}</h3>- {{#each this.activeSecondaryLinks key="objectId" as |link index|}}- <SectionFormLink- @deleteLink={{this.deleteLink}}- @duplicateValue={{has- this.duplicateLinkObjectIds- link.objectId- }}- @index={{index}}- @lastIndex={{this.lastActiveSecondaryLinkIndex}}- @link={{link}}- @reorderCallback={{this.reorder}}- @setDraggedLinkCallback={{this.setDraggedLink}}- />- {{/each}}- <DButton- class="btn-flat btn-text add-link"- @action={{this.addSecondaryLink}}- @ariaLabel="sidebar.sections.custom.links.add"- @icon="plus"- @label="sidebar.sections.custom.links.add"- @title="sidebar.sections.custom.links.add"+ {{! TODO (ui-kit-reorderable-list-cleanup) drop the branch and the+ legacy arm once the change ships. }}+ {{#if this.siteSettings.enable_new_reordering_controls}}+ <SectionFormLinksReorderable+ @activeLinks={{this.activeLinks}}+ @activeSecondaryLinks={{this.activeSecondaryLinks}}+ @addLink={{this.addLink}}+ @addSecondaryLink={{this.addSecondaryLink}}+ @deleteLink={{this.deleteLink}}+ @duplicateLinkObjectIds={{this.duplicateLinkObjectIds}}+ @initialFocusLinkObjectId={{this.initialFocusLinkObjectId}}+ @links={{this.transformedModel.links}}+ @secondaryLinks={{this.transformedModel.secondaryLinks}}+ @sectionType={{this.transformedModel.sectionType}}+ />+ {{else}}+ <SectionFormLinks+ @activeLinks={{this.activeLinks}}+ @activeSecondaryLinks={{this.activeSecondaryLinks}}+ @addLink={{this.addLink}}+ @addSecondaryLink={{this.addSecondaryLink}}+ @deleteLink={{this.deleteLink}}+ @duplicateLinkObjectIds={{this.duplicateLinkObjectIds}}+ @initialFocusLinkObjectId={{this.initialFocusLinkObjectId}}+ @links={{this.transformedModel.links}}+ @secondaryLinks={{this.transformedModel.secondaryLinks}}+ @sectionType={{this.transformedModel.sectionType}}/>{{/if}}diff --git a/frontend/discourse/app/components/sidebar/section-form-link-reorderable.gjs b/frontend/discourse/app/components/sidebar/section-form-link-reorderable.gjsnew file mode 100644index 00000000000..445a37e2ced--- /dev/null+++ b/frontend/discourse/app/components/sidebar/section-form-link-reorderable.gjs@@ -0,0 +1,99 @@+import { Input } from "@ember/component";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import withEventValue from "discourse/helpers/with-event-value";+import DButton from "discourse/ui-kit/d-button";+import DIconGridPicker from "discourse/ui-kit/d-icon-grid-picker";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";+import { i18n } from "discourse-i18n";++/**+ * One link row's cells inside the section form's reorderable lists. The row+ * element, its drag wiring, and the reorder announcements are the list's; what+ * lives here is the link's own fields plus the placement of the pre-wired+ * controls into the row's grid tracks.+ */+// TODO (ui-kit-reorderable-list-cleanup) rename this over+// `section-form-link.gjs` once the change ships.+const SectionFormLink = <template>+ {{! Every viewport, because a touch screen can drag from a grip and had no+ way to reorder at all while this was desktop-only. The drag starts at the+ grip rather than anywhere on the row, so a press that was meant to+ scroll still scrolls, and its menu carries the paths a drag cannot. }}+ <@controls.handle+ class="draggable"+ data-link-name={{@link.name}}+ role="cell"+ />++ <div class="input-group link-icon" role="cell">+ <DIconGridPicker+ aria-label={{i18n "sidebar.sections.custom.links.icon.label"}}+ @btnClass={{dConcatClass "btn-default" @link.iconCssClass}}+ @onChange={{fn (mut @link.icon)}}+ @showCaret={{true}}+ @value={{@link.icon}}+ />++ {{#if @link.invalidIconMessage}}+ <div aria-live="assertive" class="icon warning" role="alert">+ {{@link.invalidIconMessage}}+ </div>+ {{/if}}+ </div>++ <div class="input-group link-name" role="cell">++ <Input+ aria-label={{i18n "sidebar.sections.custom.links.name.label"}}+ class={{@link.nameCssClass}}+ data-1p-ignore+ name="link-name"+ @type="text"+ @value={{@link.name}}+ {{(if @focusNameInput (modifier dAutoFocus selectText=true))}}+ {{on "input" (withEventValue (fn (mut @link.name)))}}+ />++ {{#if @link.invalidNameMessage}}+ <div aria-live="assertive" class="name warning" role="alert">+ {{@link.invalidNameMessage}}+ </div>+ {{/if}}+ </div>++ <div class="input-group link-url" role="cell">++ <Input+ aria-label={{i18n "sidebar.sections.custom.links.value.label"}}+ class={{@link.valueCssClass}}+ name="link-url"+ @type="text"+ @value={{@link.value}}+ {{on "input" (withEventValue (fn (mut @link.value)))}}+ />++ {{#if @link.invalidValueMessage}}+ <div aria-live="assertive" class="value warning" role="alert">+ {{@link.invalidValueMessage}}+ </div>+ {{else if @duplicateValue}}+ {{! Not announced assertively: nothing is wrong yet, and the row still+ saves. }}+ <div class="value warning duplicate-link">+ {{i18n "sidebar.sections.custom.links.value.duplicate"}}+ </div>+ {{/if}}+ </div>++ <DButton+ class="btn-flat delete-link"+ role="cell"+ @action={{fn @deleteLink @link}}+ @icon="trash-can"+ @title="sidebar.sections.custom.links.delete"+ />+</template>;++export default SectionFormLink;diff --git a/frontend/discourse/app/components/sidebar/section-form-link.gjs b/frontend/discourse/app/components/sidebar/section-form-link.gjsindex 14a437b44a4..f1ba2c84738 100644--- a/frontend/discourse/app/components/sidebar/section-form-link.gjs+++ b/frontend/discourse/app/components/sidebar/section-form-link.gjs@@ -14,6 +14,9 @@ import dIcon from "discourse/ui-kit/helpers/d-icon";import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";import { i18n } from "discourse-i18n";+// TODO (ui-kit-reorderable-list-cleanup) delete this file once+// `enable_new_reordering_controls` ships; `section-form-link-reorderable.gjs`+// replaces it.export default class SectionFormLink extends Component {@service site;diff --git a/frontend/discourse/app/components/sidebar/section-form-links-reorderable.gjs b/frontend/discourse/app/components/sidebar/section-form-links-reorderable.gjsnew file mode 100644index 00000000000..8db5a630301--- /dev/null+++ b/frontend/discourse/app/components/sidebar/section-form-links-reorderable.gjs@@ -0,0 +1,178 @@+import Component from "@glimmer/component";+import SectionFormLinkReorderable from "discourse/components/sidebar/section-form-link-reorderable";+import { removeValueFromArray } from "discourse/lib/array-tools";+import { bind } from "discourse/lib/decorators";+import { eq, has } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import DReorderableList from "discourse/ui-kit/d-reorderable-list";+import DReorderableListGroup from "discourse/ui-kit/d-reorderable-list-group";+import { i18n } from "discourse-i18n";++/**+ * The section form's links region behind `enable_new_reordering_controls`, over+ * the shared reorderable list. The two lists are grouped so a link can move+ * between the primary set and the more menu.+ *+ * The arrays arrive by reference and are mutated in place, which is what the+ * form's own tracking already relies on.+ *+ * TODO (ui-kit-reorderable-list-cleanup) rename this over+ * `section-form-links.gjs` and drop the branch in the section form.+ */+export default class SidebarSectionFormLinksReorderable extends Component {+ linkName = (link) => link.name;++ /**+ * Applies a committed move onto the backing arrays, which hold links awaiting+ * deletion as well as visible ones.+ *+ * @param {Object} move - The normalized move from the list.+ */+ @bind+ handleMove(move) {+ const arrays = {+ primary: this.args.links,+ secondary: this.args.secondaryLinks,+ };+ const source = arrays[move.fromList];+ const destination = arrays[move.toList];++ if (move.fromList !== move.toList) {+ removeValueFromArray(source, move.item);+ move.item.segment = move.toList;+ // Anchored on the visible link that follows the landing slot, so links+ // awaiting deletion keep their positions in the stored array.+ const following = move.proposedToItems[move.toIndex + 1];+ const at = following+ ? destination.indexOf(following)+ : destination.length;+ destination.splice(at, 0, move.item);+ return;+ }++ const proposed = [...move.proposedToItems];+ const next = destination.map((link) =>+ link._destroy ? link : proposed.shift()+ );+ destination.splice(0, destination.length, ...next);+ }++ <template>+ <DReorderableListGroup @onMove={{this.handleMove}} as |group|>+ <DReorderableList+ aria-labelledby="section-links-label"+ aria-rowcount={{@activeLinks.length}}+ class="sidebar-section-form__links-wrapper"+ @controls="manual"+ @group={{group}}+ @itemRole="row"+ @items={{@activeLinks}}+ @itemTag="div"+ @key="objectId"+ @label={{this.linkName}}+ @listId="primary"+ @listLabel={{i18n "sidebar.sections.custom.links.title"}}+ @role="table"+ @rowClass="sidebar-section-form-link row-wrapper"+ @tag="div"+ >+ <:header>+ {{! The list element around this block carries the table role+ through its role argument, which the static rule cannot+ see from here. }}+ {{! eslint-disable-next-line ember/template-require-context-role }}+ <div class="row-wrapper header" role="row">+ <div+ aria-sort="none"+ class="input-group link-icon"+ role="columnheader"+ >+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <label>{{i18n "sidebar.sections.custom.links.icon.label"}}</label>+ </div>++ <div+ aria-sort="none"+ class="input-group link-name"+ role="columnheader"+ >+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <label>{{i18n "sidebar.sections.custom.links.name.label"}}</label>+ </div>++ <div+ aria-sort="none"+ class="input-group link-url"+ role="columnheader"+ >+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <label>{{i18n+ "sidebar.sections.custom.links.value.label"+ }}</label>+ </div>+ </div>+ </:header>+ <:row as |link controls|>+ <SectionFormLinkReorderable+ @controls={{controls}}+ @deleteLink={{@deleteLink}}+ @duplicateValue={{has @duplicateLinkObjectIds link.objectId}}+ @focusNameInput={{eq link.objectId @initialFocusLinkObjectId}}+ @link={{link}}+ />+ </:row>+ </DReorderableList>+ <DButton+ class="btn-flat btn-text add-link"+ @action={{@addLink}}+ @ariaLabel="sidebar.sections.custom.links.add"+ @icon="plus"+ @label="sidebar.sections.custom.links.add"+ @title="sidebar.sections.custom.links.add"+ />++ {{#if @sectionType}}+ <hr />+ <h3 id="section-secondary-links-label">{{i18n+ "sidebar.sections.custom.more_menu"+ }}</h3>+ {{! The rows resolve their columns through the wrapper's grid, so+ a list rendered without one would collapse. }}+ <DReorderableList+ aria-labelledby="section-secondary-links-label"+ aria-rowcount={{@activeSecondaryLinks.length}}+ class="sidebar-section-form__links-wrapper --secondary"+ @controls="manual"+ @group={{group}}+ @itemRole="row"+ @items={{@activeSecondaryLinks}}+ @itemTag="div"+ @key="objectId"+ @label={{this.linkName}}+ @listId="secondary"+ @listLabel={{i18n "sidebar.sections.custom.more_menu"}}+ @role="table"+ @rowClass="sidebar-section-form-link row-wrapper"+ @tag="div"+ >+ <:row as |link controls|>+ <SectionFormLinkReorderable+ @controls={{controls}}+ @deleteLink={{@deleteLink}}+ @duplicateValue={{has @duplicateLinkObjectIds link.objectId}}+ @link={{link}}+ />+ </:row>+ </DReorderableList>+ <DButton+ class="btn-flat btn-text add-link"+ @action={{@addSecondaryLink}}+ @ariaLabel="sidebar.sections.custom.links.add"+ @icon="plus"+ @label="sidebar.sections.custom.links.add"+ @title="sidebar.sections.custom.links.add"+ />+ {{/if}}+ </DReorderableListGroup>+ </template>+}diff --git a/frontend/discourse/app/components/sidebar/section-form-links.gjs b/frontend/discourse/app/components/sidebar/section-form-links.gjsnew file mode 100644index 00000000000..08711756113--- /dev/null+++ b/frontend/discourse/app/components/sidebar/section-form-links.gjs@@ -0,0 +1,145 @@+import Component from "@glimmer/component";+import SectionFormLink from "discourse/components/sidebar/section-form-link";+import { removeValueFromArray } from "discourse/lib/array-tools";+import { bind } from "discourse/lib/decorators";+import { eq, has } from "discourse/truth-helpers";+import DButton from "discourse/ui-kit/d-button";+import { i18n } from "discourse-i18n";++/**+ * The section form's links region as it renders without+ * `enable_new_reordering_controls`: a hand-rolled table whose rows carry their+ * own drag handlers.+ *+ * The arrays arrive by reference and are mutated in place, which is what the+ * form's own tracking already relies on.+ *+ * TODO (ui-kit-reorderable-list-cleanup) delete this file once the change+ * ships; `sidebar-section-form-links-reorderable.gjs` replaces it.+ */+export default class SidebarSectionFormLinks extends Component {+ // Not a # private: the legacy decorator transform cannot compile a class+ // that mixes a decorated member with private fields, and it fails the build+ // rather than the lint.+ draggedLink;++ get lastActiveLinkIndex() {+ return this.args.activeLinks.length - 1;+ }++ get lastActiveSecondaryLinkIndex() {+ return (this.args.activeSecondaryLinks?.length ?? 0) - 1;+ }++ @bind+ setDraggedLink(link) {+ this.draggedLink = link;+ }++ @bind+ reorder(targetLink, above) {+ if (this.draggedLink === targetLink) {+ return;+ }++ const source = this.draggedLink.isPrimary+ ? this.args.links+ : this.args.secondaryLinks;+ const destination = targetLink.isPrimary+ ? this.args.links+ : this.args.secondaryLinks;++ // Nothing to insert next to, so leave both arrays untouched rather than+ // removing the link and dropping it at an arbitrary offset.+ if (!destination.includes(targetLink)) {+ return;+ }++ removeValueFromArray(source, this.draggedLink);++ // Read after the removal: within one segment the two arrays are the same+ // one, so a pre-removal index would be off by one when dragging downwards.+ const toPosition = destination.indexOf(targetLink);++ this.draggedLink.segment = targetLink.isPrimary ? "primary" : "secondary";++ destination.splice(+ above ? toPosition : toPosition + 1,+ 0,+ this.draggedLink+ );+ }++ <template>+ <div+ aria-labelledby="section-links-label"+ aria-rowcount={{@activeLinks.length}}+ class="sidebar-section-form__links-wrapper"+ role="table"+ >++ <div class="row-wrapper header" role="row">+ <div aria-sort="none" class="input-group link-icon" role="columnheader">+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <label>{{i18n "sidebar.sections.custom.links.icon.label"}}</label>+ </div>++ <div aria-sort="none" class="input-group link-name" role="columnheader">+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <label>{{i18n "sidebar.sections.custom.links.name.label"}}</label>+ </div>++ <div aria-sort="none" class="input-group link-url" role="columnheader">+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <label>{{i18n "sidebar.sections.custom.links.value.label"}}</label>+ </div>+ </div>++ {{#each @activeLinks key="objectId" as |link index|}}+ <SectionFormLink+ @deleteLink={{@deleteLink}}+ @duplicateValue={{has @duplicateLinkObjectIds link.objectId}}+ @focusNameInput={{eq link.objectId @initialFocusLinkObjectId}}+ @index={{index}}+ @lastIndex={{this.lastActiveLinkIndex}}+ @link={{link}}+ @reorderCallback={{this.reorder}}+ @setDraggedLinkCallback={{this.setDraggedLink}}+ />+ {{/each}}++ </div>+ <DButton+ class="btn-flat btn-text add-link"+ @action={{@addLink}}+ @ariaLabel="sidebar.sections.custom.links.add"+ @icon="plus"+ @label="sidebar.sections.custom.links.add"+ @title="sidebar.sections.custom.links.add"+ />++ {{#if @sectionType}}+ <hr />+ <h3>{{i18n "sidebar.sections.custom.more_menu"}}</h3>+ {{#each @activeSecondaryLinks key="objectId" as |link index|}}+ <SectionFormLink+ @deleteLink={{@deleteLink}}+ @duplicateValue={{has @duplicateLinkObjectIds link.objectId}}+ @index={{index}}+ @lastIndex={{this.lastActiveSecondaryLinkIndex}}+ @link={{link}}+ @reorderCallback={{this.reorder}}+ @setDraggedLinkCallback={{this.setDraggedLink}}+ />+ {{/each}}+ <DButton+ class="btn-flat btn-text add-link"+ @action={{@addSecondaryLink}}+ @ariaLabel="sidebar.sections.custom.links.add"+ @icon="plus"+ @label="sidebar.sections.custom.links.add"+ @title="sidebar.sections.custom.links.add"+ />+ {{/if}}+ </template>+}diff --git a/frontend/discourse/app/controllers/users.js b/frontend/discourse/app/controllers/users.jsindex 5e62c9b44e1..a489d0238f5 100644--- a/frontend/discourse/app/controllers/users.js+++ b/frontend/discourse/app/controllers/users.js@@ -4,12 +4,14 @@ import { action, computed } from "@ember/object";import { dependentKeyCompat } from "@ember/object/compat";import { service } from "@ember/service";import EditUserDirectoryColumnsModal from "discourse/components/modal/edit-user-directory-columns";+import EditUserDirectoryColumnsModalReorderable from "discourse/components/modal/edit-user-directory-columns-reorderable";import discourseDebounce from "discourse/lib/debounce";import { longDate } from "discourse/lib/formatter";import Group from "discourse/models/group";export default class UsersController extends Controller {@service modal;+ @service siteSettings;@tracked period = "weekly";@@ -110,7 +112,13 @@ export default class UsersController extends Controller {@actionshowEditColumnsModal() {- this.modal.show(EditUserDirectoryColumnsModal);+ // TODO (ui-kit-reorderable-list-cleanup) drop the branch and the legacy+ // component once the change ships.+ const Modal = this.siteSettings.enable_new_reordering_controls+ ? EditUserDirectoryColumnsModalReorderable+ : EditUserDirectoryColumnsModal;++ this.modal.show(Modal);}@actiondiff --git a/frontend/discourse/tests/acceptance/manage-reports-drag-and-drop-test.gjs b/frontend/discourse/tests/acceptance/manage-reports-drag-and-drop-test.gjsnew file mode 100644index 00000000000..68697b99262--- /dev/null+++ b/frontend/discourse/tests/acceptance/manage-reports-drag-and-drop-test.gjs@@ -0,0 +1,512 @@+import { getOwner } from "@ember/owner";+import { fillIn, find, findAll, settled, visit } from "@ember/test-helpers";+import { test } from "qunit";+import ManageReportsReorderable from "discourse/admin/components/modal/manage-reports-reorderable";+import {+ disableClearA11yAnnouncementsInTests,+ enableClearA11yAnnouncementsInTests,+} from "discourse/services/a11y";+import { acceptance } from "discourse/tests/helpers/qunit-helpers";+import {+ centerOf,+ dragEvent,+ simulateDrag,+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";+import {+ moveVia,+ openMoveMenu,+} from "discourse/tests/helpers/ui-kit/reorderable-list-helper";++const REORDER_TEST_PREFIX = "Manage reports reordering";++const REPORTS = [+ {+ source: "core_report",+ identifier: "signups",+ key: "core_report:signups",+ title: "Matching signups",+ description: "New account signups",+ },+ {+ source: "core_report",+ identifier: "topics",+ key: "core_report:topics",+ title: "Matching topics",+ description: "New topics",+ },+ {+ source: "core_report",+ identifier: "posts",+ key: "core_report:posts",+ title: "Other posts",+ description: "New posts",+ },+];++function rowSelector(key) {+ return `.manageable-row-list__row[data-reorderable-key="${key}"]`;+}++// A drag starts on the handle rather than anywhere on the row, so a press meant to+// scroll still scrolls. The row owns the source data, while the shared helper+// dispatches the browser events on the handle carrying the draggable registration.+function rowHandleSelector(key) {+ return `${rowSelector(key)} .d-reorderable-list__handle`;+}++function enabledKeys() {+ return findAll(".manageable-row-list__row.--enabled").map(+ (row) => row.dataset.reorderableKey+ );+}++async function openModal(context) {+ await visit("/");+ getOwner(context).lookup("service:modal").show(ManageReportsReorderable);+ await settled();+}++async function dragReport(sourceKey, targetKey, position) {+ const source = rowSelector(sourceKey);+ const target = rowSelector(targetKey);++ const targetRect = find(target).getBoundingClientRect();+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ sourceCoordinates: centerOf(rowHandleSelector(sourceKey)),+ targetCoordinates: {+ clientY:+ position === "above" ? targetRect.top + 1 : targetRect.bottom - 1,+ },+ });+}++acceptance("Manage reports drag and drop | reorderable", function (needs) {+ needs.user({ admin: true });+ needs.settings({ enable_new_reordering_controls: true });+ needs.pretender((server, helper) => {+ server.get("/admin/dashboard/reports/available.json", () =>+ helper.response({+ enabled: REPORTS.slice(0, 2),+ available: REPORTS,+ providers: [],+ cursor: null,+ has_more: false,+ })+ );+ });++ // `settled()` waits out pending timers, and an announcement schedules its own+ // clear, so a message read after an awaited interaction would always be gone.+ needs.hooks.beforeEach(disableClearA11yAnnouncementsInTests);+ needs.hooks.afterEach(enableClearA11yAnnouncementsInTests);++ test(`${REORDER_TEST_PREFIX} adjacent rows leave no dead space between drop zones`, async function (assert) {+ await openModal(this);++ assert+ .dom(".d-reorderable-list__handle")+ .exists("the reorderable arm rendered");++ // Container spacing (a flex `gap`) belongs to the list, not to either row,+ // so a pointer inside it reaches no drop target and the above/below zones+ // stop meeting.+ const rows = findAll(".manageable-row-list__row");+ for (let i = 1; i < rows.length; i++) {+ const previous = rows[i - 1].getBoundingClientRect();+ const current = rows[i].getBoundingClientRect();++ assert.strictEqual(+ Math.round(current.top),+ Math.round(previous.bottom),+ `row ${i} starts exactly where row ${i - 1} ends, so no pointer position between them falls outside both`+ );+ }+ });++ test(`${REORDER_TEST_PREFIX} renders a handle per row and a menu of destinations`, async function (assert) {+ await openModal(this);++ assert.dom(".d-reorderable-list__handle").exists({ count: 2 });+ await openMoveMenu("core_report:topics");+ assert+ .dom(".d-reorderable-list__move-item")+ .exists(+ { count: 2 },+ "desktop keeps a pointer path to reorder, not only the drag"+ );+ });++ test(`${REORDER_TEST_PREFIX} the move menu reorders the enabled list`, async function (assert) {+ await openModal(this);++ await moveVia("core_report:topics", "up");++ assert.deepEqual(+ enabledKeys(),+ ["core_report:topics", "core_report:signups"],+ "the menu moves the report earlier, with no drag involved"+ );+ });++ test(`${REORDER_TEST_PREFIX} the menu path announces through the same call as the drag`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ await openModal(this);++ await moveVia("core_report:topics", "up");++ assert.strictEqual(+ a11y.politeMessage,+ "Moved Matching topics to position 1 of 3",+ "a menu move announces exactly like the equivalent drag, counting the disabled row the reader can also see"+ );+ });++ test(`${REORDER_TEST_PREFIX} announces where a dragged report landed`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ await openModal(this);++ await dragReport("core_report:topics", "core_report:signups", "above");++ assert.strictEqual(+ a11y.politeMessage,+ "Moved Matching topics to position 1 of 3",+ "a completed drag announces the report and its resulting position"+ );+ });++ test(`${REORDER_TEST_PREFIX} announces nothing when a drop changes no order`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ await openModal(this);++ const before = a11y.politeMessage;++ await dragReport("core_report:signups", "core_report:signups", "above");+ assert.strictEqual(+ a11y.politeMessage,+ before,+ "dropping a report onto itself is not a reorder, so nothing is announced"+ );++ // Below the report directly above it resolves to the index it already holds.+ await dragReport("core_report:topics", "core_report:signups", "below");+ assert.strictEqual(+ a11y.politeMessage,+ before,+ "a drop that resolves to the report's current index announces nothing"+ );+ });++ test(`${REORDER_TEST_PREFIX} reorders by stable key with a search filter applied`, async function (assert) {+ await openModal(this);+ await fillIn(+ ".manageable-row-list__search-wrapper .filter-input",+ "Matching"+ );++ await dragReport("core_report:topics", "core_report:signups", "above");++ assert.deepEqual(+ enabledKeys(),+ ["core_report:topics", "core_report:signups"],+ "a filtered reorder resolves fresh visible-row copies through their stable keys"+ );+ });++ test(`${REORDER_TEST_PREFIX} conditionally registers rows and puts the grab cursor on the handle`, async function (assert) {+ await openModal(this);++ const disabledRow = rowSelector("core_report:posts");+ assert+ .dom(disabledRow)+ .doesNotHaveAttribute(+ "data-drag-source",+ "a disabled row has no active drag-source registration"+ )+ .doesNotHaveAttribute(+ "draggable",+ "a disabled row is not stamped as draggable"+ );+ // The grip is what a drag begins on, so it is what advertises the grab. The+ // row must not: its text is selectable, and a `grab` cursor over text would+ // promise a gesture pressing there does not perform.+ assert.strictEqual(+ getComputedStyle(find(rowSelector("core_report:signups"))).cursor,+ "auto",+ "an enabled row does not claim the grab cursor across its whole width"+ );+ // Paired with the row above, because `auto` is what an unstyled element+ // reports anyway: on its own that assertion passes even if no rule is+ // reached at all.+ assert.strictEqual(+ getComputedStyle(find(rowHandleSelector("core_report:signups"))).cursor,+ "grab",+ "the handle does, so the rule is reached"+ );++ assert+ .dom(".manageable-row-list__row.--enabled[data-drop-target]")+ .exists({ count: 2 }, "every enabled reorderable row is a drop target");+ assert+ .dom(".manageable-row-list__row.--enabled[data-drag-source]")+ .exists(+ { count: 2 },+ "every enabled row carries the drag registration, so a drag shows the row"+ );+ assert+ .dom(+ '.manageable-row-list__row.--enabled .d-reorderable-list__handle[draggable="true"]'+ )+ .exists({ count: 2 }, "and its handle is where the drag begins");+ });++ test(`${REORDER_TEST_PREFIX} uses the shared drag state classes`, async function (assert) {+ await openModal(this);++ const source = rowSelector("core_report:signups");+ const target = rowSelector("core_report:topics");+ const dataTransfer = new DataTransfer();+ const sourceHandle = rowHandleSelector("core_report:signups");+ const sourceCoordinates = centerOf(sourceHandle);+ const targetRect = find(target).getBoundingClientRect();+ const targetCoordinates = {+ clientX: targetRect.left + targetRect.width / 2,+ clientY: targetRect.top + 1,+ };++ await dragEvent(sourceHandle, "dragstart", {+ dataTransfer,+ ...sourceCoordinates,+ });+ await dragEvent(target, "dragenter", {+ dataTransfer,+ ...targetCoordinates,+ });+ await dragEvent(target, "dragover", {+ dataTransfer,+ offsetY: 1,+ ...targetCoordinates,+ });++ assert+ .dom(source)+ .hasClass("--dragging", "the source uses the shared dragging class");+ assert+ .dom(target)+ .hasClass("--drag-above", "the target uses the shared above indicator");++ await dragEvent(sourceHandle, "dragend", {+ dataTransfer,+ ...sourceCoordinates,+ });+ });++ test(`${REORDER_TEST_PREFIX} leaves no indicator after an abandoned drag`, async function (assert) {+ await openModal(this);++ const source = rowSelector("core_report:signups");+ const target = rowSelector("core_report:topics");+ const dataTransfer = new DataTransfer();+ const sourceHandle = rowHandleSelector("core_report:signups");+ const sourceCoordinates = centerOf(sourceHandle);+ const targetRect = find(target).getBoundingClientRect();+ const targetCoordinates = {+ clientX: targetRect.left + targetRect.width / 2,+ clientY: targetRect.top + 1,+ };++ await dragEvent(sourceHandle, "dragstart", {+ dataTransfer,+ ...sourceCoordinates,+ });+ await dragEvent(target, "dragenter", {+ dataTransfer,+ ...targetCoordinates,+ });+ await dragEvent(target, "dragover", {+ dataTransfer,+ offsetY: 1,+ ...targetCoordinates,+ });+ await dragEvent(sourceHandle, "dragend", {+ dataTransfer,+ ...sourceCoordinates,+ });++ assert+ .dom(source)+ .doesNotHaveClass(+ "--dragging",+ "an abandoned drag clears the source indicator"+ )+ .doesNotHaveClass(+ "dragging",+ "an abandoned drag leaves no legacy source indicator"+ );+ assert+ .dom(target)+ .doesNotHaveClass(+ "drag-above",+ "an abandoned drag leaves no legacy above indicator"+ )+ .doesNotHaveClass(+ "drag-below",+ "an abandoned drag leaves no legacy below indicator"+ )+ .doesNotHaveClass(+ "--drag-above",+ "an abandoned drag clears the target's above indicator"+ )+ .doesNotHaveClass(+ "--drag-below",+ "an abandoned drag clears the target's below indicator"+ );+ });+});++acceptance(+ "Manage reports menu reorder with a hidden row between matches | reorderable",+ function (needs) {+ needs.user({ admin: true });+ needs.settings({ enable_new_reordering_controls: true });+ needs.pretender((server, helper) =>+ server.get("/admin/dashboard/reports/available.json", () =>+ helper.response({+ // Order matters: the row the filter hides sits BETWEEN the two it+ // shows, which is the arrangement that separates moving by displayed+ // position from moving by stored position.+ enabled: [REPORTS[0], REPORTS[2], REPORTS[1]],+ available: REPORTS,+ providers: [],+ cursor: null,+ has_more: false,+ })+ )+ );++ needs.hooks.beforeEach(disableClearA11yAnnouncementsInTests);+ needs.hooks.afterEach(enableClearA11yAnnouncementsInTests);++ test(`${REORDER_TEST_PREFIX} moves a row past its visible neighbour from the menu`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ await openModal(this);++ assert+ .dom(".d-reorderable-list__handle")+ .exists("the reorderable arm rendered");++ await fillIn(+ ".manageable-row-list__search-wrapper .filter-input",+ "Matching"+ );++ assert.deepEqual(+ enabledKeys(),+ ["core_report:signups", "core_report:topics"],+ "the filter shows the two matching rows, with one hidden between them"+ );++ await moveVia("core_report:signups", "down");++ assert.deepEqual(+ enabledKeys(),+ ["core_report:topics", "core_report:signups"],+ "the row moves past its visible neighbour, so the list the user sees actually changes"+ );+ assert.strictEqual(+ a11y.politeMessage,+ "Moved Matching signups to position 2 of 2",+ "and the announced position counts the rows on screen, not the stored order"+ );+ });++ test(`${REORDER_TEST_PREFIX} drag announces the same displayed position as the menu`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ await openModal(this);+ await fillIn(+ ".manageable-row-list__search-wrapper .filter-input",+ "Matching"+ );++ await dragReport("core_report:signups", "core_report:topics", "below");++ assert.deepEqual(+ enabledKeys(),+ ["core_report:topics", "core_report:signups"],+ "the drag reaches the same order the menu did"+ );+ // The stored order is three long and the row lands third in it, so an+ // announcement counted there would say "3 of 3" for a list showing two.+ assert.strictEqual(+ a11y.politeMessage,+ "Moved Matching signups to position 2 of 2",+ "so it announces the same position, counted on screen rather than in the stored order"+ );+ });++ test(`${REORDER_TEST_PREFIX} filtered drag leaves the hidden row in its slot`, async function (assert) {+ await openModal(this);+ await fillIn(+ ".manageable-row-list__search-wrapper .filter-input",+ "Matching"+ );++ await dragReport("core_report:signups", "core_report:topics", "below");++ await fillIn(".manageable-row-list__search-wrapper .filter-input", "");++ assert.deepEqual(+ enabledKeys(),+ ["core_report:topics", "core_report:posts", "core_report:signups"],+ "the two rows on screen swap the slots they held, and the row between them keeps its own"+ );+ });++ test(`${REORDER_TEST_PREFIX} the menu leaves the hidden row in the same slot as drag`, async function (assert) {+ await openModal(this);+ await fillIn(+ ".manageable-row-list__search-wrapper .filter-input",+ "Matching"+ );++ await moveVia("core_report:signups", "down");++ await fillIn(".manageable-row-list__search-wrapper .filter-input", "");++ assert.deepEqual(+ enabledKeys(),+ ["core_report:topics", "core_report:posts", "core_report:signups"],+ "so the two ways of reordering persist the same order rather than disagreeing about the hidden row"+ );+ });++ test(`${REORDER_TEST_PREFIX} no-op filtered drag changes nothing`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ await openModal(this);+ await fillIn(+ ".manageable-row-list__search-wrapper .filter-input",+ "Matching"+ );++ const before = a11y.politeMessage;++ // Below the row shown above it, which is the position it already holds.+ // In the stored order it is a move, because of the row hidden between.+ await dragReport("core_report:topics", "core_report:signups", "below");++ assert.strictEqual(+ a11y.politeMessage,+ before,+ "a drop onto the position the row already occupies announces nothing"+ );++ await fillIn(".manageable-row-list__search-wrapper .filter-input", "");++ assert.deepEqual(+ enabledKeys(),+ ["core_report:signups", "core_report:posts", "core_report:topics"],+ "and stores nothing, rather than quietly moving the row the user cannot see"+ );+ });+ }+);diff --git a/frontend/discourse/tests/integration/components/admin-config-areas/flags-reorderable-test.gjs b/frontend/discourse/tests/integration/components/admin-config-areas/flags-reorderable-test.gjsnew file mode 100644index 00000000000..a4602cf587f--- /dev/null+++ b/frontend/discourse/tests/integration/components/admin-config-areas/flags-reorderable-test.gjs@@ -0,0 +1,92 @@+import { getOwner } from "@ember/owner";+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import FlagsReorderable from "discourse/admin/components/admin-config-areas/flags-reorderable";+import { SYSTEM_FLAG_IDS } from "discourse/admin/lib/constants";+import DMenus from "discourse/float-kit/components/d-menus";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import { moveVia } from "discourse/tests/helpers/ui-kit/reorderable-list-helper";++module(+ "Integration | Component | AdminConfigAreas | FlagsReorderable",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ const flags = [+ { id: SYSTEM_FLAG_IDS.notify_user, name: "Message" },+ { id: SYSTEM_FLAG_IDS.off_topic, name: "Off-Topic" },+ { id: SYSTEM_FLAG_IDS.inappropriate, name: "Inappropriate" },+ { id: SYSTEM_FLAG_IDS.spam, name: "Spam" },+ { id: SYSTEM_FLAG_IDS.illegal, name: "Illegal" },+ ].map((flag) => ({+ ...flag,+ name_key: flag.name.toLowerCase(),+ description: "",+ enabled: true,+ is_flag: true,+ system: true,+ }));+ getOwner(this).lookup("service:site").set("post_action_types", flags);++ // The endpoint as the server implements it: the flag lands on a position+ // among the flags that can move.+ this.serverOrder = flags.slice(1).map((flag) => flag.name);+ this.serverRefuses = false;+ pretender.put("/admin/config/flags/:id/move", (request) => {+ if (this.serverRefuses) {+ return response(422, { errors: ["refused"] });+ }+ const name = flags.find(+ (flag) => flag.id === Number(request.params.id)+ ).name;+ const position = Number(+ new URLSearchParams(request.requestBody).get("position")+ );+ this.serverOrder.splice(this.serverOrder.indexOf(name), 1);+ this.serverOrder.splice(position, 0, name);+ return response(204, {});+ });+ });++ function displayedOrder() {+ return [...document.querySelectorAll(".admin-flag-item__name")].map(+ (element) => element.textContent.trim()+ );+ }++ test("a move across several rows reaches the server", async function (assert) {+ await render(<template><DMenus /><FlagsReorderable /></template>);++ await moveVia(SYSTEM_FLAG_IDS.off_topic, "bottom");++ assert.deepEqual(+ this.serverOrder,+ ["Inappropriate", "Spam", "Illegal", "Off-Topic"],+ "the server moved the flag as far as the list did"+ );+ assert.deepEqual(+ displayedOrder(),+ ["Message", ...this.serverOrder],+ "the list shows the order the server holds"+ );+ });++ test("a move the server refuses is undone", async function (assert) {+ this.serverRefuses = true;+ await render(<template><DMenus /><FlagsReorderable /></template>);++ await moveVia(SYSTEM_FLAG_IDS.illegal, "top");++ assert.deepEqual(+ displayedOrder(),+ ["Message", "Off-Topic", "Inappropriate", "Spam", "Illegal"],+ "the list is back in the order the server holds"+ );+ assert+ .dom(".admin-flag-item.illegal")+ .hasClass("saved", "the row is no longer pending");+ });+ }+);diff --git a/frontend/discourse/tests/integration/components/admin-flag-item-reorderable-test.gjs b/frontend/discourse/tests/integration/components/admin-flag-item-reorderable-test.gjsnew file mode 100644index 00000000000..8c62321de6c--- /dev/null+++ b/frontend/discourse/tests/integration/components/admin-flag-item-reorderable-test.gjs@@ -0,0 +1,84 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import AdminFlagItemReorderable from "discourse/admin/components/admin-flag-item-reorderable";+import DMenus from "discourse/float-kit/components/d-menus";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";++module("Integration | Component | AdminFlagItemReorderable", function (hooks) {+ setupRenderingTest(hooks);++ function createFlag(overrides = {}) {+ return {+ id: 1001,+ name: "colliding",+ name_key: "custom_colliding",+ description: "custom flag",+ enabled: true,+ is_used: false,+ system: false,+ ...overrides,+ };+ }++ test("custom flag is editable", async function (assert) {+ this.flag = createFlag();++ await render(+ <template>+ <DMenus />+ <table><tbody><tr>+ <AdminFlagItemReorderable @flag={{this.flag}} />+ </tr></tbody></table>+ </template>+ );++ assert+ .dom(".admin-flag-item__edit")+ .doesNotHaveAttribute("disabled", "the edit button is enabled");+ assert+ .dom(".d-table__overview-link")+ .exists("the name links to the edit route");+ });++ test("system flag is not editable", async function (assert) {+ this.flag = createFlag({ id: 3, name_key: "off_topic", system: true });++ await render(+ <template>+ <DMenus />+ <table><tbody><tr>+ <AdminFlagItemReorderable @flag={{this.flag}} />+ </tr></tbody></table>+ </template>+ );++ assert+ .dom(".admin-flag-item__edit")+ .hasAttribute("disabled", "", "the edit button is disabled");+ assert+ .dom(".d-table__overview-link")+ .doesNotExist("the name is not a link");+ });++ // Editability follows the serialized `system` flag rather than a hardcoded id+ // list, so a system flag missing from SYSTEM_FLAG_IDS stays locked.+ test("system flag absent from SYSTEM_FLAG_IDS is not editable", async function (assert) {+ this.flag = createFlag({ id: 11, name_key: "unlisted", system: true });++ await render(+ <template>+ <DMenus />+ <table><tbody><tr>+ <AdminFlagItemReorderable @flag={{this.flag}} />+ </tr></tbody></table>+ </template>+ );++ assert+ .dom(".admin-flag-item__edit")+ .hasAttribute("disabled", "", "the edit button is disabled");+ assert+ .dom(".d-table__overview-link")+ .doesNotExist("the name is not a link");+ });+});diff --git a/frontend/discourse/tests/integration/components/dashboard/configure-menu-reorderable-test.gjs b/frontend/discourse/tests/integration/components/dashboard/configure-menu-reorderable-test.gjsnew file mode 100644index 00000000000..2a4308a7d87--- /dev/null+++ b/frontend/discourse/tests/integration/components/dashboard/configure-menu-reorderable-test.gjs@@ -0,0 +1,859 @@+import { tracked } from "@glimmer/tracking";+import { getOwner } from "@ember/owner";+import { click, find, findAll, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import ConfigureMenuReorderable from "discourse/admin/components/dashboard/configure-menu-reorderable";+import DMenus from "discourse/float-kit/components/d-menus";+import { forceMobile } from "discourse/lib/mobile";+import {+ disableClearA11yAnnouncementsInTests,+ enableClearA11yAnnouncementsInTests,+} from "discourse/services/a11y";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import {+ centerOf,+ dragEvent,+ simulateDrag,+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";+import {+ moveItemSelector,+ moveVia,+ moveViaChord,+ openMoveMenu,+} from "discourse/tests/helpers/ui-kit/reorderable-list-helper";++const REORDER_TEST_PREFIX = "Dashboard section reordering";++const FOUR_SECTIONS = [+ { id: "highlights", visible: true },+ { id: "reports", visible: true },+ { id: "traffic", visible: false },+ { id: "engagement", visible: true },+];++function rowSelector(id) {+ return `[data-reorderable-key="${id}"]`;+}++// A drag starts on the grip rather than anywhere on the row, so a press meant to+// scroll still scrolls and the row's own text stays selectable. The grip is what+// carries the registration, so that is where the events go.+function gripSelector(id) {+ return `${rowSelector(id)} .d-reorderable-list__handle`;+}++async function dragSection(sourceId, targetId, position) {+ const source = rowSelector(sourceId);+ const target = rowSelector(targetId);++ const targetRect = find(target).getBoundingClientRect();+ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ sourceCoordinates: centerOf(gripSelector(sourceId)),+ targetCoordinates: {+ clientY:+ position === "above" ? targetRect.top + 1 : targetRect.bottom - 1,+ },+ });+}++function isTransparent(color) {+ return color === "transparent" || /rgba\(0, 0, 0, 0\)/.test(color);+}++/**+ * The y-range of whichever row edge is currently painted as the drop indicator.+ *+ * Read from the computed border rather than from a class, because the point is+ * where the line physically lands, not which row was asked to draw it.+ *+ * @returns {{top: number, bottom: number}|null} The band, or `null` if none.+ */+function indicatorBand() {+ for (const row of findAll(".db-configure__row")) {+ const style = getComputedStyle(row);+ const rect = row.getBoundingClientRect();++ if (!isTransparent(style.borderTopColor)) {+ return {+ top: rect.top,+ bottom: rect.top + parseFloat(style.borderTopWidth),+ };+ }+ if (!isTransparent(style.borderBottomColor)) {+ return {+ top: rect.bottom - parseFloat(style.borderBottomWidth),+ bottom: rect.bottom,+ };+ }+ }+ return null;+}++/** Opens a drag and holds it over a target, without dropping. */+async function hoverOver(sourceId, targetId, position) {+ const target = rowSelector(targetId);+ const dataTransfer = new DataTransfer();+ const targetRect = find(target).getBoundingClientRect();+ const coordinates = {+ clientX: targetRect.left + targetRect.width / 2,+ clientY: position === "above" ? targetRect.top + 1 : targetRect.bottom - 1,+ };++ // Dispatched on the grip, which is where the registration lives: a row that+ // scopes its drag to a handle is not itself draggable, so the browser would+ // never raise `dragstart` on it.+ await dragEvent(gripSelector(sourceId), "dragstart", {+ dataTransfer,+ ...centerOf(gripSelector(sourceId)),+ });+ await dragEvent(target, "dragenter", { dataTransfer, ...coordinates });+ await dragEvent(target, "dragover", { dataTransfer, ...coordinates });++ return () =>+ dragEvent(gripSelector(sourceId), "dragend", {+ dataTransfer,+ ...centerOf(gripSelector(sourceId)),+ });+}++module(+ "Integration | Component | Dashboard | ConfigureMenu | reorderable",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ getOwner(this).lookup(+ "service:site-settings"+ ).enable_new_reordering_controls = true;+ });++ // `settled()` waits out pending timers, and an announcement schedules its own+ // clear, so a message read after `await click(...)` would always be gone.+ hooks.beforeEach(disableClearA11yAnnouncementsInTests);+ hooks.afterEach(enableClearA11yAnnouncementsInTests);++ test(`${REORDER_TEST_PREFIX} renders one row per section`, async function (assert) {+ const sections = FOUR_SECTIONS;+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ assert+ .dom(".d-reorderable-list__handle")+ .exists("the reorderable arm rendered");+ assert.dom(".db-configure__row").exists({ count: 4 });+ assert.dom('[data-reorderable-key="highlights"]').exists();+ assert.dom('[data-reorderable-key="reports"]').exists();+ assert.dom('[data-reorderable-key="traffic"]').exists();+ assert.dom('[data-reorderable-key="engagement"]').exists();+ });++ test(`${REORDER_TEST_PREFIX} toggle click fires @onToggleVisibility with the section id`, async function (assert) {+ const sections = FOUR_SECTIONS;+ const calls = [];+ const onToggle = (id) => calls.push(id);+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{onToggle}}+ @sections={{sections}}+ />+ </template>+ );++ await click(+ '[data-reorderable-key="highlights"] .d-toggle-switch__checkbox'+ );+ assert.deepEqual(calls, ["highlights"]);+ });++ test(`${REORDER_TEST_PREFIX} reorders in both directions`, async function (assert) {+ const sections = FOUR_SECTIONS;+ const calls = [];+ const onReorder = (from, to) => calls.push([from, to]);+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{onReorder}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ await dragSection("reports", "highlights", "above");+ await dragSection("highlights", "engagement", "below");++ assert.deepEqual(+ calls,+ [+ [1, 0],+ [0, 3],+ ],+ "drops above and below resolve from source and target rows without dragstart state"+ );+ });++ test(`${REORDER_TEST_PREFIX} wires every row as a shared source and target`, async function (assert) {+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{FOUR_SECTIONS}}+ />+ </template>+ );++ assert+ .dom(".db-configure__row[data-drop-target]")+ .exists(+ { count: FOUR_SECTIONS.length },+ "every configure row is a drop target"+ );+ assert+ .dom(".db-configure__row[data-drag-source]")+ .exists(+ { count: FOUR_SECTIONS.length },+ "every configure row carries the drag registration, so a drag shows the row"+ );+ assert+ .dom('.db-configure__row .d-reorderable-list__handle[draggable="true"]')+ .exists(+ { count: FOUR_SECTIONS.length },+ "and its grip is where the drag begins"+ );+ });++ test(`${REORDER_TEST_PREFIX} uses the shared drag state classes`, async function (assert) {+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{FOUR_SECTIONS}}+ />+ </template>+ );++ const source = rowSelector("reports");+ const target = rowSelector("traffic");+ const dataTransfer = new DataTransfer();+ const sourceGrip = gripSelector("reports");+ const sourceCoordinates = centerOf(sourceGrip);+ const targetRect = find(target).getBoundingClientRect();+ const targetCoordinates = {+ clientX: targetRect.left + targetRect.width / 2,+ clientY: targetRect.top + 1,+ };++ await dragEvent(sourceGrip, "dragstart", {+ dataTransfer,+ ...sourceCoordinates,+ });+ await dragEvent(target, "dragenter", {+ dataTransfer,+ ...targetCoordinates,+ });+ await dragEvent(target, "dragover", {+ dataTransfer,+ offsetY: 1,+ ...targetCoordinates,+ });++ assert+ .dom(source)+ .hasClass("--dragging", "the source uses the shared dragging class");+ assert+ .dom(target)+ .hasClass("--drag-above", "the target uses the shared above indicator");++ await dragEvent(sourceGrip, "dragend", {+ dataTransfer,+ ...sourceCoordinates,+ });+ });++ test(`${REORDER_TEST_PREFIX} leaves no indicator after an abandoned drag`, async function (assert) {+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{FOUR_SECTIONS}}+ />+ </template>+ );++ const source = rowSelector("reports");+ const target = rowSelector("traffic");+ const dataTransfer = new DataTransfer();+ const sourceGrip = gripSelector("reports");+ const sourceCoordinates = centerOf(sourceGrip);+ const targetRect = find(target).getBoundingClientRect();+ const targetCoordinates = {+ clientX: targetRect.left + targetRect.width / 2,+ clientY: targetRect.top + 1,+ };++ await dragEvent(sourceGrip, "dragstart", {+ dataTransfer,+ ...sourceCoordinates,+ });+ await dragEvent(target, "dragenter", {+ dataTransfer,+ ...targetCoordinates,+ });+ await dragEvent(target, "dragover", {+ dataTransfer,+ offsetY: 1,+ ...targetCoordinates,+ });+ await dragEvent(sourceGrip, "dragend", {+ dataTransfer,+ ...sourceCoordinates,+ });++ assert+ .dom(source)+ .doesNotHaveClass(+ "--dragging",+ "an abandoned drag clears the source indicator"+ )+ .doesNotHaveClass(+ "dragging",+ "an abandoned drag leaves no legacy source indicator"+ );+ assert+ .dom(target)+ .doesNotHaveClass(+ "drag-above",+ "an abandoned drag leaves no legacy above indicator"+ )+ .doesNotHaveClass(+ "drag-below",+ "an abandoned drag leaves no legacy below indicator"+ )+ .doesNotHaveClass(+ "--drag-above",+ "an abandoned drag clears the target's above indicator"+ )+ .doesNotHaveClass(+ "--drag-below",+ "an abandoned drag clears the target's below indicator"+ );+ });++ test(`${REORDER_TEST_PREFIX} renders one handle per row on desktop`, async function (assert) {+ const sections = FOUR_SECTIONS;+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ assert.dom(".d-reorderable-list__handle").exists({ count: 4 });++ await openMoveMenu("reports");+ assert+ .dom(".d-reorderable-list__move-item")+ .exists(+ { count: 4 },+ "desktop keeps a pointer path to reorder, not only the drag"+ );+ });++ test(`${REORDER_TEST_PREFIX} keeps the moved row's handle focused once it has moved`, async function (assert) {+ // A live list, unlike the sibling tests: the row has to actually move for+ // this to say anything about what happens to focus when it does.+ const state = new (class {+ @tracked sections = [...FOUR_SECTIONS];+ })();+ const onReorder = (from, to) => {+ const next = [...state.sections];+ const [moved] = next.splice(from, 1);+ next.splice(to, 0, moved);+ state.sections = next;+ };+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{onReorder}}+ @onToggleVisibility={{noop}}+ @sections={{state.sections}}+ />+ </template>+ );++ await moveVia("highlights", "down");++ assert.deepEqual(+ state.sections.map((section) => section.id),+ ["reports", "highlights", "traffic", "engagement"],+ "the row moved, so focus has something to survive"+ );+ // Without this a keyboard user is dropped to the top of the document after+ // one move and cannot make a second, which defeats the keyboard path.+ assert.strictEqual(+ document.activeElement,+ find(gripSelector("highlights")),+ "focus follows the row rather than falling back to the body"+ );+ });++ test(`${REORDER_TEST_PREFIX} desktop arrow buttons fire @onReorder`, async function (assert) {+ const sections = FOUR_SECTIONS;+ const calls = [];+ const onReorder = (from, to) => calls.push([from, to]);+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{onReorder}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ await moveVia("reports", "up");+ assert.deepEqual(+ calls.at(-1),+ [1, 0],+ "the up arrow moves the row earlier"+ );++ await moveVia("highlights", "down");+ assert.deepEqual(+ calls.at(-1),+ [0, 1],+ "the down arrow moves the row later"+ );+ });++ test(`${REORDER_TEST_PREFIX} the Alt chord fires @onReorder`, async function (assert) {+ const sections = FOUR_SECTIONS;+ const calls = [];+ const onReorder = (from, to) => calls.push([from, to]);+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{onReorder}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ await moveViaChord("reports", "up");+ assert.deepEqual(+ calls.at(-1),+ [1, 0],+ "the accelerator moves the row without opening the menu"+ );++ await moveViaChord("highlights", "bottom");+ assert.deepEqual(calls.at(-1), [0, 3], "and sends it to the far end");+ });++ test(`${REORDER_TEST_PREFIX} adjacent rows leave no dead space between drop zones`, async function (assert) {+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{FOUR_SECTIONS}}+ />+ </template>+ );++ // Each row splits into its own above/below halves at its midpoint, so the+ // zones only meet end to end if the row boxes themselves touch. Container+ // spacing (a flex `gap`) is owned by the list, not by either row, so a+ // pointer inside it reaches no drop target at all.+ const rows = findAll(".db-configure__row");+ for (let i = 1; i < rows.length; i++) {+ const previous = rows[i - 1].getBoundingClientRect();+ const current = rows[i].getBoundingClientRect();++ // Compared exactly, not rounded: a sub-pixel seam is still a band of+ // pixels that belongs to no row, and rounding both sides would hide it.+ assert.strictEqual(+ current.top,+ previous.bottom,+ `row ${i} starts exactly where row ${i - 1} ends, so no pointer position between them falls outside both`+ );+ }+ });++ test(`${REORDER_TEST_PREFIX} both sides of a boundary draw one shared indicator line`, async function (assert) {+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{FOUR_SECTIONS}}+ />+ </template>+ );++ // The same boundary reached from either side. Both resolve to the same+ // insertion point, so the line has to stay put rather than shifting by its+ // own width as the pointer crosses the midpoint.+ const endBelow = await hoverOver("traffic", "highlights", "below");+ const below = indicatorBand();+ await endBelow();++ const endAbove = await hoverOver("traffic", "reports", "above");+ const above = indicatorBand();+ await endAbove();++ assert.notStrictEqual(+ below,+ null,+ "hovering below the first row paints an indicator"+ );+ assert.notStrictEqual(+ above,+ null,+ "hovering above the second row paints an indicator"+ );+ assert.deepEqual(+ above,+ below,+ "below row 1 and above row 2 are the same insertion point, so they paint the same pixels"+ );+ });++ test(`${REORDER_TEST_PREFIX} the indicator colour follows its own custom property`, async function (assert) {+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <div style="--d-drag-indicator-color: rgb(1, 2, 3)">+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{FOUR_SECTIONS}}+ />+ </div>+ </template>+ );++ const end = await hoverOver("traffic", "highlights", "below");+ const painted = getComputedStyle(+ find(rowSelector("highlights"))+ ).borderBottomColor;+ await end();++ assert.strictEqual(+ painted,+ "rgb(1, 2, 3)",+ "an ancestor can retune drag feedback without touching any other accent border"+ );+ });++ test(`${REORDER_TEST_PREFIX} the arrow path announces where the row landed`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ const sections = FOUR_SECTIONS;+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ await moveVia("reports", "up");+ assert.strictEqual(+ a11y.politeMessage,+ "Moved Reports to position 1 of 4",+ "the announcement names the row and its resulting position"+ );++ await moveVia("highlights", "down");+ assert.strictEqual(+ a11y.politeMessage,+ "Moved Highlights to position 2 of 4",+ "moving down announces the row's new position, not the direction"+ );+ });++ test(`${REORDER_TEST_PREFIX} the drag path announces through the same call as the arrows`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ const sections = FOUR_SECTIONS;+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ await dragSection("engagement", "highlights", "above");+ assert.strictEqual(+ a11y.politeMessage,+ "Moved Engagement to position 1 of 4",+ "a completed drag announces exactly like the equivalent arrow press"+ );+ });++ test(`${REORDER_TEST_PREFIX} a reorder that moves nothing announces nothing`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ const sections = FOUR_SECTIONS;+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ const before = a11y.politeMessage;++ await dragSection("reports", "reports", "above");+ assert.strictEqual(+ a11y.politeMessage,+ before,+ "dropping a row onto itself is not a reorder, so nothing is announced"+ );++ // Below the row directly above it resolves to the index it already holds,+ // so this is a no-op that the self-drop guard alone does not catch.+ await dragSection("reports", "highlights", "below");+ assert.strictEqual(+ a11y.politeMessage,+ before,+ "a drop that resolves to the row's current index announces nothing"+ );+ });++ test(`${REORDER_TEST_PREFIX} desktop keyboard path reaches every handle and offers only reachable destinations`, async function (assert) {+ const sections = FOUR_SECTIONS;+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ assert+ .dom(".d-reorderable-list__handle")+ .exists({ count: 4 }, "every section's handle is reachable");+ assert+ .dom('.d-reorderable-list__handle[tabindex="-1"]')+ .doesNotExist("and none is held out of the tab sequence");++ await openMoveMenu("highlights");+ assert+ .dom(moveItemSelector("up"))+ .doesNotExist("the first row cannot move up");+ await click(moveItemSelector("down"));++ await openMoveMenu("engagement");+ assert+ .dom(moveItemSelector("down"))+ .doesNotExist("the last row cannot move down");+ await click(moveItemSelector("up"));++ await openMoveMenu("reports");+ assert.dom(moveItemSelector("up")).exists("a middle row can move up");+ });+ }+);++module(+ "Integration | Component | Dashboard | ConfigureMenu | Mobile | reorderable",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ getOwner(this).lookup(+ "service:site-settings"+ ).enable_new_reordering_controls = true;+ forceMobile();+ });++ test(`${REORDER_TEST_PREFIX} renders one handle per row on mobile`, async function (assert) {+ const sections = FOUR_SECTIONS;+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ // Both paths render: a touch screen can drag from the grip and has no+ // keyboard, so neither is a substitute for the other here.+ assert+ .dom(".d-reorderable-list__handle")+ .exists("the reorderable arm rendered");+ assert.dom(".d-reorderable-list__handle").exists({ count: 4 });+ });++ test(`${REORDER_TEST_PREFIX} keeps the row draggable from its grip on mobile`, async function (assert) {+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{FOUR_SECTIONS}}+ />+ </template>+ );++ assert+ .dom(".d-reorderable-list__handle")+ .exists(+ "the grip renders on mobile, so the drag has a target to press"+ );+ assert+ .dom(".db-configure__row")+ .hasAttribute(+ "data-drag-source",+ "",+ "a mobile row carries an active drag-source registration"+ );+ assert+ .dom(".db-configure__row .d-reorderable-list__handle")+ .hasAttribute(+ "draggable",+ "true",+ "and its grip is where a touch press starts the drag"+ );+ });++ test(`${REORDER_TEST_PREFIX} mobile menu moves fire @onReorder`, async function (assert) {+ const sections = FOUR_SECTIONS;+ const calls = [];+ const onReorder = (from, to) => calls.push([from, to]);+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{onReorder}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ await moveVia("reports", "up");+ assert.deepEqual(calls.at(-1), [1, 0]);++ await moveVia("highlights", "down");+ assert.deepEqual(calls.at(-1), [0, 1]);+ });++ test(`${REORDER_TEST_PREFIX} omits unavailable mobile destinations`, async function (assert) {+ const sections = FOUR_SECTIONS;+ const noop = () => {};++ await render(+ <template>+ <DMenus />+ <ConfigureMenuReorderable+ @onReorder={{noop}}+ @onToggleVisibility={{noop}}+ @sections={{sections}}+ />+ </template>+ );++ await openMoveMenu("highlights");+ assert+ .dom(moveItemSelector("up"))+ .doesNotExist("the first row cannot move up");+ await click(moveItemSelector("down"));++ await openMoveMenu("engagement");+ assert+ .dom(moveItemSelector("down"))+ .doesNotExist("the last row cannot move down");+ await click(moveItemSelector("up"));++ await openMoveMenu("reports");+ assert.dom(moveItemSelector("up")).exists("a middle row can move up");+ });+ }+);diff --git a/frontend/discourse/tests/integration/components/modal/compare-groups-reorderable-test.gjs b/frontend/discourse/tests/integration/components/modal/compare-groups-reorderable-test.gjsnew file mode 100644index 00000000000..c954d08e970--- /dev/null+++ b/frontend/discourse/tests/integration/components/modal/compare-groups-reorderable-test.gjs@@ -0,0 +1,215 @@+import { array, hash } from "@ember/helper";+import { getOwner } from "@ember/owner";+import { click, fillIn, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import CompareGroupsReorderable from "discourse/admin/components/modal/compare-groups-reorderable";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";++module(+ "Integration | Component | Modal | CompareGroups | reorderable",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ getOwner(this).lookup(+ "service:site-settings"+ ).enable_new_reordering_controls = true;+ this.site.groups = [+ { id: 0, name: "everyone" },+ { id: 1, name: "admins" },+ { id: 2, name: "moderators" },+ { id: 3, name: "staff" },+ { id: 4, name: "anonymous_users" },+ { id: 5, name: "logged_in_users" },+ { id: 10, name: "support", full_name: "Support" },+ { id: 11, name: "beta_testers", full_name: "Beta testers" },+ ];+ });++ const noop = () => {};++ test("pre-selects the given current tokens", async function (assert) {+ await render(+ <template>+ <CompareGroupsReorderable+ @closeModal={{noop}}+ @inline={{true}}+ @model={{hash+ currentTokens=(array "new_members" "returning" "staff")+ }}+ />+ </template>+ );++ assert+ .dom(".d-reorderable-list__handle")+ .exists("the reorderable arm rendered");+ assert+ .dom(".manageable-row-list__counter")+ .hasText("3 of 10 groups selected");+ assert+ .dom(+ "[data-reorderable-key='new_members'].manageable-row-list__row.--enabled"+ )+ .exists();+ assert+ .dom(+ "[data-reorderable-key='returning'].manageable-row-list__row.--enabled"+ )+ .exists();+ assert+ .dom(+ "[data-reorderable-key='staff'].manageable-row-list__row.--enabled"+ )+ .exists();+ });++ test("excludes the everyone/anonymous/logged-in pseudogroups and the real staff auto-group", async function (assert) {+ await render(+ <template>+ <CompareGroupsReorderable+ @closeModal={{noop}}+ @inline={{true}}+ @model={{hash currentTokens=(array "staff")}}+ />+ </template>+ );++ assert.dom("[data-reorderable-key='group:0']").doesNotExist();+ assert.dom("[data-reorderable-key='group:3']").doesNotExist();+ assert.dom("[data-reorderable-key='group:4']").doesNotExist();+ assert.dom("[data-reorderable-key='group:5']").doesNotExist();+ assert.dom("[data-reorderable-key='group:1']").exists();+ assert.dom("[data-reorderable-key='group:10']").exists();+ });++ test("search filters the disabled rows by title", async function (assert) {+ await render(+ <template>+ <CompareGroupsReorderable+ @closeModal={{noop}}+ @inline={{true}}+ @model={{hash currentTokens=(array "staff")}}+ />+ </template>+ );++ await fillIn(".compare-groups input", "support");++ assert.dom("[data-reorderable-key='group:10']").exists();+ assert.dom("[data-reorderable-key='group:11']").doesNotExist();+ assert.dom("[data-reorderable-key='staff']").exists();+ });++ test("toggling a row on adds it to the selection, and off removes it", async function (assert) {+ await render(+ <template>+ <CompareGroupsReorderable+ @closeModal={{noop}}+ @inline={{true}}+ @model={{hash currentTokens=(array "staff")}}+ />+ </template>+ );++ await click(+ "[data-reorderable-key='group:10'] .d-toggle-switch__checkbox"+ );+ assert+ .dom(".manageable-row-list__counter")+ .hasText("2 of 10 groups selected");++ await click("[data-reorderable-key='staff'] .d-toggle-switch__checkbox");+ assert+ .dom(".manageable-row-list__counter")+ .hasText("1 of 10 groups selected");+ });++ test("prevents disabling the last remaining selected row", async function (assert) {+ await render(+ <template>+ <CompareGroupsReorderable+ @closeModal={{noop}}+ @inline={{true}}+ @model={{hash currentTokens=(array "staff")}}+ />+ </template>+ );++ assert+ .dom("[data-reorderable-key='staff'] .d-toggle-switch__checkbox")+ .isDisabled();+ assert+ .dom(".manageable-row-list__counter")+ .hasText("1 of 10 groups selected");+ assert+ .dom(+ "[data-reorderable-key='staff'].manageable-row-list__row.--enabled"+ )+ .exists();+ });++ test("disables further toggles once the cap of 10 is reached", async function (assert) {+ this.site.groups = Array.from({ length: 12 }, (_, i) => ({+ id: 100 + i,+ name: `group-${i}`,+ }));++ await render(+ <template>+ <CompareGroupsReorderable+ @closeModal={{noop}}+ @inline={{true}}+ @model={{hash+ currentTokens=(array+ "group:100"+ "group:101"+ "group:102"+ "group:103"+ "group:104"+ "group:105"+ "group:106"+ "group:107"+ "group:108"+ "group:109"+ )+ }}+ />+ </template>+ );++ assert+ .dom(".manageable-row-list__counter")+ .hasText("10 of 10 groups selected");+ assert+ .dom("[data-reorderable-key='group:110'] .d-toggle-switch__checkbox")+ .isDisabled();+ });++ test("apply calls onApply with the ordered selection and closes the modal", async function (assert) {+ let appliedTokens;+ let closed = false;++ const onApply = (tokens) => (appliedTokens = tokens);+ const closeModal = () => (closed = true);++ await render(+ <template>+ <CompareGroupsReorderable+ @closeModal={{closeModal}}+ @inline={{true}}+ @model={{hash currentTokens=(array "staff") onApply=onApply}}+ />+ </template>+ );++ await click(+ "[data-reorderable-key='group:10'] .d-toggle-switch__checkbox"+ );+ await click(".compare-groups__apply");++ assert.deepEqual(appliedTokens, ["staff", "group:10"]);+ assert.true(closed);+ });+ }+);diff --git a/frontend/discourse/tests/integration/components/sidebar-section-form-reorderable-test.gjs b/frontend/discourse/tests/integration/components/sidebar-section-form-reorderable-test.gjsnew file mode 100644index 00000000000..0fb7b417648--- /dev/null+++ b/frontend/discourse/tests/integration/components/sidebar-section-form-reorderable-test.gjs@@ -0,0 +1,713 @@+import { getOwner } from "@ember/owner";+import {+ click,+ find,+ findAll,+ render,+ triggerKeyEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import SidebarSectionForm from "discourse/components/modal/sidebar-section-form";+import SectionFormLinksReorderable from "discourse/components/sidebar/section-form-links-reorderable";+import DMenus from "discourse/float-kit/components/d-menus";+import {+ disableClearA11yAnnouncementsInTests,+ enableClearA11yAnnouncementsInTests,+} from "discourse/services/a11y";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import {+ centerOf,+ dragEvent,+ simulateDrag,+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";++const REORDER_TEST = "Sidebar link reordering";++function communitySection() {+ return {+ id: 42,+ title: "Community",+ public: false,+ section_type: "community",+ links: [+ {+ id: 1,+ icon: "link",+ name: "Primary 1",+ value: "/primary-1",+ segment: "primary",+ },+ {+ id: 2,+ icon: "link",+ name: "Primary 2",+ value: "/primary-2",+ segment: "primary",+ },+ {+ id: 3,+ icon: "link",+ name: "Secondary 1",+ value: "/secondary-1",+ segment: "secondary",+ },+ {+ id: 4,+ icon: "link",+ name: "Secondary 2",+ value: "/secondary-2",+ segment: "secondary",+ },+ ],+ };+}++/**+ * A section whose primary list is long enough that deleting one link still+ * leaves two visible, so an arrow move has a neighbour to swap with and a+ * deleted link can sit between them.+ */+function sectionWithThreePrimaryLinks() {+ const section = communitySection();++ section.links.splice(2, 0, {+ id: 5,+ icon: "link",+ name: "Primary 3",+ value: "/primary-3",+ segment: "primary",+ });++ return section;+}++function linkNames(selector) {+ return findAll(`${selector} input[name="link-name"]`).map(+ (input) => input.value+ );+}++function renderedLinks() {+ return {+ primary: linkNames(+ ".sidebar-section-form__links-wrapper:not(.--secondary)"+ ),+ secondary: linkNames(".sidebar-section-form__links-wrapper.--secondary"),+ };+}++function gripSelector(name) {+ return `.draggable[data-link-name="${name}"]`;+}++function rowSelector(name) {+ const row = find(gripSelector(name)).closest(".sidebar-section-form-link");+ return `[data-reorderable-key="${row.dataset.reorderableKey}"]`;+}++function moveItemSelector(target) {+ return `.d-reorderable-list__move-item.--${target}`;+}++/** Opens one link's move menu, leaving it open for inspection. */+async function openLinkMenu(name) {+ await click(`${rowSelector(name)} .d-reorderable-list__handle`);+}++async function moveLink(name, target) {+ await openLinkMenu(name);+ await click(moveItemSelector(target));+}++async function dragLink(sourceName, targetName, position) {+ const source = rowSelector(sourceName);+ const target = rowSelector(targetName);++ const targetRect = find(target).getBoundingClientRect();+ const targetCoordinates = {+ clientY: position === "above" ? targetRect.top + 1 : targetRect.bottom - 1,+ };++ await simulateDrag(source, target, {+ dataTransfer: new DataTransfer(),+ sourceCoordinates: centerOf(gripSelector(sourceName)),+ targetCoordinates,+ });+}++async function renderForm(context) {+ await render(+ <template>+ <DMenus />+ <SidebarSectionForm+ @closeModal={{context.closeModal}}+ @inline={{true}}+ @model={{context.model}}+ />+ </template>+ );+}++module(+ "Integration | Component | Modal | SidebarSectionForm | reorderable",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.owner.register(+ "component:sidebar/section-form-links-reorderable",+ SectionFormLinksReorderable+ );+ getOwner(this).lookup(+ "service:site-settings"+ ).enable_new_reordering_controls = true;+ const section = communitySection();++ this.modalClosed = false;+ this.closeModal = () => (this.modalClosed = true);+ this.currentUser.set("sidebar_sections", [section]);+ this.model = { section };+ });++ // `settled()` waits out pending timers, and an announcement schedules its own+ // clear, so a message read after an awaited drag would always be gone.+ hooks.beforeEach(disableClearA11yAnnouncementsInTests);++ hooks.afterEach(function () {+ enableClearA11yAnnouncementsInTests();+ sinon.restore();+ });++ test(`${REORDER_TEST}: announces a cross-list move at its destination position`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ await renderForm(this);++ assert+ .dom(".d-reorderable-list__handle")+ .exists("the reorderable arm rendered");++ await dragLink("Primary 1", "Secondary 2", "above");++ assert.strictEqual(+ a11y.politeMessage,+ "Moved Primary 1 to More menu, position 2 of 3",+ "the position is counted within the list the link moved into"+ );+ });++ test(`${REORDER_TEST}: announces a within-list reorder`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ await renderForm(this);++ await dragLink("Primary 2", "Primary 1", "above");++ assert.strictEqual(+ a11y.politeMessage,+ "Moved Primary 2 to position 1 of 2",+ "a same-list move announces against that list's own length"+ );+ });++ test(`${REORDER_TEST}: announces nothing when a drop moves no link`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ await renderForm(this);++ const before = a11y.politeMessage;++ await dragLink("Primary 1", "Primary 1", "above");++ assert.strictEqual(+ a11y.politeMessage,+ before,+ "dropping a link onto itself is not a reorder, so nothing is announced"+ );+ });++ test(`${REORDER_TEST}: moves a primary link to the chosen position in the secondary list`, async function (assert) {+ await renderForm(this);++ await dragLink("Primary 1", "Secondary 2", "above");++ assert.deepEqual(+ renderedLinks(),+ {+ primary: ["Primary 2"],+ secondary: ["Secondary 1", "Primary 1", "Secondary 2"],+ },+ "the dragged link is removed from Primary and inserted above its Secondary target"+ );+ });++ test(`${REORDER_TEST}: saves a cross-list move at the chosen secondary position`, async function (assert) {+ let savedLinks;++ pretender.put("/sidebar_sections/42", (request) => {+ savedLinks = JSON.parse(request.requestBody).links.map(+ ({ name, segment }) => ({ name, segment })+ );++ return response({ sidebar_section: communitySection() });+ });++ await renderForm(this);++ await dragLink("Primary 1", "Secondary 2", "above");+ await click("#save-section");++ assert.deepEqual(+ savedLinks,+ [+ { name: "Primary 2", segment: "primary" },+ { name: "Secondary 1", segment: "secondary" },+ { name: "Primary 1", segment: "secondary" },+ { name: "Secondary 2", segment: "secondary" },+ ],+ "the request preserves the dropped position within the destination list"+ );+ assert.true(this.modalClosed, "the successful save closes the modal");+ });++ test(`${REORDER_TEST}: does not duplicate a cross-list link when the drop is repeated`, async function (assert) {+ await renderForm(this);++ await dragLink("Primary 1", "Secondary 2", "above");+ await dragLink("Primary 1", "Secondary 2", "above");++ assert.deepEqual(+ renderedLinks(),+ {+ primary: ["Primary 2"],+ secondary: ["Secondary 1", "Primary 1", "Secondary 2"],+ },+ "the moved link is rendered only once in its destination list"+ );+ });++ test(`${REORDER_TEST}: reorders links within the primary list`, async function (assert) {+ await renderForm(this);++ await dragLink("Primary 2", "Primary 1", "above");++ assert.deepEqual(+ renderedLinks(),+ {+ primary: ["Primary 2", "Primary 1"],+ secondary: ["Secondary 1", "Secondary 2"],+ },+ "the dragged link is inserted above its target without changing lists"+ );+ });++ test(`${REORDER_TEST}: moves a primary link below a secondary target`, async function (assert) {+ await renderForm(this);++ await dragLink("Primary 1", "Secondary 2", "below");++ assert.deepEqual(+ renderedLinks(),+ {+ primary: ["Primary 2"],+ secondary: ["Secondary 1", "Secondary 2", "Primary 1"],+ },+ "the dragged link is removed from Primary and inserted below its Secondary target"+ );+ });++ test(`${REORDER_TEST}: moves a secondary link to the chosen position in the primary list`, async function (assert) {+ await renderForm(this);++ await dragLink("Secondary 2", "Primary 2", "above");++ assert.deepEqual(+ renderedLinks(),+ {+ primary: ["Primary 1", "Secondary 2", "Primary 2"],+ secondary: ["Secondary 1"],+ },+ "the dragged link is removed from Secondary and inserted above its Primary target"+ );+ });++ test(`${REORDER_TEST}: wires every desktop row as a handled source and target`, async function (assert) {+ await renderForm(this);++ assert+ .dom(".sidebar-section-form-link[data-drop-target]")+ .exists({ count: 4 }, "every link row is a drop target");+ assert+ .dom(".sidebar-section-form-link[data-drag-source]")+ .exists(+ { count: 4 },+ "every link row carries the drag registration, so a drag shows the row"+ );+ assert+ .dom('.sidebar-section-form-link .draggable[draggable="true"]')+ .exists({ count: 4 }, "and its grip is where the drag begins");++ const source = rowSelector("Primary 1");+ const target = rowSelector("Primary 2");+ const dataTransfer = new DataTransfer();++ // The row is not draggable, which is both why a press on its body cannot+ // begin a drag and why the name and URL inputs beside the grip stay+ // selectable. Dispatching here anyway proves the row routes nothing.+ assert.dom(source).doesNotHaveAttribute("draggable");+ await dragEvent(source, "dragstart", {+ dataTransfer,+ ...centerOf(source),+ });+ assert+ .dom(source)+ .doesNotHaveClass(+ "--dragging",+ "pressing the row body does not initiate a drag"+ );+ await dragEvent(source, "dragend", {+ dataTransfer,+ ...centerOf(source),+ });++ await dragEvent(gripSelector("Primary 1"), "dragstart", {+ dataTransfer,+ ...centerOf(gripSelector("Primary 1")),+ });+ assert+ .dom(source)+ .hasClass("--dragging", "pressing the grip initiates the row drag");+ await dragEvent(gripSelector("Primary 1"), "dragend", {+ dataTransfer,+ ...centerOf(target),+ });+ });++ test(`${REORDER_TEST}: leaves no indicator after an abandoned drag`, async function (assert) {+ await renderForm(this);++ const source = rowSelector("Primary 1");+ const target = rowSelector("Primary 2");+ const dataTransfer = new DataTransfer();+ const sourceGrip = gripSelector("Primary 1");+ const sourceCoordinates = centerOf(sourceGrip);+ const targetRect = find(target).getBoundingClientRect();+ const targetCoordinates = {+ clientX: targetRect.left + targetRect.width / 2,+ clientY: targetRect.top + 1,+ };++ await dragEvent(sourceGrip, "dragstart", {+ dataTransfer,+ ...sourceCoordinates,+ });+ assert+ .dom(source)+ .hasClass("--dragging", "the source uses the shared dragging class");++ await dragEvent(target, "dragenter", {+ dataTransfer,+ ...targetCoordinates,+ });+ await dragEvent(target, "dragover", {+ dataTransfer,+ ...targetCoordinates,+ });+ assert+ .dom(target)+ .hasClass("--drag-above", "the target uses the shared above indicator");++ await dragEvent(sourceGrip, "dragend", {+ dataTransfer,+ ...sourceCoordinates,+ });++ assert+ .dom(source)+ .doesNotHaveClass(+ "--dragging",+ "an abandoned drag clears the source indicator"+ );+ assert+ .dom(target)+ .doesNotHaveClass(+ "--drag-above",+ "an abandoned drag clears the target's above indicator"+ )+ .doesNotHaveClass(+ "--drag-below",+ "an abandoned drag clears the target's below indicator"+ )+ .doesNotHaveClass(+ "drag-above",+ "an abandoned drag leaves no legacy above indicator"+ )+ .doesNotHaveClass(+ "drag-below",+ "an abandoned drag leaves no legacy below indicator"+ );+ });++ test(`${REORDER_TEST}: refuses a self drop`, async function (assert) {+ await renderForm(this);++ const row = rowSelector("Primary 1");+ const sharedDragIsRegistered =+ find(row).hasAttribute("data-drag-source") &&+ find(row).hasAttribute("data-drop-target");+ const dataTransfer = new DataTransfer();+ const sourceGrip = gripSelector("Primary 1");+ const sourceCoordinates = centerOf(sourceGrip);+ const rowRect = find(row).getBoundingClientRect();+ const targetCoordinates = {+ clientX: rowRect.left + rowRect.width / 2,+ clientY: rowRect.top + 1,+ };++ assert.true(+ sharedDragIsRegistered,+ "the self-drop check runs on a row whose grip is its own source"+ );++ if (sharedDragIsRegistered) {+ await dragEvent(sourceGrip, "dragstart", {+ dataTransfer,+ ...sourceCoordinates,+ });+ await dragEvent(row, "dragenter", {+ dataTransfer,+ ...targetCoordinates,+ });+ await dragEvent(row, "dragover", {+ dataTransfer,+ ...targetCoordinates,+ });++ assert+ .dom(row)+ .doesNotHaveClass(+ "--drag-above",+ "a row does not show a drop indicator for itself"+ )+ .doesNotHaveClass(+ "--drag-below",+ "a row does not resolve itself as a drop position"+ );++ await dragEvent(row, "drop", {+ dataTransfer,+ ...targetCoordinates,+ });+ await dragEvent(sourceGrip, "dragend", {+ dataTransfer,+ ...sourceCoordinates,+ });+ }++ assert.deepEqual(+ renderedLinks(),+ {+ primary: ["Primary 1", "Primary 2"],+ secondary: ["Secondary 1", "Secondary 2"],+ },+ "dropping a link onto itself leaves both lists unchanged"+ );+ });++ test(`${REORDER_TEST}: drags from the grip on mobile too`, async function (assert) {+ // A touch screen has no keyboard, so the arrows are not a substitute here;+ // taking the drag away on mobile left the surface with the arrows alone.+ sinon.stub(this.site, "desktopView").value(false);+ await renderForm(this);++ const row = ".sidebar-section-form-link";+ const grip = `${row} .draggable`;+ const dataTransfer = new DataTransfer();++ assert+ .dom(grip)+ .exists(+ "the grip renders on mobile, so the drag has a target to press"+ );+ assert+ .dom(row)+ .hasAttribute(+ "data-drag-source",+ "",+ "a mobile row carries an active drag-source registration"+ );+ assert+ .dom(grip)+ .hasAttribute(+ "draggable",+ "true",+ "and the grip is what a touch press starts the drag from"+ );++ await dragEvent(grip, "dragstart", {+ dataTransfer,+ ...centerOf(grip),+ });+ assert+ .dom(row)+ .hasClass("--dragging", "a drag pressed on the grip starts on mobile");+ await dragEvent(grip, "dragend", { dataTransfer, ...centerOf(grip) });+ });++ test(`${REORDER_TEST}: moves a link down its own list from the menu`, async function (assert) {+ await renderForm(this);++ await moveLink("Primary 1", "down");++ assert.deepEqual(+ renderedLinks(),+ {+ primary: ["Primary 2", "Primary 1"],+ secondary: ["Secondary 1", "Secondary 2"],+ },+ "the link swaps with the row below it and the other list is untouched"+ );+ });++ test(`${REORDER_TEST}: moves a link up its own list from the menu`, async function (assert) {+ await renderForm(this);++ await moveLink("Secondary 2", "up");++ assert.deepEqual(+ renderedLinks(),+ {+ primary: ["Primary 1", "Primary 2"],+ secondary: ["Secondary 2", "Secondary 1"],+ },+ "a secondary link swaps within Secondary rather than crossing into Primary"+ );+ });++ test(`${REORDER_TEST}: offers only the reachable destinations at each list's boundaries`, async function (assert) {+ await renderForm(this);++ await openLinkMenu("Primary 1");+ assert+ .dom(moveItemSelector("up"))+ .doesNotExist("the first link has nothing above it");+ assert+ .dom(moveItemSelector("down"))+ .exists("a link with a row below it can still move down");+ await triggerKeyEvent(document.activeElement, "keydown", "Escape");++ await openLinkMenu("Primary 2");+ assert+ .dom(moveItemSelector("down"))+ .doesNotExist("the last primary link has nothing below it");+ await triggerKeyEvent(document.activeElement, "keydown", "Escape");++ await openLinkMenu("Secondary 1");+ assert+ .dom(moveItemSelector("up"))+ .doesNotExist("each list boundary is counted within that list");+ });++ test(`${REORDER_TEST}: steps over a link awaiting deletion`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ this.model = { section: sectionWithThreePrimaryLinks() };+ await renderForm(this);++ await click(`${rowSelector("Primary 2")} .delete-link`);+ await moveLink("Primary 1", "down");++ assert.deepEqual(+ renderedLinks().primary,+ ["Primary 3", "Primary 1"],+ "the move swaps with the next visible link, not with the deleted one between them"+ );+ assert.strictEqual(+ a11y.politeMessage,+ "Moved Primary 1 to position 2 of 2",+ "the position is counted within the visible list"+ );+ });++ test(`${REORDER_TEST}: a drag over a link awaiting deletion that changes nothing announces nothing`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ this.model = { section: sectionWithThreePrimaryLinks() };+ await renderForm(this);++ await click(`${rowSelector("Primary 2")} .delete-link`);++ const before = a11y.politeMessage;++ // Below the link shown above it, which is the position it already holds.+ // In the underlying array it reads as a move, because of the deleted link+ // sitting between the two.+ await dragLink("Primary 3", "Primary 1", "below");++ assert.deepEqual(+ renderedLinks().primary,+ ["Primary 1", "Primary 3"],+ "the visible list is the one it already was"+ );+ assert.strictEqual(+ a11y.politeMessage,+ before,+ "so nothing is announced, rather than a position the link never left"+ );+ });++ test(`${REORDER_TEST}: walks a link down the list with repeated presses`, async function (assert) {+ this.model = { section: sectionWithThreePrimaryLinks() };+ await renderForm(this);++ await moveLink("Primary 1", "down");++ // Through whatever holds focus, which is what a keyboard user presses a+ // second time. Selecting by name instead would find the right control no+ // matter where focus went, and so would pass even if the keyboard path+ // were unusable: on an unkeyed list the row keeps its DOM node and takes+ // on a different link, so the second press would move the wrong one back.+ await triggerKeyEvent(document.activeElement, "keydown", "ArrowDown", {+ altKey: true,+ });++ assert.deepEqual(+ renderedLinks().primary,+ ["Primary 2", "Primary 3", "Primary 1"],+ "the link keeps moving instead of swapping back and forth"+ );+ });++ test(`${REORDER_TEST}: announces a drag by the position the user can see`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ this.model = { section: sectionWithThreePrimaryLinks() };+ await renderForm(this);++ await click(`${rowSelector("Primary 1")} .delete-link`);+ await dragLink("Primary 3", "Primary 2", "above");++ assert.deepEqual(+ renderedLinks().primary,+ ["Primary 3", "Primary 2"],+ "the drag reorders the visible list"+ );+ // The underlying array still holds the deleted link, so counting there+ // would announce a position and a total the user cannot see.+ assert.strictEqual(+ a11y.politeMessage,+ "Moved Primary 3 to position 1 of 2",+ "and the announcement counts only the links still on screen"+ );+ });++ test(`${REORDER_TEST}: announces where a menu move landed`, async function (assert) {+ const a11y = getOwner(this).lookup("service:a11y");+ await renderForm(this);++ await moveLink("Secondary 2", "up");++ assert.strictEqual(+ a11y.politeMessage,+ "Moved Secondary 2 to position 1 of 2",+ "the announcement counts against the list the link moved within"+ );+ });+ }+);diff --git a/frontend/discourse/tests/integration/components/simple-list-reorderable-test.gjs b/frontend/discourse/tests/integration/components/simple-list-reorderable-test.gjsnew file mode 100644index 00000000000..622a65e1016--- /dev/null+++ b/frontend/discourse/tests/integration/components/simple-list-reorderable-test.gjs@@ -0,0 +1,232 @@+import { tracked } from "@glimmer/tracking";+import { getOwner } from "@ember/owner";+import {+ blur,+ click,+ fillIn,+ render,+ settled,+ triggerKeyEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import SimpleList from "discourse/admin/components/simple-list";+import DMenus from "discourse/float-kit/components/d-menus";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";++module("Integration | Component | SimpleList | reorderable", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ getOwner(this).lookup(+ "service:site-settings"+ ).enable_new_reordering_controls = true;+ });++ test("adding a value", async function (assert) {+ const values = "vinkas\nosama";+ await render(+ <template><DMenus /><SimpleList @values={{values}} /></template>+ );++ assert+ .dom(".d-reorderable-list__handle")+ .exists("the reorderable arm rendered");+ assert.dom(".values .value").exists({ count: 2 });+ assert.dom(".add-value-btn").isDisabled("disabled when input is empty");++ await fillIn(".add-value-input", "penar");+ await click(".add-value-btn");++ assert+ .dom(".values .value")+ .exists({ count: 3 }, "adds the value to the list of values");++ assert+ .dom(".values .value[data-reorderable-key='2'] .value-input")+ .hasValue("penar", "sets the correct value for added item");++ await fillIn(".add-value-input", "eviltrout");+ await triggerKeyEvent(".add-value-input", "keydown", "Enter");++ assert+ .dom(".values .value")+ .exists({ count: 4 }, "adds the value when pressing Enter");+ });++ test("adding a value when list is predefined", async function (assert) {+ const values = "vinkas\nosama";+ const choices = ["vinkas", "osama", "kris", "jeff"];++ await render(+ <template>+ <DMenus />+ <SimpleList+ @allowAny={{false}}+ @choices={{choices}}+ @values={{values}}+ />+ </template>+ );++ await click(".add-value-input summary");+ assert.dom(".select-kit-row").exists({ count: 2 });+ await click(".select-kit-row");++ assert+ .dom(".values .value")+ .exists({ count: 3 }, "adds the value to the list of values");+ });++ test("changing a value", async function (assert) {+ const done = assert.async();++ const values = "vinkas\nosama";+ const onChange = (collection) => {+ assert.deepEqual(collection, ["vinkas", "jarek"]);+ done();+ };++ await render(+ <template>+ <DMenus />+ <SimpleList @onChange={{onChange}} @values={{values}} />+ </template>+ );++ await fillIn(+ ".values .value[data-reorderable-key='1'] .value-input",+ "jarek"+ );+ await blur(".values .value[data-reorderable-key='1'] .value-input");++ assert+ .dom(".values .value[data-reorderable-key='1'] .value-input")+ .hasValue("jarek");+ });++ test("removing a value", async function (assert) {+ const values = "vinkas\nosama";+ await render(+ <template><DMenus /><SimpleList @values={{values}} /></template>+ );++ await click(+ ".values .value[data-reorderable-key='0'] .d-reorderable-list__remove"+ );++ assert+ .dom(".values .value")+ .exists({ count: 1 }, "removes the value from the list of values");++ assert+ .dom(".values .value[data-reorderable-key='0'] .value-input")+ .hasValue("osama", "removes the correct value");+ });++ test("delimiter support", async function (assert) {+ await render(+ <template>+ <DMenus />+ <SimpleList @inputDelimiter="|" @values="vinkas|osama" />+ </template>+ );++ await fillIn(".add-value-input", "eviltrout");+ await click(".add-value-btn");++ assert+ .dom(".values .value")+ .exists({ count: 3 }, "adds the value to the list of values");++ assert+ .dom(".values .value[data-reorderable-key='2'] .value-input")+ .hasValue("eviltrout", "adds the correct value");+ });++ test("updates when values change", async function (assert) {+ const state = new (class {+ @tracked values = "vinkas|osama";+ })();++ await render(+ <template>+ <DMenus />+ <SimpleList @inputDelimiter="|" @values={{state.values}} />+ </template>+ );++ assert+ .dom(".values .value[data-reorderable-key='0'] .value-input")+ .hasValue("vinkas");++ state.values = "kris|jeff";+ await settled();++ assert+ .dom(".values .value[data-reorderable-key='0'] .value-input")+ .hasValue("kris");+ });++ test("a closed set offers no editable field", async function (assert) {+ const choices = ["latest", "new", "unread"];+ const values = "latest|new";++ await render(+ <template>+ <DMenus />+ <SimpleList+ @allowAny={{false}}+ @choices={{choices}}+ @inputDelimiter="|"+ @values={{values}}+ />+ </template>+ );++ assert+ .dom(".values input.value-input")+ .doesNotExist(+ "a value drawn from a fixed set has nothing to type into it"+ );+ assert+ .dom(".values .value-input.--readonly")+ .exists({ count: 2 }, "each value still reads as its own row");+ });++ test("a free-text list keeps its editable field", async function (assert) {+ const values = "vinkas|osama";++ await render(+ <template>+ <DMenus /><SimpleList @inputDelimiter="|" @values={{values}} />+ </template>+ );++ assert+ .dom(".values input.value-input")+ .exists(+ { count: 2 },+ "an open list is still edited in place, not only added to"+ );+ });++ test("removing a value names what it removes", async function (assert) {+ const values = "vinkas|osama";++ await render(+ <template>+ <DMenus /><SimpleList @inputDelimiter="|" @values={{values}} />+ </template>+ );++ assert+ .dom(+ ".values .value[data-reorderable-key='0'] .d-reorderable-list__remove"+ )+ .hasAria(+ "label",+ "Remove vinkas",+ "the standard control says which value it drops"+ );+ });+});diff --git a/frontend/discourse/tests/integration/components/value-list-reorderable-test.gjs b/frontend/discourse/tests/integration/components/value-list-reorderable-test.gjsnew file mode 100644index 00000000000..f4d2cf605b0--- /dev/null+++ b/frontend/discourse/tests/integration/components/value-list-reorderable-test.gjs@@ -0,0 +1,165 @@+import { getOwner } from "@ember/owner";+import { blur, click, fillIn, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import ValueList from "discourse/admin/components/value-list";+import DMenus from "discourse/float-kit/components/d-menus";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import selectKit from "discourse/tests/helpers/select-kit-helper";++module("Integration | Component | ValueList | reorderable", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ getOwner(this).lookup(+ "service:site-settings"+ ).enable_new_reordering_controls = true;+ });++ test("adding a value", async function (assert) {+ this.set("values", "vinkas\nosama");++ await render(+ <template><DMenus /><ValueList @values={{this.values}} /></template>+ );++ assert+ .dom(".d-reorderable-list__handle")+ .exists("the reorderable arm rendered");++ await selectKit().expand();+ await selectKit().fillInFilter("eviltrout");+ await selectKit().keyboard("Enter");++ assert+ .dom(".values .value")+ .exists({ count: 3 }, "adds the value to the list of values");++ assert.strictEqual(+ this.values,+ "vinkas\nosama\neviltrout",+ "it adds the value to the list of values"+ );+ });++ test("changing a value", async function (assert) {+ this.set("values", "vinkas\nosama");++ await render(+ <template><DMenus /><ValueList @values={{this.values}} /></template>+ );++ await fillIn(+ ".values .value[data-reorderable-key='1'] .value-input",+ "jarek"+ );+ await blur(".values .value[data-reorderable-key='1'] .value-input");++ assert+ .dom(".values .value[data-reorderable-key='1'] .value-input")+ .hasValue("jarek");+ assert.deepEqual(this.values, "vinkas\njarek", "updates the value list");+ });++ test("removing a value", async function (assert) {+ this.set("values", "vinkas\nosama");++ await render(+ <template><DMenus /><ValueList @values={{this.values}} /></template>+ );++ await click(+ ".values .value[data-reorderable-key='0'] .d-reorderable-list__remove"+ );++ assert+ .dom(".values .value")+ .exists({ count: 1 }, "removes the value from the list of values");++ assert.strictEqual(this.values, "osama", "it removes the expected value");++ await selectKit().expand();++ assert+ .dom(".select-kit-collection li.select-kit-row span.name")+ .hasText("vinkas", "it adds the removed value to choices");+ });++ test("selecting a value", async function (assert) {+ this.setProperties({+ values: "vinkas\nosama",+ choices: ["maja", "michael"],+ });++ await render(+ <template>+ <DMenus />+ <ValueList @choices={{this.choices}} @values={{this.values}} />+ </template>+ );++ await selectKit().expand();+ await selectKit().selectRowByValue("maja");++ assert+ .dom(".values .value")+ .exists({ count: 3 }, "adds the value to the list of values");++ assert.strictEqual(+ this.values,+ "vinkas\nosama\nmaja",+ "it adds the value to the list of values"+ );+ });++ test("array support", async function (assert) {+ this.set("values", ["vinkas", "osama"]);++ await render(+ <template>+ <DMenus />+ <ValueList @inputType="array" @values={{this.values}} />+ </template>+ );++ this.set("values", ["vinkas", "osama"]);++ await selectKit().expand();+ await selectKit().fillInFilter("eviltrout");+ await selectKit().selectRowByValue("eviltrout");++ assert+ .dom(".values .value")+ .exists({ count: 3 }, "adds the value to the list of values");++ assert.deepEqual(+ this.values,+ ["vinkas", "osama", "eviltrout"],+ "it adds the value to the list of values"+ );+ });++ test("delimiter support", async function (assert) {+ this.set("values", "vinkas|osama");++ await render(+ <template>+ <DMenus />+ <ValueList @inputDelimiter="|" @values={{this.values}} />+ </template>+ );++ await selectKit().expand();+ await selectKit().fillInFilter("eviltrout");+ await selectKit().keyboard("Enter");++ assert+ .dom(".values .value")+ .exists({ count: 3 }, "adds the value to the list of values");++ assert.strictEqual(+ this.values,+ "vinkas|osama|eviltrout",+ "it adds the value to the list of values"+ );+ });+});diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-edit-form-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-edit-form-test.gjsindex 7b17d6d9dc5..0a97b4eec6f 100644--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-edit-form-test.gjs+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-edit-form-test.gjs@@ -1,7 +1,12 @@import { tracked } from "@glimmer/tracking";+import { getOwner } from "@ember/owner";import { click, fillIn, render } 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 pretender, { response } from "discourse/tests/helpers/create-pretender";+import { moveVia } from "discourse/tests/helpers/ui-kit/reorderable-list-helper";import WorkflowVariableForm from "discourse/plugins/discourse-workflows/admin/components/workflows/variable-edit-form";class TestWorkflow {@@ -119,4 +124,59 @@ module("Integration | Component | WorkflowVariableForm", function (hooks) {.dom(".form-kit__errors").exists("shows a validation error for the malformed key");});++ // TODO (ui-kit-reorderable-list-cleanup) fold this over the choices tests+ // above once `enable_new_reordering_controls` ships.+ test("with the new reordering controls, a moved choice is saved in its new place", async function (assert) {+ getOwner(this).lookup(+ "service:site-settings"+ ).enable_new_reordering_controls = true;+ sinon.stub(getOwner(this).lookup("service:router"), "transitionTo");++ const variable = {+ id: 10,+ key: "priority",+ variable_type: "enum",+ type_options: { choices: ["low", "medium", "high"] },+ };+ const workflow = new TestWorkflow({ id: 1, variables: [variable] });++ let savedChoices;+ pretender.put(+ "/admin/plugins/discourse-workflows/workflows/1/variables/10.json",+ (request) => {+ savedChoices = new URLSearchParams(request.requestBody).getAll(+ "type_options[choices][]"+ );+ return response({+ variable,+ workflow: {+ version_id: "draft-uuid",+ active_version_id: "published-uuid",+ has_unpublished_changes: true,+ },+ });+ }+ );++ await render(+ <template>+ <DMenus />+ <WorkflowVariableForm @variableId="10" @workflow={{workflow}} />+ </template>+ );++ assert+ .dom(".simple-list .d-reorderable-list__handle")+ .exists({ count: 3 }, "each choice has the shared reorder handle");++ await moveVia("2", "top", ".simple-list");+ await click(".form-kit__button");++ assert.deepEqual(+ savedChoices,+ ["high", "low", "medium"],+ "the choices are saved in the order shown"+ );+ });});diff --git a/spec/requests/admin/config/flags_controller_spec.rb b/spec/requests/admin/config/flags_controller_spec.rbnew file mode 100644index 00000000000..f8ef44b2f9a--- /dev/null+++ b/spec/requests/admin/config/flags_controller_spec.rb@@ -0,0 +1,88 @@+# frozen_string_literal: true++RSpec.describe Admin::Config::FlagsController do+ fab!(:admin)+ fab!(:moderator)+ fab!(:user)++ describe "#move" do+ let(:flag) { Flag.find_by(name_key: "notify_moderators") }++ context "when logged in as an admin" do+ before { sign_in(admin) }++ context "with a position in range" do+ let!(:original_positions) { Flag.unscoped.pluck(:id, :position).to_h }++ # DO NOT REMOVE: saving a flag reloads the cached flag types after+ # commit, so the moved order will leak to other examples otherwise.+ after do+ original_positions.each { |id, position| Flag.unscoped.where(id:).update_all(position:) }+ Flag.reset_flag_settings!+ end++ it "moves the flag and returns 204" do+ put "/admin/config/flags/#{flag.id}/move.json", params: { position: 1 }++ expect(response.status).to eq(204)+ expect(response.body).to be_empty+ expect(Flag.order(:position).map(&:name)).to eq(+ %w[notify_user off_topic notify_moderators inappropriate spam illegal],+ )+ end+ end++ it "returns 404 when the flag does not exist" do+ put "/admin/config/flags/0/move.json", params: { position: 1 }++ expect(response.status).to eq(404)+ end++ it "returns 403 when the flag is notify_user" do+ put "/admin/config/flags/#{Flag.find_by(name_key: "notify_user").id}/move.json",+ params: {+ position: 1,+ }++ expect(response.status).to eq(403)+ end++ it "returns 422 with an explanatory error when the position is out of range" do+ put "/admin/config/flags/#{flag.id}/move.json", params: { position: 5 }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to contain_exactly(I18n.t("flags.errors.wrong_move"))+ end++ it "returns 400 when the position is missing or negative" do+ put "/admin/config/flags/#{flag.id}/move.json"+ expect(response.status).to eq(400)++ put "/admin/config/flags/#{flag.id}/move.json", params: { position: -1 }+ expect(response.status).to eq(400)+ end+ end++ it "returns 403 for a moderator" do+ sign_in(moderator)++ put "/admin/config/flags/#{flag.id}/move.json", params: { position: 1 }++ expect(response.status).to eq(403)+ end++ it "returns 404 for a regular user" do+ sign_in(user)++ put "/admin/config/flags/#{flag.id}/move.json", params: { position: 1 }++ expect(response.status).to eq(404)+ end++ it "returns 404 for an anonymous user" do+ put "/admin/config/flags/#{flag.id}/move.json", params: { position: 1 }++ expect(response.status).to eq(404)+ end+ end+enddiff --git a/spec/services/flags/move_flag_spec.rb b/spec/services/flags/move_flag_spec.rbnew file mode 100644index 00000000000..98942a7a4d8--- /dev/null+++ b/spec/services/flags/move_flag_spec.rb@@ -0,0 +1,108 @@+# frozen_string_literal: true++RSpec.describe Flags::MoveFlag do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:flag_id) }+ it { is_expected.to allow_values(0, 5).for(:position) }+ it { is_expected.not_to allow_values(-1, nil).for(:position) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:current_user, :admin)++ let(:params) { { flag_id:, position: } }+ let(:dependencies) { { guardian: current_user.guardian } }+ let(:flag_id) { flag.id }+ let(:flag) { Flag.find_by(name_key: "notify_moderators") }+ let(:position) { 1 }++ context "when contract is invalid" do+ let(:position) { -1 }++ it { is_expected.to fail_a_contract }+ end++ context "when flag is not found" do+ let(:flag_id) { 0 }++ it { is_expected.to fail_to_find_a_model(:flag) }+ end++ context "when user is not allowed to perform the action" do+ fab!(:current_user, :user)++ it { is_expected.to fail_a_policy(:invalid_access) }+ end++ context "when flag is notify_user" do+ let(:flag) { Flag.find_by(name_key: "notify_user") }++ it { is_expected.to fail_a_policy(:invalid_access) }+ end++ context "when position is out of range" do+ let(:position) { 5 }++ it { is_expected.to fail_a_policy(:invalid_move) }+ end++ context "when everything's ok" do+ let!(:original_positions) { Flag.unscoped.pluck(:id, :position).to_h }++ # A gap in the position values tells reusing them apart from renumbering.+ before { Flag.where(name_key: "notify_moderators").update_all(position: 10) }++ # DO NOT REMOVE: saving a flag reloads the cached flag types after+ # commit, so the moved order will leak to other examples otherwise.+ after do+ original_positions.each { |id, position| Flag.unscoped.where(id:).update_all(position:) }+ Flag.reset_flag_settings!+ end++ it { is_expected.to run_successfully }++ it "moves the flag up to the requested position" do+ expect { result }.to change { Flag.order(:position).map(&:name) }.from(+ %w[notify_user off_topic inappropriate spam illegal notify_moderators],+ ).to(%w[notify_user off_topic notify_moderators inappropriate spam illegal])+ end++ it "reuses the existing position values" do+ expect { result }.not_to change { Flag.order(:position).map(&:position) }.from(+ [1, 2, 3, 4, 5, 10],+ )+ end++ it "logs the action" do+ expect { result }.to change { UserHistory.count }.by(1)+ expect(UserHistory.last).to have_attributes(+ custom_type: "move_flag",+ details: "flag: notify_moderators\nposition: 1",+ )+ end++ context "when moving to the first position" do+ let(:position) { 0 }++ it "places the flag right after notify_user" do+ expect { result }.to change { Flag.order(:position).map(&:name) }.from(+ %w[notify_user off_topic inappropriate spam illegal notify_moderators],+ ).to(%w[notify_user notify_moderators off_topic inappropriate spam illegal])+ end+ end++ context "when moving down to the last position" do+ let(:flag) { Flag.find_by(name_key: "off_topic") }+ let(:position) { 4 }++ it "moves the flag below every other flag" do+ expect { result }.to change { Flag.order(:position).map(&:name) }.from(+ %w[notify_user off_topic inappropriate spam illegal notify_moderators],+ ).to(%w[notify_user inappropriate spam illegal notify_moderators off_topic])+ end+ end+ end+ end+enddiff --git a/spec/system/admin_badges_spec.rb b/spec/system/admin_badges_spec.rbindex fded8f331f6..bbe92781d1b 100644--- a/spec/system/admin_badges_spec.rb+++ b/spec/system/admin_badges_spec.rb@@ -150,4 +150,27 @@ describe "Admin Badges Page" doexpect(page).to have_current_path("/admin/badges")endend++ context "when enable_new_reordering_controls is enabled" do+ fab!(:custom_grouping) { BadgeGrouping.create!(name: "Custom grouping", position: 10) }++ before { SiteSetting.enable_new_reordering_controls = true }++ it "draws edit and remove only on the groupings that accept them" do+ badges_page.visit_page(Badge::Autobiographer).edit_groupings++ expect(page).to have_css(".badge-grouping-item", minimum: 6)++ system_row = find(".badge-grouping-item", text: "Getting Started")+ custom_row = find(".badge-grouping-item", text: "Custom grouping")++ # A system grouping can be neither renamed nor removed, so it draws neither+ # control rather than drawing them disabled.+ expect(system_row).to have_no_css(".btn .d-icon-pencil")+ expect(system_row).to have_no_css(".d-reorderable-list__remove")++ expect(custom_row).to have_css(".btn .d-icon-pencil")+ expect(custom_row).to have_css(".d-reorderable-list__remove")+ end+ endenddiff --git a/spec/system/admin_dashboard_configure_spec.rb b/spec/system/admin_dashboard_configure_spec.rbindex d83ca2bab43..e26464fd43e 100644--- a/spec/system/admin_dashboard_configure_spec.rb+++ b/spec/system/admin_dashboard_configure_spec.rb@@ -73,6 +73,47 @@ describe "Admin Dashboard Configure menu" doexpect(dashboard).to have_first_section("reports")expect(dashboard.section_ids_in_order.first(2)).to eq(%w[reports highlights])end++ # TODO (ui-kit-reorderable-list-cleanup) fold these over the examples above+ # once the change ships and the arrow buttons are gone.+ context "when enable_new_reordering_controls is enabled" do+ before { SiteSetting.enable_new_reordering_controls = true }++ it "reorders sections via the move menu on mobile", mobile: true do+ dashboard.visit++ dashboard.open_configure_menu.move_section_up_via_list("reports")++ # reorder applies immediately, without closing the menu+ expect(dashboard).to have_first_section("reports")+ expect(dashboard.section_ids_in_order.first(2)).to eq(%w[reports highlights])+ end++ it "shows the drag handle on mobile", mobile: true do+ # The rendering test only proves the handle is in the DOM. A touch screen+ # reaches the menu as a modal rather than a popover, so this asserts it is+ # actually visible there, which is the only thing a finger can act on.+ dashboard.visit+ dashboard.open_configure_menu++ expect(page).to have_css(".d-reorderable-list__handle")+ end++ it "reorders sections with a real browser drag" do+ dashboard.visit+ dashboard.open_configure_menu++ # Asserted before the drag: without it, a run where the two are already+ # in the expected order passes whether or not the drag did anything.+ expect(dashboard.section_ids_in_order.first(2)).to eq(%w[highlights reports])++ dashboard.drag_section("reports", "highlights")++ try_until_success do+ expect(dashboard.section_ids_in_order.first(2)).to eq(%w[reports highlights])+ end+ end+ endendcontext "as a moderator" dodiff --git a/spec/system/admin_dashboard_redesign/reports_section_spec.rb b/spec/system/admin_dashboard_redesign/reports_section_spec.rbindex 1387cc9c647..592f4237683 100644--- a/spec/system/admin_dashboard_redesign/reports_section_spec.rb+++ b/spec/system/admin_dashboard_redesign/reports_section_spec.rb@@ -52,6 +52,89 @@ describe "Admin Dashboard Redesign | Reports section" doexpect(modal).to have_disabled_move_down("core_report:topics")end+ # TODO (ui-kit-reorderable-list-cleanup) fold these over the examples above+ # once the change ships and the arrow buttons are gone.+ context "when enable_new_reordering_controls is enabled" do+ before { SiteSetting.enable_new_reordering_controls = true }++ it "marks the unavailable destinations at the ends of the enabled list on mobile",+ mobile: true do+ AdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)+ AdminDashboardReport.create!(source: "core_report", identifier: "topics", position: 1)++ page.visit("/admin")+ dashboard.open_manage_reports_via_cog+ expect(modal).to have_open++ expect(modal).to have_no_move_up("core_report:signups")+ expect(modal).to have_move_down("core_report:signups")+ expect(modal).to have_move_up("core_report:topics")+ expect(modal).to have_no_move_down("core_report:topics")+ end++ it "lets the admin select a report's text" do+ # A row is a drag source, and a draggable element turns a press-drag into a+ # drag rather than a selection. The grip is what should be draggable, so the+ # title and description stay selectable like any other text.+ #+ # drag_with_pointer, not drag_and_drop: the latter goes through CDP drag+ # interception, which suppresses the ordinary mouse moves a selection is+ # made of. And a real pointer is the only thing that can select at all, as+ # a synthetic drag never touches the browser's selection.+ AdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)+ AdminDashboardReport.create!(source: "core_report", identifier: "topics", position: 1)++ page.visit("/admin")+ dashboard.open_manage_reports_via_cog+ expect(modal).to have_open++ drag_with_pointer(+ from: ".manageable-row-list__row.--enabled .manageable-row-list__title",+ by: {+ x: 60,+ },+ )++ expect(page.evaluate_script("window.getSelection().toString()")).to be_present+ end++ it "reorders reports with a real browser drag" do+ AdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)+ AdminDashboardReport.create!(source: "core_report", identifier: "topics", position: 1)++ page.visit("/admin")+ dashboard.open_manage_reports_via_cog+ expect(modal).to have_open++ modal.drag_report("core_report:topics", "core_report:signups")++ try_until_success do+ expect(modal.enabled_identifiers).to eq(%w[core_report:topics core_report:signups])+ end+ end++ it "keeps report sizes when admins add and reorder reports" do+ Fabricate(:tall_admin_dashboard_report, position: 0)+ Fabricate(:admin_dashboard_report, identifier: "topics", position: 1, cols: 2)++ page.visit("/admin")+ dashboard.open_manage_reports_via_cog+ expect(modal).to have_open+ modal.toggle("core_report:admin_logins")+ modal.reorderable("core_report:topics").move(:top)+ modal.apply+ expect(modal).to have_closed++ page.refresh+ expect(dashboard).to have_cards_in_order(+ %w[core_report:topics core_report:signups core_report:admin_logins],+ )+ expect(dashboard).to have_card_size("core_report:signups", rows: 3, cols: 2)+ expect(dashboard).to have_card_size("core_report:topics", rows: 1, cols: 2)+ expect(dashboard).to have_card_size("core_report:admin_logins", rows: 1, cols: 1)+ end+ end+it "lets admins customize the reports section via the manage-reports modal" doAdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)AdminDashboardReport.create!(source: "core_report", identifier: "topics", position: 1)diff --git a/spec/system/admin_flags_spec.rb b/spec/system/admin_flags_spec.rbindex d9aaee83a4b..1894e7991b0 100644--- a/spec/system/admin_flags_spec.rb+++ b/spec/system/admin_flags_spec.rb@@ -199,4 +199,56 @@ describe "Admin Flags Page" doadmin_flags_page.visit.toggle_flag_menu("off_topic")expect(admin_flags_page).to have_no_item_action("move-up")end++ # TODO (ui-kit-reorderable-list-cleanup) fold these over the reordering in+ # the first example once the change ships.+ context "when enable_new_reordering_controls is enabled" do+ before { SiteSetting.enable_new_reordering_controls = true }++ it "keeps a flag where the admin moved it through the menu" do+ admin_flags_page.visit++ admin_flags_page.move_up_via_list("illegal")+ expect(admin_flags_page).to have_saved_flag("illegal")+ admin_flags_page.move_to_top_via_list("notify_moderators")+ expect(admin_flags_page).to have_saved_flag("notify_moderators")++ page.refresh++ expect(admin_flags_page).to have_flags_in_order(+ "Send @%{username} a message",+ "Something Else",+ "Off-Topic",+ "Inappropriate",+ "Illegal",+ "Spam",+ )+ end++ it "keeps a flag where the admin dragged it" do+ admin_flags_page.visit++ admin_flags_page.drag_flag_above("off_topic", "illegal")+ expect(admin_flags_page).to have_flags_in_order(+ "Send @%{username} a message",+ "Inappropriate",+ "Spam",+ "Off-Topic",+ "Illegal",+ "Something Else",+ )+ expect(admin_flags_page).to have_saved_flag("off_topic")++ page.refresh++ expect(admin_flags_page).to have_flags_in_order(+ "Send @%{username} a message",+ "Inappropriate",+ "Spam",+ "Off-Topic",+ "Illegal",+ "Something Else",+ )+ end+ endenddiff --git a/spec/system/admin_site_setting_value_list_spec.rb b/spec/system/admin_site_setting_value_list_spec.rbindex 0689c296fc6..524f151ab3e 100644--- a/spec/system/admin_site_setting_value_list_spec.rb+++ b/spec/system/admin_site_setting_value_list_spec.rb@@ -34,5 +34,102 @@ describe "Admin Site Setting Value Lists" doexpect(settings_page).to have_visible_reorder_buttons("default_emoji_reactions")endend++ # The reorder control used to be revealed on hover, which a touch screen has+ # no way to trigger, so these settings were unreorderable on a phone. It is+ # permanent on every device behind the change, and that parity is what the+ # first four guard.+ #+ # TODO (ui-kit-reorderable-list-cleanup) fold these over the contexts above+ # once the change ships.+ context "when enable_new_reordering_controls is enabled" do+ before { SiteSetting.enable_new_reordering_controls = true }++ context "when on non-touch devices" do+ it "shows the reorder handle for simple-list settings" do+ settings_page.visit("top_menu")+ expect(page).to have_css("html.discourse-no-touch")+ expect(settings_page).to have_reorder_handle("top_menu")+ end++ it "shows the reorder handle for emoji-list settings" do+ settings_page.visit("default_emoji_reactions")+ expect(page).to have_css("html.discourse-no-touch")+ expect(settings_page).to have_reorder_handle("default_emoji_reactions")+ end+ end++ context "when on touch devices", mobile: true do+ it "shows the same reorder handle for simple-list settings" do+ settings_page.visit("top_menu")+ expect(page).to have_css("html.discourse-touch")+ expect(settings_page).to have_reorder_handle("top_menu")+ end++ it "shows the same reorder handle for emoji-list settings" do+ settings_page.visit("default_emoji_reactions")+ expect(page).to have_css("html.discourse-touch")+ expect(settings_page).to have_reorder_handle("default_emoji_reactions")+ end+ end++ it "keeps an emoji where the admin moved it" do+ settings_page.visit("default_emoji_reactions")++ settings_page.move_list_value_to_top("default_emoji_reactions", "tada")+ settings_page.save_setting("default_emoji_reactions")+ expect(settings_page).to have_overridden_setting("default_emoji_reactions")++ page.refresh++ expect(settings_page).to have_list_values_in_order(+ "default_emoji_reactions",+ %w[tada +1 heart],+ )+ end++ # The menu is portaled and positioned asynchronously, so focusing a+ # destination before it has been placed asks the browser to scroll to+ # wherever the float still sits, which throws the reader to the top of the+ # settings page they were working in.+ it "does not scroll the page when the move menu opens" do+ # Short enough that the settings page has somewhere to scroll from, which+ # is the whole of what this measures.+ resize_window(height: 700) do+ settings_page.visit_category("basic")+ expect(settings_page).to have_reorder_handle("top_menu")++ page.execute_script(<<~JS)+ document+ .querySelector("[data-setting='top_menu'] .d-reorderable-list__handle")+ .scrollIntoView({ block: "center" });+ JS+ before = page.evaluate_script("Math.round(window.scrollY)")+ expect(before).to be > 0++ settings_page.open_reorder_menu("top_menu")++ expect(page).to have_css(".d-reorderable-list__move-item:focus")+ expect(page.evaluate_script("Math.round(window.scrollY)")).to eq(before)+ end+ end++ # A pointer press does not set focus-visible, and the menu places focus on+ # a destination as it opens, so a highlight keyed on that alone leaves a+ # mouse user with a focused item and no way to see which one it is.+ it "highlights the focused destination when the menu is opened by pointer" do+ settings_page.visit_category("basic")+ expect(settings_page).to have_reorder_handle("top_menu")++ settings_page.open_reorder_menu("top_menu")++ expect(page).to have_css(".d-reorderable-list__move-item:focus")+ background = page.evaluate_script(<<~JS)+ getComputedStyle(document.querySelector(".d-reorderable-list__move-item:focus"))+ .backgroundColor+ JS+ expect(background).not_to eq("rgba(0, 0, 0, 0)")+ end+ endendenddiff --git a/spec/system/admin_user_fields_spec.rb b/spec/system/admin_user_fields_spec.rbindex 0311773a367..6a9fefae5e5 100644--- a/spec/system/admin_user_fields_spec.rb+++ b/spec/system/admin_user_fields_spec.rb@@ -103,4 +103,42 @@ describe "Admin User Fields" doexpect(page).to have_no_text(I18n.t("admin_js.admin.user_fields.requirement.confirmation"))endend++ context "when enable_new_reordering_controls is enabled" do+ fab!(:field1) { Fabricate(:user_field, name: "Favourite colour") }+ fab!(:field2) { Fabricate(:user_field, name: "Home town") }++ before { SiteSetting.enable_new_reordering_controls = true }++ it "keeps each row's controls anchored to its own row on mobile", mobile: true do+ user_fields_page.visit++ expect(page).to have_css(".admin-user_field-item", count: 2)++ escaped = page.evaluate_script(<<~JS)+ Array.from(document.querySelectorAll(".d-table__cell.--controls")).filter(+ (cell) => cell.offsetParent !== cell.closest("tr")+ ).length+ JS++ expect(escaped).to eq(0)+ end++ it "sizes the drag handle column to the handle" do+ user_fields_page.visit++ expect(page).to have_css(".admin-user_field-item", count: 2)++ width = page.evaluate_script(<<~JS)+ Math.round(+ document+ .querySelector(".d-reorderable-list__handle")+ .closest("td")+ .getBoundingClientRect().width+ )+ JS++ expect(width).to be < 60+ end+ endenddiff --git a/spec/system/custom_sidebar_sections_spec.rb b/spec/system/custom_sidebar_sections_spec.rbindex 81106ced4e3..c47d64e5938 100644--- a/spec/system/custom_sidebar_sections_spec.rb+++ b/spec/system/custom_sidebar_sections_spec.rb@@ -288,6 +288,192 @@ describe "Custom sidebar sections" doexpect(page).not_to have_css(".sidebar-section-form-link .draggable")end+ # TODO (ui-kit-reorderable-list-cleanup) fold these over the examples above+ # once the change ships.+ context "when enable_new_reordering_controls is enabled" do+ before { SiteSetting.enable_new_reordering_controls = true }++ it "lets the user select text in a link's fields" do+ # The row is a drag source, and a `draggable` element turns a press-drag into+ # a drag rather than a selection. These rows are a form: the name and URL are+ # text inputs whose contents a user edits and copies, so only the grip may be+ # draggable.+ #+ # A selection inside a form control does not appear in `window.getSelection`,+ # so this reads the input's own selection range.+ sidebar_section = Fabricate(:sidebar_section, title: "My section", user: user)++ Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags").tap do |sidebar_url|+ Fabricate(:sidebar_section_link, sidebar_section: sidebar_section, linkable: sidebar_url)+ end++ sign_in user+ visit("/latest")+ sidebar.edit_custom_section("My section")++ url_field = ".sidebar-section-form-link input[name='link-url']"+ # Leftwards and well past the field's edge: the press lands at its centre,+ # which for a short value is beyond the end of the text, so a short sweep+ # crosses no characters and would fail whether or not selection works. A+ # drag running off the edge still selects back to the start.+ drag_with_pointer(from: url_field, by: { x: -400 })++ expect(+ page.evaluate_script(+ "(() => { const i = document.querySelector(\"#{url_field}\"); " \+ "return i.selectionEnd - i.selectionStart; })()",+ ),+ ).to be > 0+ end++ it "lets the user reorder links in a custom section" do+ sidebar_section = Fabricate(:sidebar_section, title: "My section", user: user)++ sidebar_url_1 =+ Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags").tap do |sidebar_url|+ Fabricate(:sidebar_section_link, sidebar_section: sidebar_section, linkable: sidebar_url)+ end++ sidebar_url_2 =+ Fabricate(+ :sidebar_url,+ name: "Sidebar Categories",+ value: "/categories",+ ).tap do |sidebar_url|+ Fabricate(:sidebar_section_link, sidebar_section: sidebar_section, linkable: sidebar_url)+ end++ sidebar_url_3 =+ Fabricate(:sidebar_url, name: "Sidebar Latest", value: "/latest").tap do |sidebar_url|+ Fabricate(:sidebar_section_link, sidebar_section: sidebar_section, linkable: sidebar_url)+ end++ sign_in user++ visit("/latest")++ expect(sidebar.primary_section_links("my-section")).to eq(+ ["Sidebar Tags", "Sidebar Categories", "Sidebar Latest"],+ )++ sidebar.edit_custom_section("My section")++ drag_and_drop(+ source: ".sidebar-section-form-link:has(.draggable[data-link-name='Sidebar Tags'])",+ # Press the grip, not the row centre: the centre is a text input, and a+ # text-selection drag stalls after dragstart.+ source_position: {+ x: 16,+ y: 20,+ },+ target: ".sidebar-section-form-link:has(.draggable[data-link-name='Sidebar Categories'])",+ target_position: {+ x: 100,+ y: 55,+ },+ )+ try_until_success do+ expect(section_modal.link_names).to eq(+ ["Sidebar Categories", "Sidebar Tags", "Sidebar Latest"],+ )+ end+ section_modal.save+ expect(section_modal).to be_closed++ try_until_success do+ expect(sidebar.primary_section_links("my-section")).to eq(+ ["Sidebar Categories", "Sidebar Tags", "Sidebar Latest"],+ )+ end+ end++ it "lets the user reorder links with the keyboard" do+ sidebar_section = Fabricate(:sidebar_section, title: "My section", user: user)++ ["Sidebar Tags", "Sidebar Categories", "Sidebar Latest"].each do |name|+ Fabricate(:sidebar_url, name: name, value: "/#{name.parameterize}").tap do |sidebar_url|+ Fabricate(:sidebar_section_link, sidebar_section: sidebar_section, linkable: sidebar_url)+ end+ end++ sign_in user++ visit("/latest")++ sidebar.edit_custom_section("My section")++ # Asserted before the move: without it, a run where the order already matched+ # would pass whether or not the arrow did anything.+ expect(section_modal.link_names).to eq(+ ["Sidebar Tags", "Sidebar Categories", "Sidebar Latest"],+ )++ section_modal.move_link_down("Sidebar Tags")++ try_until_success do+ expect(section_modal.link_names).to eq(+ ["Sidebar Categories", "Sidebar Tags", "Sidebar Latest"],+ )+ end++ # Focus is where the keyboard path lives or dies: the row moves in the DOM+ # under the pressed control, and a lost focus makes a second press+ # impossible.+ expect(section_modal.focused_link_name).to eq("Sidebar Tags")++ # So the second press goes through whatever holds focus, not through another+ # lookup by name, which would pass even if focus had been dropped.+ section_modal.press_focused_link_move_down++ try_until_success do+ expect(section_modal.link_names).to eq(+ ["Sidebar Categories", "Sidebar Latest", "Sidebar Tags"],+ )+ end++ section_modal.save+ expect(section_modal).to be_closed++ try_until_success do+ expect(sidebar.primary_section_links("my-section")).to eq(+ ["Sidebar Categories", "Sidebar Latest", "Sidebar Tags"],+ )+ end+ end++ it "offers both the drag handle and the arrows on mobile", mobile: true do+ sidebar_section = Fabricate(:sidebar_section, title: "My section", user: user)++ Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags").tap do |sidebar_url|+ Fabricate(:sidebar_section_link, sidebar_section: sidebar_section, linkable: sidebar_url)+ end++ Fabricate(:sidebar_url, name: "Sidebar Categories", value: "/categories").tap do |sidebar_url|+ Fabricate(:sidebar_section_link, sidebar_section: sidebar_section, linkable: sidebar_url)+ end++ sign_in user++ visit("/latest")++ sidebar.open_on_mobile+ sidebar.edit_custom_section("My section")++ # The handle renders on every viewport now that the drag begins on the grip+ # rather than anywhere on the row, so a press meant to scroll still scrolls.+ expect(page).to have_css(".sidebar-section-form-link .draggable")++ # Neither path substitutes for the other: the menu behind the handle is the+ # only route without a drag, and the drag is the only route without a+ # keyboard.+ section_modal.move_link_down("Sidebar Tags")++ try_until_success do+ expect(section_modal.link_names).to eq(["Sidebar Categories", "Sidebar Tags"])+ end+ end+ end+it "reorders links in the sidebar with drag and drop" dosidebar_section = Fabricate(:sidebar_section, title: "My section", user: user)Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags").tap do |sidebar_url|diff --git a/spec/system/edit_user_directory_columns_spec.rb b/spec/system/edit_user_directory_columns_spec.rbnew file mode 100644index 00000000000..cea6744400b--- /dev/null+++ b/spec/system/edit_user_directory_columns_spec.rb@@ -0,0 +1,30 @@+# frozen_string_literal: true++describe "Edit user directory columns" do+ fab!(:admin)++ let(:columns_modal) { PageObjects::Modals::EditUserDirectoryColumns.new }++ before { sign_in(admin) }++ # TODO (ui-kit-reorderable-list-cleanup) drop the context once the change+ # ships and this is the only arm.+ context "when enable_new_reordering_controls is enabled" do+ before { SiteSetting.enable_new_reordering_controls = true }++ it "keeps a column where the admin moved it" do+ columns = DirectoryColumn.order(:position).to_a++ visit("/u")+ columns_modal.open+ expect(columns_modal).to have_columns_in_order(columns)++ columns_modal.move_to_top(columns.last)+ columns_modal.save+ expect(columns_modal).to be_closed++ columns_modal.open+ expect(columns_modal).to have_columns_in_order([columns.last, *columns[0...-1]])+ end+ end+enddiff --git a/spec/system/editing_sidebar_community_section_spec.rb b/spec/system/editing_sidebar_community_section_spec.rbindex 27f4735017f..bab1fb7bf31 100644--- a/spec/system/editing_sidebar_community_section_spec.rb+++ b/spec/system/editing_sidebar_community_section_spec.rb@@ -56,6 +56,77 @@ RSpec.describe "Editing Sidebar Community Section" do)end+ # TODO (ui-kit-reorderable-list-cleanup) fold this over the example above+ # once the change ships.+ context "when enable_new_reordering_controls is enabled" do+ before { SiteSetting.enable_new_reordering_controls = true }++ it "lets an admin reorder and reset the Community section" do+ sign_in(admin)++ visit("/latest")++ expect(sidebar.primary_section_icons("community")).to eq(+ %w[layer-group user inbox flag wrench paper-plane ellipsis-vertical],+ )++ modal = sidebar.click_community_section_more_button.click_customize_community_section_button+ modal.fill_link("Topics", "/latest", "paper-plane")+ drag_and_drop(+ source: ".sidebar-section-form-link:has(.draggable[data-link-name='Topics'])",+ # Press the grip, not the row centre: the centre is a text input, and a+ # text-selection drag stalls after dragstart.+ source_position: {+ x: 16,+ y: 20,+ },+ target: ".sidebar-section-form-link:has(.draggable[data-link-name='My messages'])",+ target_position: {+ x: 100,+ y: 55,+ },+ )+ try_until_success do+ expect(modal.link_names).to eq(+ ["My posts", "My messages", "Topics", "Review", "Admin", "Invite"],+ )+ end+ modal.save+ modal.confirm_update++ page.refresh++ try_until_success do+ expect(sidebar.primary_section_links("community")).to eq(+ ["My posts", "My messages", "Topics", "Review", "Admin", "Invite", "More"],+ )+ end++ try_until_success do+ expect(sidebar.primary_section_icons("community")).to eq(+ %w[user inbox paper-plane flag wrench paper-plane ellipsis-vertical],+ )+ end++ modal = sidebar.click_community_section_more_button.click_customize_community_section_button+ modal.reset++ expect(sidebar).to have_section("Community")++ try_until_success do+ expect(sidebar.primary_section_links("community")).to eq(+ ["Topics", "My posts", "My messages", "Review", "Admin", "Invite", "More"],+ )+ end++ try_until_success do+ expect(sidebar.primary_section_icons("community")).to eq(+ %w[layer-group user inbox flag wrench paper-plane ellipsis-vertical],+ )+ end+ end+ end+it "lets an admin localize manually created Community section links" doSiteSetting.content_localization_enabled = trueSiteSetting.content_localization_supported_locales = "ja"diff --git a/spec/system/page_objects/components/manageable_row_list_modal.rb b/spec/system/page_objects/components/manageable_row_list_modal.rbindex 4cbb5ff1948..9792037e8d8 100644--- a/spec/system/page_objects/components/manageable_row_list_modal.rb+++ b/spec/system/page_objects/components/manageable_row_list_modal.rb@@ -26,7 +26,7 @@ module PageObjectsenddef enabled_identifiers- all("#{@modal} #{ENABLED_ROW}").map { |el| el["data-identifier"] }+ all("#{@modal} #{ENABLED_ROW}").map { |el| row_key(el) }enddef has_enabled_rows_in_order?(identifiers)@@ -39,11 +39,15 @@ module PageObjectsenddef has_all_row?(identifier)- has_css?("#{@modal} #{ROW}[data-identifier='#{identifier}']")+ has_css?(+ "#{@modal} #{ROW}[data-identifier='#{identifier}'], #{@modal} #{ROW}[data-reorderable-key='#{identifier}']",+ )enddef has_no_all_row?(identifier)- has_no_css?("#{@modal} #{ROW}[data-identifier='#{identifier}']")+ has_no_css?(+ "#{@modal} #{ROW}[data-identifier='#{identifier}'], #{@modal} #{ROW}[data-reorderable-key='#{identifier}']",+ )enddef toggle(identifier)@@ -52,17 +56,24 @@ module PageObjectsenddef has_toggle_on?(identifier)- has_css?("#{@modal} #{ENABLED_ROW}[data-identifier='#{identifier}']")+ has_css?(+ "#{@modal} #{ENABLED_ROW}[data-identifier='#{identifier}'], #{@modal} #{ENABLED_ROW}[data-reorderable-key='#{identifier}']",+ )enddef has_toggle_off?(identifier)- has_css?("#{@modal} #{ROW}[data-identifier='#{identifier}']") &&- has_no_css?("#{@modal} #{ENABLED_ROW}[data-identifier='#{identifier}']")+ has_css?(+ "#{@modal} #{ROW}[data-identifier='#{identifier}'], #{@modal} #{ROW}[data-reorderable-key='#{identifier}']",+ ) &&+ has_no_css?(+ "#{@modal} #{ENABLED_ROW}[data-identifier='#{identifier}'], #{@modal} #{ENABLED_ROW}[data-reorderable-key='#{identifier}']",+ )enddef toggle_for(identifier)PageObjects::Components::DToggleSwitch.new(- "#{@modal} #{ROW}[data-identifier='#{identifier}'] .d-toggle-switch__checkbox",+ "#{@modal} #{ROW}[data-identifier='#{identifier}'] .d-toggle-switch__checkbox, " \+ "#{@modal} #{ROW}[data-reorderable-key='#{identifier}'] .d-toggle-switch__checkbox",)end@@ -114,12 +125,76 @@ module PageObjectshas_no_css?("#{@modal} .manageable-row-list__list.--reorderable")end+ # Methods for when the enable_new_reordering_controls upcoming change is+ # enabled. The disabled group above keeps main's behaviour; anything whose+ # meaning differs is named separately rather than swapped in place.+ #+ # TODO (ui-kit-reorderable-list-cleanup) fold these over the disabled+ # group once the change ships.++ # The row's own reorderable list, for driving and inspecting its moves.+ def reorderable(identifier)+ PageObjects::Components::ReorderableList.new(reorderable_row_selector(identifier))+ end++ def has_move_up?(identifier)+ reorderable(identifier).has_destination?(:up)+ end++ def has_no_move_up?(identifier)+ reorderable(identifier).has_no_destination?(:up)+ end++ def has_move_down?(identifier)+ reorderable(identifier).has_destination?(:down)+ end++ def has_no_move_down?(identifier)+ reorderable(identifier).has_no_destination?(:down)+ end++ # Distinct from has_drag_controls?, which asks whether the legacy list is+ # in its reorderable state. This asks whether a row offers a handle.+ def has_reorderable_handles?+ has_css?("#{@modal} #{ROW} .d-reorderable-list__handle")+ end++ def has_no_reorderable_handles?+ has_css?("#{@modal} #{ROW}") && has_no_css?("#{@modal} #{ROW} .d-reorderable-list__handle")+ end++ # A real browser drag, which is the only way to prove the row is a+ # registered drag source rather than merely carrying a handle.+ def drag_report(source_identifier, target_identifier)+ drag_and_drop(+ source: "#{reorderable_row_selector(source_identifier)} .d-reorderable-list__handle",+ target: reorderable_row_selector(target_identifier),+ target_position: {+ x: 100,+ y: 1,+ },+ )+ self+ end+def has_counter?(count, max)has_css?("#{@modal} .manageable-row-list__counter",text: I18n.t(@counter_i18n_key, count:, max:),)end++ private++ # Either arm's row identity: the legacy rows name it one way, the shared+ # list names it another.+ def row_key(element)+ element["data-identifier"] || element["data-reorderable-key"]+ end++ def reorderable_row_selector(identifier)+ "#{@modal} #{ROW}[data-reorderable-key='#{identifier}']"+ endendendenddiff --git a/spec/system/page_objects/modals/edit_user_directory_columns.rb b/spec/system/page_objects/modals/edit_user_directory_columns.rbnew file mode 100644index 00000000000..013581f94de--- /dev/null+++ b/spec/system/page_objects/modals/edit_user_directory_columns.rb@@ -0,0 +1,42 @@+# frozen_string_literal: true++module PageObjects+ module Modals+ # Methods for when the enable_new_reordering_controls upcoming change is+ # enabled, where the columns are a reorderable list.+ class EditUserDirectoryColumns < PageObjects::Modals::Base+ MODAL_SELECTOR = ".edit-user-directory-columns-modal"+ COLUMN_SELECTOR = "#{MODAL_SELECTOR} .edit-directory-column"++ def open+ find(".open-edit-columns-btn").click+ self+ end++ def move_to_top(column)+ PageObjects::Components::ReorderableList.new(column_selector(column)).move(:top)+ self+ end++ def save+ click_primary_button+ self+ end++ def has_columns_in_order?(columns)+ has_css?(COLUMN_SELECTOR, count: columns.size) &&+ columns.each_with_index.all? do |column, index|+ has_css?(+ "#{COLUMN_SELECTOR}:nth-child(#{index + 1})[data-reorderable-key='#{column.id}']",+ )+ end+ end++ private++ def column_selector(column)+ "#{COLUMN_SELECTOR}[data-reorderable-key='#{column.id}']"+ end+ end+ end+enddiff --git a/spec/system/page_objects/modals/sidebar_section_form.rb b/spec/system/page_objects/modals/sidebar_section_form.rbindex a456e56850c..d4e603223e5 100644--- a/spec/system/page_objects/modals/sidebar_section_form.rb+++ b/spec/system/page_objects/modals/sidebar_section_form.rb@@ -204,6 +204,54 @@ module PageObjectsfind(".draggable[data-link-name='Review']")end+ # Methods for when the enable_new_reordering_controls upcoming change is+ # enabled. topics_link/review_link above keep main's drag-source lookups.+ #+ # TODO (ui-kit-reorderable-list-cleanup) fold these over them once the change+ # ships.++ # Driven by the keyboard rather than clicked: the reorder control exists+ # because a drag has no keyboard path, so the spec has to go through the+ # keyboard to be testing the thing it was added for.+ def move_link_up(name)+ link_handle(name).send_keys(%i[alt up])+ end++ def move_link_down(name)+ link_handle(name).send_keys(%i[alt down])+ end++ # Presses whatever the previous move left focused, rather than looking the+ # handle up again. Finding it by name would pass even if focus had been lost,+ # which is most of what there is to get wrong here.+ def press_focused_link_move_down+ page.driver.with_playwright_page { |pw_page| pw_page.keyboard.press("Alt+ArrowDown") }+ end++ def open_focused_link_menu+ page.driver.with_playwright_page { |pw_page| pw_page.keyboard.press("Enter") }+ end++ # The link whose row currently holds focus. The row is the cursor's item, so+ # this is what says focus survived a move; the handle inside it is a pointer+ # affordance and never takes focus from the keyboard.+ def focused_link_name+ page.evaluate_script("document.activeElement?.dataset?.linkName")+ end++ def link_handle(name)+ find("button[aria-label='Reorder #{name}']")+ end++ # Read from the name inputs, not from the drag handles, so it reports the+ # order on a touch screen too, where no handle renders. Scoped away from the+ # secondary list, which renders in a wrapper of its own.+ def link_names+ all(".sidebar-section-form__links-wrapper:not(.--secondary) input[name='link-name']").map(+ &:value+ )+ end+def has_source_language?(locale)page.has_css?(".sidebar-section-form__source-locale-select option[value='#{locale}']:checked",diff --git a/spec/system/page_objects/pages/admin_dashboard.rb b/spec/system/page_objects/pages/admin_dashboard.rbindex ecc9ee7dbed..81d5d4a2776 100644--- a/spec/system/page_objects/pages/admin_dashboard.rb+++ b/spec/system/page_objects/pages/admin_dashboard.rb@@ -182,9 +182,10 @@ module PageObjectsenddef toggle_section(id)- within(".db-configure__row[data-section-id='#{id}']") do- find(".d-toggle-switch__label").click- end+ within(+ ".db-configure__row[data-section-id='#{id}'], " \+ ".db-configure__row[data-reorderable-key='#{id}']",+ ) { find(".d-toggle-switch__label").click }selfend@@ -195,6 +196,48 @@ module PageObjectsselfend+ # Methods for when the enable_new_reordering_controls upcoming change is++ # enabled. move_section_up/down above keep main's arrow-button behaviour.++ #++ # TODO (ui-kit-reorderable-list-cleanup) fold these over them once the change++ # ships.++ def configure_reorderable(id)+ PageObjects::Components::ReorderableList.new(+ ".db-configure__row[data-reorderable-key='#{id}']",+ )+ end++ def move_section_up_via_list(id)+ configure_reorderable(id).move(:up)++ self+ end++ def move_section_down_via_list(id)+ configure_reorderable(id).move(:down)++ self+ end++ def drag_section(source_id, target_id)+ drag_and_drop(+ source:+ ".db-configure__row[data-reorderable-key='#{source_id}'] .d-reorderable-list__handle",+ target: ".db-configure__row[data-reorderable-key='#{target_id}']",+ target_position: {+ x: 100,+ y: 1,+ },+ )++ self+ end+def move_section_up(id)within(".db-configure__row[data-section-id='#{id}']") dofind(".db-configure__arrow:first-child").clickdiff --git a/spec/system/page_objects/pages/admin_flags.rb b/spec/system/page_objects/pages/admin_flags.rbindex b89b499daa1..a453d65658e 100644--- a/spec/system/page_objects/pages/admin_flags.rb+++ b/spec/system/page_objects/pages/admin_flags.rb@@ -71,6 +71,52 @@ module PageObjectshas_no_css?(".flag-menu-content")end+ # Methods for when the enable_new_reordering_controls upcoming change is+ # enabled. move_up/move_down below keep main's menu-driven behaviour.+ #+ # TODO (ui-kit-reorderable-list-cleanup) fold these over them once the+ # change ships.+ def reorderable(key)+ PageObjects::Components::ReorderableList.new(reorderable_row_selector(key))+ end++ def move_up_via_list(key)+ reorderable(key).move(:up)+ self+ end++ def move_down_via_list(key)+ reorderable(key).move(:down)+ self+ end++ def move_to_top_via_list(key)+ reorderable(key).move(:top)+ self+ end++ # A real browser drag, the only move that can cross several rows without+ # naming a destination. The drop lands on the target's top edge.+ def drag_flag_above(source_key, target_key)+ drag_and_drop(+ source: "#{reorderable_row_selector(source_key)} .d-reorderable-list__handle",+ target: reorderable_row_selector(target_key),+ target_position: {+ x: 100,+ y: 1,+ },+ )+ self+ end++ # Waiting, unlike has_flags?, so it can follow a move or a page load.+ def has_flags_in_order?(*flags)+ has_css?(".admin-flag-item__name", count: flags.size) &&+ flags.each_with_index.all? do |flag, index|+ has_css?(".admin-flag-item:nth-child(#{index + 1}) .admin-flag-item__name", text: flag)+ end+ end+def move_down(key)toggle_flag_menu(key)find(".admin-flag-item__move-down").click@@ -106,6 +152,12 @@ module PageObjectsexpect(page).to have_no_css(".dialog-body", wait: Capybara.default_max_wait_time * 3)selfend++ private++ def reorderable_row_selector(key)+ ".admin-flag-item.#{key}"+ endendendenddiff --git a/spec/system/page_objects/pages/admin_site_settings.rb b/spec/system/page_objects/pages/admin_site_settings.rbindex 72a1f21fe47..9c33f1be10c 100644--- a/spec/system/page_objects/pages/admin_site_settings.rb+++ b/spec/system/page_objects/pages/admin_site_settings.rb@@ -212,6 +212,39 @@ module PageObjectshas_css?("#{setting_row_selector(setting_name)} .shift-down-value-btn", visible: :hidden)end+ # Methods for when the enable_new_reordering_controls upcoming change is+ # enabled. The two predicates above keep main's arrow-button behaviour.+ #+ # TODO (ui-kit-reorderable-list-cleanup) fold these over them once the+ # change ships.+ def has_reorder_handle?(setting_name)+ has_css?("#{setting_row_selector(setting_name)} .d-reorderable-list__handle")+ end++ def open_reorder_menu(setting_name)+ find(+ "#{setting_row_selector(setting_name)} .d-reorderable-list__handle",+ match: :first,+ ).click+ has_css?(".d-reorderable-list__move-item")+ self+ end++ def move_list_value_to_top(setting_name, value)+ PageObjects::Components::ReorderableList.new(+ "#{setting_row_selector(setting_name)} .value[data-reorderable-key='#{value}']",+ ).move(:top)+ self+ end++ def has_list_values_in_order?(setting_name, values)+ list = "#{setting_row_selector(setting_name)} .values"+ has_css?("#{list} .value", count: values.size) &&+ values.each_with_index.all? do |value, index|+ has_css?("#{list} .value:nth-child(#{index + 1})[data-reorderable-key='#{value}']")+ end+ end+def category_setting(setting_name)PageObjects::Components::SelectKit.new("#{setting_row_selector(setting_name)} .category-chooser",diff --git a/spec/system/reordering_screenshots_spec.rb b/spec/system/reordering_screenshots_spec.rbnew file mode 100644index 00000000000..82c207dd5e4--- /dev/null+++ b/spec/system/reordering_screenshots_spec.rb@@ -0,0 +1,129 @@+# frozen_string_literal: true++# Photographs every reordering surface with `enable_new_reordering_controls`+# off and on, so the two arms can be compared side by side.+#+# TODO (ui-kit-reorderable-list-cleanup) delete this file once the change ships+# and there is only one arm left to photograph.+describe "Reordering surfaces" do+ fab!(:admin)+ fab!(:user_field) { Fabricate(:user_field, name: "Favourite colour") }+ fab!(:second_user_field) { Fabricate(:user_field, name: "Home town") }++ # A non-system grouping, so the badge groupings shot shows a row that can be+ # renamed and removed next to the ones that cannot.+ fab!(:custom_grouping) { BadgeGrouping.create!(name: "Custom grouping", position: 10) }++ let(:dashboard) { PageObjects::Pages::AdminDashboard.new }+ let(:reports_dashboard) { PageObjects::Pages::AdminDashboardReports.new }+ let(:settings_page) { PageObjects::Pages::AdminSiteSettings.new }+ let(:user_fields_page) { PageObjects::Pages::AdminUserFields.new }+ let(:badges_page) { PageObjects::Pages::AdminBadges.new }+ let(:flags_page) { PageObjects::Pages::AdminFlags.new }+ let(:section_modal) { PageObjects::Modals::SidebarSectionForm.new }+ let(:sidebar) { PageObjects::Components::NavigationMenu::Sidebar.new }++ before do+ SiteSetting.dashboard_improvements = true+ sign_in(admin)+ end++ [false, true].each do |enabled|+ suffix = enabled ? "on" : "off"++ context "with the change #{suffix}" do+ before { SiteSetting.enable_new_reordering_controls = enabled }++ it "photographs the dashboard configure menu" do+ dashboard.visit+ dashboard.open_configure_menu++ expect(page).to have_css(".db-configure__row")+ screenshot_marker(label: "reorder-configure-menu-#{suffix}")+ end++ it "photographs the manage reports modal" do+ AdminDashboardReport.create!(source: "core_report", identifier: "signups", position: 0)+ AdminDashboardReport.create!(source: "core_report", identifier: "topics", position: 1)++ page.visit("/admin")+ reports_dashboard.open_manage_reports_via_cog++ expect(page).to have_css(".manage-reports .manageable-row-list__row")+ screenshot_marker(label: "reorder-manage-reports-#{suffix}")+ end++ it "photographs the compare groups modal" do+ page.visit("/admin")+ find(".db-whos-posting__add-group").click++ expect(page).to have_css(".compare-groups .manageable-row-list__row")+ screenshot_marker(label: "reorder-compare-groups-#{suffix}")+ end++ it "photographs a simple-list setting" do+ settings_page.visit("top_menu")++ expect(page).to have_css(".value-list .value")+ screenshot_marker(label: "reorder-simple-list-#{suffix}")+ end++ it "photographs a value-list setting" do+ SiteSetting.exclude_rel_nofollow_domains = "example.com|discourse.org"+ settings_page.visit("exclude_rel_nofollow_domains")++ expect(page).to have_css(".value-list .value")+ screenshot_marker(label: "reorder-value-list-#{suffix}")+ end++ it "photographs an emoji-list setting" do+ settings_page.visit("default_emoji_reactions")++ expect(page).to have_css(".value-list")+ screenshot_marker(label: "reorder-emoji-list-#{suffix}")+ end++ it "photographs the admin flags table" do+ flags_page.visit++ expect(page).to have_css(".admin-flag-item")+ screenshot_marker(label: "reorder-admin-flags-#{suffix}")+ end++ it "photographs the user fields table" do+ user_fields_page.visit++ expect(page).to have_css(".admin-user_field-item")+ screenshot_marker(label: "reorder-user-fields-#{suffix}")+ end++ it "photographs the badge groupings modal" do+ badges_page.visit_page(Badge::Autobiographer).edit_groupings++ expect(page).to have_css(".badge-grouping-item")+ screenshot_marker(label: "reorder-badge-groupings-#{suffix}")+ end++ it "photographs the directory columns modal" do+ page.visit("/u")+ find(".open-edit-columns-btn").click++ expect(page).to have_css(".edit-directory-column")+ screenshot_marker(label: "reorder-directory-columns-#{suffix}")+ end++ it "photographs the sidebar section form" do+ visit("/latest")+ sidebar.click_add_section_button+ expect(section_modal).to be_visible++ section_modal.fill_name("My section")+ section_modal.fill_link("Sidebar Tags", "/tags")+ section_modal.add_link+ section_modal.fill_last_link("Sidebar Categories", "/categories")++ screenshot_marker(label: "reorder-sidebar-links-#{suffix}")+ end+ end+ end+end