A platform for community discussion. Free, open, simple.
FEATURE: Move sidebar links by dragging them (#42803)
Sérgio Saquetimbff6ad4358b7
diff --git a/app/controllers/sidebar_sections_controller.rb b/app/controllers/sidebar_sections_controller.rbindex ffc6bde4999..0d90e6ee5da 100644--- a/app/controllers/sidebar_sections_controller.rb+++ b/app/controllers/sidebar_sections_controller.rb@@ -93,6 +93,62 @@ class SidebarSectionsController < ApplicationControllerrender_serialized(sidebar_section, SidebarSectionSerializer)end+ def reorder+ SidebarSection::ReorderLinks.call(+ service_params.deep_merge(params: { section_id: params[:id] }),+ ) do+ on_success { |section:| render_serialized(section.reload, SidebarSectionSerializer) }+ on_model_not_found(:section) { raise Discourse::NotFound }+ on_failed_policy(:can_edit_section) { render json: failed_json, status: :forbidden }+ on_failed_policy(:order_covers_every_link) do+ raise Discourse::InvalidParameters.new(:links_order)+ end+ on_failed_contract do |contract|+ render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request+ end+ on_failure { render json: failed_json, status: :unprocessable_entity }+ end+ end++ def move_link+ SidebarSection::MoveLink.call(+ service_params.deep_merge(params: { source_section_id: params[:id] }),+ ) do+ on_success do |source_section:, target_section:|+ sections = [source_section.reload, target_section.reload]+ render json: {+ sidebar_sections:+ sections.map do |section|+ SidebarSectionSerializer.new(section, scope: guardian, root: false).as_json+ end,+ }+ end+ on_model_not_found(:source_section) { raise Discourse::NotFound }+ on_model_not_found(:target_section) { raise Discourse::NotFound }+ on_model_not_found(:link) { raise Discourse::NotFound }+ on_failed_policy(:can_edit_source_section) { render json: failed_json, status: :forbidden }+ on_failed_policy(:can_edit_target_section) { render json: failed_json, status: :forbidden }+ on_failed_policy(:sections_are_distinct) do+ raise Discourse::InvalidParameters.new(:target_section_id)+ end+ on_failed_policy(:sections_are_custom) { raise Discourse::InvalidAccess }+ on_failed_policy(:target_section_has_room) do |target_section:|+ render_json_error(+ I18n.t(+ "activerecord.errors.models.sidebar_section.attributes.base.too_many_sidebar_urls",+ limit: SiteSetting.max_sidebar_section_links,+ count: target_section.sidebar_section_links.count + 1,+ ),+ status: :unprocessable_entity,+ )+ end+ on_failed_contract do |contract|+ render json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request+ end+ on_failure { render json: failed_json, status: :unprocessable_entity }+ end+ end+def destroysidebar_section = SidebarSection.find(section_params["id"])@guardian.ensure_can_delete!(sidebar_section)@@ -178,10 +234,6 @@ class SidebarSectionsController < ApplicationControllerlinksend- def reorder_params- params.permit(:sidebar_section_id, links_order: [])- end-privatedef check_access_if_publicdiff --git a/app/models/sidebar_section.rb b/app/models/sidebar_section.rbindex 93f08b1424b..20bcf2ca641 100644--- a/app/models/sidebar_section.rb+++ b/app/models/sidebar_section.rb@@ -73,8 +73,33 @@ class SidebarSection < ActiveRecord::Baseendend+ # Renumbers the section's links so they read in `ordered_linkable_ids` order.+ # Links the caller left out are pushed to the end.+ def apply_links_order!(ordered_linkable_ids)+ links = sidebar_section_links.reload.to_a+ return if links.empty?++ rank = ordered_linkable_ids.each_with_index.to_h+ reordered = links.sort_by { |link| rank.fetch(link.linkable_id, rank.size) }++ rows =+ reordered.zip(free_positions(links)).map { |link, position| link.attributes.merge(position:) }++ sidebar_section_links.upsert_all(rows, update_only: [:position])+ end+private+ # Positions no link in the section currently holds, in ascending order.+ #+ # `upsert_all` writes every row in one statement, and a unique index covers+ # (sidebar_section_id, user_id, position). Reusing a position another link+ # still holds collides before that row is rewritten. Twice the link count+ # always leaves enough free ones.+ def free_positions(links)+ (0..links.size * 2).to_a - links.map(&:position)+ end+def sidebar_urls_count_within_limitcount = sidebar_urls.reject(&:marked_for_destruction?).sizepersisted_count = sidebar_urls.count(&:persisted?)diff --git a/app/services/sidebar_section/move_link.rb b/app/services/sidebar_section/move_link.rbnew file mode 100644index 00000000000..6603ebaceb1--- /dev/null+++ b/app/services/sidebar_section/move_link.rb@@ -0,0 +1,112 @@+# frozen_string_literal: true++class SidebarSection::MoveLink+ include Service::Base++ params do+ attribute :source_section_id, :integer+ attribute :link_id, :integer+ attribute :target_section_id, :integer+ attribute :position, :integer++ validates :source_section_id, :link_id, :target_section_id, presence: true+ validates :position,+ numericality: {+ only_integer: true,+ greater_than_or_equal_to: 0,+ },+ allow_nil: true+ end++ model :source_section+ model :target_section+ policy :sections_are_distinct+ policy :sections_are_custom+ policy :can_edit_source_section+ policy :can_edit_target_section+ model :link++ transaction do+ step :lock_sections+ # Runs under the lock. Two moves into the same near-full section would+ # otherwise both find room, and both take it.+ policy :target_section_has_room+ step :attach_link_to_target+ step :place_link+ end++ only_if :any_section_public do+ step :publish_public_update+ end++ private++ def fetch_source_section(params:)+ SidebarSection.find_by(id: params.source_section_id)+ end++ def fetch_target_section(params:)+ SidebarSection.find_by(id: params.target_section_id)+ end++ def sections_are_distinct(source_section:, target_section:)+ source_section.id != target_section.id+ end++ # A built-in section's links come from the server, and `reset_community!`+ # restores them wholesale. They cannot move in or out, even for an admin.+ def sections_are_custom(source_section:, target_section:)+ source_section.custom_section? && target_section.custom_section?+ end++ def can_edit_source_section(guardian:, source_section:)+ guardian.can_edit?(source_section)+ end++ def can_edit_target_section(guardian:, target_section:)+ guardian.can_edit?(target_section)+ end++ def target_section_has_room(target_section:)+ target_section.sidebar_section_links.count < SiteSetting.max_sidebar_section_links+ end++ def fetch_link(params:, source_section:)+ source_section.sidebar_section_links.find_by(+ linkable_type: "SidebarUrl",+ linkable_id: params.link_id,+ )+ end++ def lock_sections(source_section:, target_section:)+ SidebarSection.where(id: [source_section.id, target_section.id]).order(:id).lock.load+ end++ def attach_link_to_target(link:, target_section:)+ link.update!(+ sidebar_section: target_section,+ position: target_section.sidebar_section_links.maximum(:position).to_i + 1,+ )+ end++ def place_link(params:, link:, target_section:)+ ordered = target_section.sidebar_section_links.reload.map(&:linkable_id)+ ordered.delete(link.linkable_id)+ index = params.position ? [params.position, ordered.size].min : ordered.size+ ordered.insert(index, link.linkable_id)+ target_section.apply_links_order!(ordered)+ end++ def any_section_public(source_section:, target_section:)+ source_section.public? || target_section.public?+ end++ def publish_public_update(guardian:, source_section:, target_section:)+ [source_section, target_section].select(&:public?)+ .each do |section|+ StaffActionLogger.new(guardian.user).log_update_public_sidebar_section(section)+ end+ MessageBus.publish("/refresh-sidebar-sections", nil)+ Site.clear_anon_cache!+ end+enddiff --git a/app/services/sidebar_section/reorder_links.rb b/app/services/sidebar_section/reorder_links.rbnew file mode 100644index 00000000000..e8e637f832e--- /dev/null+++ b/app/services/sidebar_section/reorder_links.rb@@ -0,0 +1,62 @@+# frozen_string_literal: true++class SidebarSection::ReorderLinks+ include Service::Base++ params do+ attribute :section_id, :integer+ attribute :links_order, :array++ before_validation do+ self.links_order = links_order&.filter_map { |link_id| Integer(link_id, exception: false) }+ end++ validates :section_id, presence: true+ validates :links_order, presence: true+ end++ model :section+ policy :can_edit_section+ policy :order_covers_every_link++ transaction do+ step :lock_section+ step :apply_order+ end++ only_if :public_section do+ step :publish_public_update+ end++ private++ def fetch_section(params:)+ SidebarSection.find_by(id: params.section_id)+ end++ def can_edit_section(guardian:, section:)+ guardian.can_edit?(section)+ end++ def order_covers_every_link(params:, section:)+ params.links_order.sort == section.sidebar_section_links.pluck(:linkable_id).sort+ end++ def lock_section(section:)+ section.lock!+ end++ def apply_order(params:, section:)+ section.apply_links_order!(params.links_order)+ end++ def public_section(section:)+ section.public?+ end++ def publish_public_update(guardian:, section:)+ StaffActionLogger.new(guardian.user).log_update_public_sidebar_section(section)+ MessageBus.publish("/refresh-sidebar-sections", nil)+ Site.clear_anon_cache!+ end+enddiff --git a/app/services/sidebar_section_updater.rb b/app/services/sidebar_section_updater.rbindex d4c697f595c..7f6293bff22 100644--- a/app/services/sidebar_section_updater.rb+++ b/app/services/sidebar_section_updater.rb@@ -30,32 +30,15 @@ class SidebarSectionUpdaterprivatedef update_link_order- order =+ ordered_linkable_ids =@sidebar_section.sidebar_urls.sort_by do |url|@links_params.index { |link| link[:name] == url.name && link[:value] == url.value } || -1end- .each_with_index- .map { |url, index| [url.id, index] }- .to_h+ .map(&:id)- set_order(order)- end-- def set_order(order)- position_generator =- (0..@sidebar_section.sidebar_section_links.count * 2).excluding(- @sidebar_section.sidebar_section_links.map(&:position),- ).each-- links =- @sidebar_section- .sidebar_section_links- .sort_by { |link| order[link.linkable_id] }- .map { |link| link.attributes.merge(position: position_generator.next) }-- @sidebar_section.sidebar_section_links.upsert_all(links, update_only: [:position])+ @sidebar_section.apply_links_order!(ordered_linkable_ids)enddef publish_public_updatediff --git a/config/routes.rb b/config/routes.rbindex d7446c00efb..dafda0b1b9b 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -1975,6 +1975,8 @@ Discourse::Application.routes.draw doresources :sidebar_sections, only: %i[index show create update destroy]put "/sidebar_sections/reset/:id" => "sidebar_sections#reset"+ put "/sidebar_sections/:id/reorder" => "sidebar_sections#reorder"+ put "/sidebar_sections/:id/move_link" => "sidebar_sections#move_link"get "/form-templates/:id" => "form_templates#show"get "/form-templates" => "form_templates#index"diff --git a/frontend/discourse/app/components/modal/sidebar-section-form.gjs b/frontend/discourse/app/components/modal/sidebar-section-form.gjsindex cd45ad75b9c..54ce0240b36 100644--- a/frontend/discourse/app/components/modal/sidebar-section-form.gjs+++ b/frontend/discourse/app/components/modal/sidebar-section-form.gjs@@ -460,7 +460,7 @@ export default class SidebarSectionForm extends Component {"sidebar_sections",this.currentUser.sidebar_sections.concat(data.sidebar_section));- this.closeModal();+ this.closeModal({ createdSection: data.sidebar_section });}).catch((e) => {this.flash = sanitize(extractError(e));diff --git a/frontend/discourse/app/components/sidebar/common/custom-section.gjs b/frontend/discourse/app/components/sidebar/common/custom-section.gjsindex 5c274c565b5..d0b812b0534 100644--- a/frontend/discourse/app/components/sidebar/common/custom-section.gjs+++ b/frontend/discourse/app/components/sidebar/common/custom-section.gjs@@ -1,13 +1,15 @@import Component from "@glimmer/component";import { cached } from "@glimmer/tracking";+import { hash } from "@ember/helper";import { getOwner } from "@ember/owner";import { service } from "@ember/service";import { findActiveLink } from "discourse/lib/sidebar/active-link";import CommonCommunitySection from "discourse/lib/sidebar/common/community-section/section";import Section from "discourse/lib/sidebar/section";import AdminCommunitySection from "discourse/lib/sidebar/user/community-section/admin-section";-import { and, eq, or } from "discourse/truth-helpers";+import { and, eq, not, or } from "discourse/truth-helpers";import dReplaceEmoji from "discourse/ui-kit/helpers/d-replace-emoji";+import dDragAndDropSource from "discourse/ui-kit/modifiers/d-drag-and-drop-source";import MoreSectionLink from "../more-section-link";import MoreSectionLinks from "../more-section-links";import SectionComponent from "../section";@@ -15,6 +17,7 @@ import SectionLink from "../section-link";import SectionLinkButton from "../section-link-button";export default class SidebarCustomSection extends Component {+ @service capabilities;@service currentUser;@service navigationMenu;@service router;@@ -49,6 +52,19 @@ export default class SidebarCustomSection extends Component {);}+ /**+ * Rows drag only where a drop may land, and never on touch-first devices,+ * where the press stays reserved for scrolling and the long-press link+ * preview. A machine with a mouse and a touch screen keeps dragging.+ */+ get linkDragEnabled() {+ return (+ Boolean(this.args.enableLinkDrop) &&+ this.section.canAcceptLinkDrop &&+ !this.capabilities.touchFirst+ );+ }+get exactUrlMatch() {return this.section.links.find((link) => {return this.router.currentURL === link.value;@@ -68,22 +84,18 @@ export default class SidebarCustomSection extends Component {@hideSectionHeader={{this.section.hideSectionHeader}}@linkDropEnabled={{and @enableLinkDrop this.section.canAcceptLinkDrop}}@onLinkDrop={{this.section.dropLink}}- class={{this.section.dragCss}}+ @onLinkMove={{this.section.moveLink}}as |linkDrop|>{{#each this.section.links as |link index|}}<SectionLink- data-sidebar-custom-link="true"class={{if (eq linkDrop.linkDropIndex index) "is-link-drop-before"}}- @scrollIntoView={{and- @scrollActiveLinkIntoView- (eq link.name this.activeLink.name)- }}+ data-sidebar-custom-link="true"@badgeText={{link.badgeText}}@content={{dReplaceEmoji link.text}}@currentWhen={{link.currentWhen}}+ @exactUrlMatch={{this.exactUrlMatch}}@href={{or link.value link.href}}- @linkClass={{link.linkDragCss}}@linkName={{link.name}}@model={{link.model}}@models={{link.models}}@@ -91,12 +103,32 @@ export default class SidebarCustomSection extends Component {@prefixValue={{link.prefixValue}}@query={{link.query}}@route={{link.route}}+ @scrollIntoView={{and+ @scrollActiveLinkIntoView+ (eq link.name this.activeLink.name)+ }}@shouldDisplay={{link.shouldDisplay}}@suffixCSSClass={{link.suffixCSSClass}}@suffixType={{link.suffixType}}@suffixValue={{link.suffixValue}}+ @suppressNativeDrag={{this.linkDragEnabled}}@title={{link.title}}- @exactUrlMatch={{this.exactUrlMatch}}+ {{! Rows drag as registered sources; the native anchor drag is turned+ off with them, or the browser would start its own dead drag from+ the innermost anchor instead. }}+ {{dDragAndDropSource+ type="sidebar-link"+ data=(hash+ linkId=link.id+ name=link.name+ value=link.value+ icon=link.prefixValue+ )+ effectAllowed="move"+ disabled=(not this.linkDragEnabled)+ }}/>{{/each}}diff --git a/frontend/discourse/app/components/sidebar/section-link.gjs b/frontend/discourse/app/components/sidebar/section-link.gjsindex 6755861757c..e24ae8a4ada 100644--- a/frontend/discourse/app/components/sidebar/section-link.gjs+++ b/frontend/discourse/app/components/sidebar/section-link.gjs@@ -204,6 +204,7 @@ export default class SectionLink extends Component {href={{@href}}rel="noopener noreferrer"target={{this.target}}+ draggable={{if @suppressNativeDrag false}}title={{@title}}data-link-name={{@linkName}}class={{this.linkClass}}@@ -272,6 +273,7 @@ export default class SectionLink extends Component {@query={{or @query (hash)}}@models={{this.models}}@current-when={{and (not @exactUrlMatch) @currentWhen}}+ draggable={{if @suppressNativeDrag false}}title={{@title}}data-link-name={{@linkName}}class={{this.linkClass}}diff --git a/frontend/discourse/app/components/sidebar/section.gjs b/frontend/discourse/app/components/sidebar/section.gjsindex d6b1c377cc3..ee5af5a67da 100644--- a/frontend/discourse/app/components/sidebar/section.gjs+++ b/frontend/discourse/app/components/sidebar/section.gjs@@ -1,6 +1,6 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";-import { fn, hash } from "@ember/helper";+import { array, fn, hash } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";import didInsert from "@ember/render-modifiers/modifiers/did-insert";@@ -15,6 +15,7 @@ import {getSidebarSectionContentId,} from "discourse/lib/sidebar/helpers";import {+ linkDropEffectFor,WEB_LINK_ADOPTION,WEB_LINK_KINDS,webLinkPayload,@@ -176,10 +177,18 @@ export default class SidebarSection extends Component {*/@actioncanDropLink({ source }) {- return (- Boolean(this.args.linkDropEnabled) &&- !webLinkPayload(source).containsFiles()- );+ if (!this.args.linkDropEnabled) {+ return false;+ }+ if (source.type === "sidebar-link") {+ return true;+ }+ return !webLinkPayload(source).containsFiles();+ }++ @action+ linkDropEffect({ source }) {+ return linkDropEffectFor(source);}/**@@ -193,8 +202,10 @@ export default class SidebarSection extends Component {@actiontrackLinkDrop({ source, location, element }) {// A drag carrying only text may well turn out to hold nothing droppable, so- // the insertion point stays hidden until the drag declares a real URL.- this.linkDropActive = webLinkPayload(source).containsURLs();+ // the insertion point stays hidden until the drag declares a real URL. A+ // registered row drag has no native payload to ask; it always qualifies.+ this.linkDropActive =+ source.type === "sidebar-link" || webLinkPayload(source).containsURLs();if (!this.linkDropActive) {this.linkDropIndex = undefined;@@ -235,6 +246,10 @@ export default class SidebarSection extends Component {dropLink({ source }) {const linkDropIndex = this.linkDropIndex;this.clearLinkDrop();+ if (source.type === "sidebar-link") {+ this.args.onLinkMove?.(source.data, linkDropIndex);+ return;+ }// Unwrapped here so `onLinkDrop` keeps taking a decorated payload whichever// target reported the drop, and the section model needs no change.this.args.onLinkDrop?.(webLinkPayload(source), linkDropIndex);@@ -246,11 +261,13 @@ export default class SidebarSection extends Component {*/@actioncanDwellToOpen({ source }) {- return (- !this.displaySectionContent &&- this.canDropLink({ source }) &&- webLinkPayload(source).containsURLs()- );+ if (this.displaySectionContent || !this.canDropLink({ source })) {+ return false;+ }+ if (source.type === "sidebar-link") {+ return true;+ }+ return webLinkPayload(source).containsURLs();}/**@@ -311,6 +328,19 @@ export default class SidebarSection extends Component {<template>{{#if this.displaySection}}<div+ class={{dConcatClass+ "sidebar-section"+ "sidebar-section-wrapper"+ (if this.linkDropActive "is-link-drop-active")+ (if+ this.displaySectionContent+ "sidebar-section--expanded"+ "sidebar-section--collapsed"+ )+ (if @persistentActions "sidebar-section--persistent-actions")+ }}+ data-section-name={{@sectionName}}+ ...attributes{{didInsert this.setExpandedState}}{{dDragAndDropExternalTargetaccepts=WEB_LINK_KINDS@@ -325,9 +355,10 @@ export default class SidebarSection extends Component {{{! The same drop, for a link the browser started dragging from thispage rather than from outside the window. }}{{dDragAndDropTarget+ accepts="sidebar-link"adopts=WEB_LINK_ADOPTIONcanDrop=this.canDropLink- dropEffect="copy"+ dropEffect=this.linkDropEffectindicator=falseonDragEnter=this.trackLinkDroponDrag=this.trackLinkDrop@@ -335,25 +366,12 @@ export default class SidebarSection extends Component {onDrop=this.dropLink}}{{dDragDwell- types=WEB_LINK_ADOPTION.type+ types=(array WEB_LINK_ADOPTION.type "sidebar-link")externalKinds=WEB_LINK_KINDScanDwell=this.canDwellToOpenonDwell=this.openForLinkDwellonDwellEnd=this.endLinkDwell}}- data-section-name={{@sectionName}}- class={{dConcatClass- "sidebar-section"- "sidebar-section-wrapper"- (if this.linkDropActive "is-link-drop-active")- (if- this.displaySectionContent- "sidebar-section--expanded"- "sidebar-section--collapsed"- )- (if @persistentActions "sidebar-section--persistent-actions")- }}- ...attributes>{{#unless @hideSectionHeader}}<div class="sidebar-section-header-wrapper sidebar-row">diff --git a/frontend/discourse/app/components/sidebar/user/sections.gjs b/frontend/discourse/app/components/sidebar/user/sections.gjsindex d9c4bc8c62e..fb17414d8cd 100644--- a/frontend/discourse/app/components/sidebar/user/sections.gjs+++ b/frontend/discourse/app/components/sidebar/user/sections.gjs@@ -1,13 +1,18 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";+import { array } from "@ember/helper";import { action } from "@ember/object";import { cancel } from "@ember/runloop";import { service } from "@ember/service";import BlockOutlet from "discourse/blocks/block-outlet";import SidebarSectionForm from "discourse/components/modal/sidebar-section-form";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";import discourseLater from "discourse/lib/later";+import { replaceUserSidebarSections } from "discourse/lib/sidebar/helpers";import {extractDroppedWebLink,+ linkDropEffectFor,WEB_LINK_ADOPTION,WEB_LINK_KINDS,webLinkPayload,@@ -35,6 +40,7 @@ const ZONE_ARM_DELAY = 250;export default class SidebarUserSections extends Component {@service sidebarState;@service currentUser;+ @service dialog;@service modal;/** Whether the new-section drop zone is on screen. */@@ -60,12 +66,14 @@ export default class SidebarUserSections extends Component {*/@actioncanDwellForNewSection({ source }) {+ if (!this.args.enableLinkDrop) {+ return false;+ }+ if (source.type === "sidebar-link") {+ return true;+ }const payload = webLinkPayload(source);- return (- Boolean(this.args.enableLinkDrop) &&- payload.containsURLs() &&- !payload.containsFiles()- );+ return payload.containsURLs() && !payload.containsFiles();}@action@@ -106,11 +114,24 @@ export default class SidebarUserSections extends Component {*/@actioncanDropLink({ source }) {+ if (source.type === "sidebar-link") {+ return true;+ }return !webLinkPayload(source).containsFiles();}+ @action+ linkDropEffect({ source }) {+ return linkDropEffectFor(source);+ }+@actioncreateSectionFromLink({ source }) {+ if (source.type === "sidebar-link") {+ this.#splitOutLink(source.data);+ return;+ }+const link = extractDroppedWebLink(webLinkPayload(source));if (!link) {return;@@ -128,6 +149,71 @@ export default class SidebarUserSections extends Component {return this.sidebarState.panels.find((panel) => panel.key === MAIN_PANEL);}+ /**+ * Splits a dragged row out into a section of its own: the create form opens+ * prefilled from the row, and only a saved creation removes the original+ * from the section it came from. Taking a row out of a public section is a+ * public change and asks first, like every other edit of one.+ */+ async #splitOutLink(dragData) {+ if (dragData.public && !(await this.#confirmPublicChange())) {+ return;+ }++ const result = await this.modal.show(SidebarSectionForm, {+ model: {+ link: {+ icon: dragData.icon || "link",+ name: dragData.name,+ value: dragData.value,+ segment: "primary",+ },+ },+ });++ if (result?.createdSection) {+ await this.#removeLinkFromOrigin(dragData);+ }+ }++ #confirmPublicChange() {+ return new Promise((resolve) => {+ this.dialog.yesNoConfirm({+ message: i18n("sidebar.sections.custom.update_public_confirm"),+ didConfirm: () => resolve(true),+ didCancel: () => resolve(false),+ });+ });+ }++ async #removeLinkFromOrigin({ sectionId, linkId }) {+ const origin = this.currentUser.sidebar_sections.find(+ (section) => section.id === sectionId+ );+ if (!origin) {+ return;+ }++ try {+ // The whole links array rides along: the update endpoint reads order+ // from it, and an omitted link would jump to the front of the section.+ const response = await ajax(`/sidebar_sections/${sectionId}`, {+ type: "PUT",+ contentType: "application/json",+ dataType: "json",+ data: JSON.stringify({+ title: origin.title,+ links: origin.links.map((link) =>+ link.id === linkId ? { ...link, _destroy: "1" } : link+ ),+ }),+ });+ replaceUserSidebarSections(this.currentUser, [response.sidebar_section]);+ } catch (error) {+ popupAjaxError(error);+ }+ }+<template>{{! This is the element that scrolls, so a link dragged in can only reach asection below the fold if the scrolling happens here. Both origins are@@ -136,11 +222,11 @@ export default class SidebarUserSections extends Component {<divclass="sidebar-sections"{{dDragAndDropAutoScroll- types=WEB_LINK_ADOPTION.type+ types=(array WEB_LINK_ADOPTION.type "sidebar-link")externalKinds=WEB_LINK_KINDS}}{{dDragDwell- types=WEB_LINK_ADOPTION.type+ types=(array WEB_LINK_ADOPTION.type "sidebar-link")externalKinds=WEB_LINK_KINDScanDwell=this.canDwellForNewSectiononDwell=this.revealZone@@ -179,9 +265,10 @@ export default class SidebarUserSections extends Component {{{! The same drop, for a link the browser started dragging from thispage rather than from outside the window. }}{{dDragAndDropTarget+ accepts="sidebar-link"adopts=WEB_LINK_ADOPTIONcanDrop=this.canDropLink- dropEffect="copy"+ dropEffect=this.linkDropEffectindicator=falseonDragEnter=this.trackZoneHoveronDragLeave=this.clearZoneHoverdiff --git a/frontend/discourse/app/lib/sidebar/helpers.js b/frontend/discourse/app/lib/sidebar/helpers.jsindex c4911474607..7d7dc42704c 100644--- a/frontend/discourse/app/lib/sidebar/helpers.js+++ b/frontend/discourse/app/lib/sidebar/helpers.js@@ -23,3 +23,17 @@ export function getSidebarSectionContentId(name) {export function getCollapsedSidebarSectionKey(name) {return `sidebar-section-${name}-collapsed`;}++/**+ * Replaces freshly-changed sections in the user's list, the same way the edit+ * form applies its save, so the sidebar re-renders from them.+ *+ * @param {User} user - The current user holding `sidebar_sections`.+ * @param {Object[]} updatedSections - Serialized sections to swap in by id.+ */+export function replaceUserSidebarSections(user, updatedSections) {+ const sections = user.sidebar_sections.map((section) => {+ return updatedSections.find((fresh) => fresh.id === section.id) ?? section;+ });+ user.set("sidebar_sections", sections);+}diff --git a/frontend/discourse/app/lib/sidebar/link-drop.js b/frontend/discourse/app/lib/sidebar/link-drop.jsindex 95f737d1e09..35dc48d9ec8 100644--- a/frontend/discourse/app/lib/sidebar/link-drop.js+++ b/frontend/discourse/app/lib/sidebar/link-drop.js@@ -7,6 +7,21 @@ import { SIDEBAR_URL } from "discourse/lib/constants";*/export const WEB_LINK_KINDS = ["urls", "html", "text"];+/**+ * The drop effect a target answers a link drag with. A row being moved is taken+ * from where it was. An incoming link is copied in.+ *+ * Every target that accepts both must agree. A row drags as `move`, so a target+ * answering `copy` makes the pair incompatible. The browser then refuses the+ * drop outright: no `drop` event, nothing logged.+ *+ * @param {Object} source - The source a drop target reported.+ * @returns {"move"|"copy"} The effect for this source.+ */+export function linkDropEffectFor(source) {+ return source.type === "sidebar-link" ? "move" : "copy";+}+/*** Lets the sidebar accept a link the browser started dragging from this page —* a topic row, a category, a link in a post — none of which register a dragdiff --git a/frontend/discourse/app/lib/sidebar/section-link.js b/frontend/discourse/app/lib/sidebar/section-link.jsindex 2e429015ffd..0344fc9e382 100644--- a/frontend/discourse/app/lib/sidebar/section-link.js+++ b/frontend/discourse/app/lib/sidebar/section-link.js@@ -1,8 +1,4 @@-import { tracked } from "@glimmer/tracking";-export default class SectionLink {- @tracked linkDragCss;-constructor({ external, icon, id, name, value }, section) {this.external = external;this.prefixValue = icon;diff --git a/frontend/discourse/app/lib/sidebar/section.js b/frontend/discourse/app/lib/sidebar/section.jsindex 15a4572417e..e73e5c3fde1 100644--- a/frontend/discourse/app/lib/sidebar/section.js+++ b/frontend/discourse/app/lib/sidebar/section.js@@ -1,4 +1,3 @@-import { tracked } from "@glimmer/tracking";import { setOwner } from "@ember/owner";import { service } from "@ember/service";import { isPresent } from "@ember/utils";@@ -6,6 +5,7 @@ import SidebarSectionForm from "discourse/components/modal/sidebar-section-form"import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { bind } from "discourse/lib/decorators";+import { replaceUserSidebarSections } from "discourse/lib/sidebar/helpers";import { extractDroppedWebLink } from "discourse/lib/sidebar/link-drop";import SectionLink from "discourse/lib/sidebar/section-link";import { autoTrackedArray } from "discourse/lib/tracked-tools";@@ -14,10 +14,10 @@ import { i18n } from "discourse-i18n";export default class Section {@service currentUser;+ @service dialog;@service modal;@service router;- @tracked dragCss;@autoTrackedArray links;constructor({ section, owner }) {@@ -120,40 +120,98 @@ export default class Section {return "pencil";}+ /**+ * Commits a dragged row's drop into this section: a drop from this very+ * section reorders it, one from another section transfers the link here.+ *+ * @param {Object} dragData - The drag source's payload: `sectionId`,+ * `linkId`, and whether the source section is `public`.+ * @param {number|undefined} dropIndex - The measured drop offset;+ * undefined appends.+ */@bind- disable() {- this.dragCss = "disabled";- }+ async moveLink(dragData, dropIndex) {+ const reordering = dragData.sectionId === this.section.id;+ // A drop right back into the gap it came from, on either side of the row,+ // changes nothing; decided before anything asks, so it never nags either.+ if (reordering && this.#reorderIsNoop(dragData.linkId, dropIndex)) {+ return;+ }- @bind- enable() {- this.dragCss = null;+ // Editing a public section reaches everyone, so a drag that touches one,+ // on either end, gets the same confirmation the edit form gives it.+ if (dragData.public || this.section.public) {+ if (!(await this.#confirmPublicChange())) {+ return;+ }+ }++ if (reordering) {+ await this.#reorderLink(dragData, dropIndex);+ } else {+ await this.#transferLinkHere(dragData, dropIndex);+ }}- @bind- moveLinkDown(link) {- const position = this.links.indexOf(link);- this.links.splice(position, 1);- this.links.splice(position + 1, 0, link);+ #reorderIsNoop(linkId, dropIndex) {+ const fromIndex = this.#indexOfLink(linkId);+ const toIndex = dropIndex ?? this.links.length;+ return toIndex === fromIndex || toIndex === fromIndex + 1;}- @bind- moveLinkUp(link) {- const position = this.links.indexOf(link);- this.links.splice(position, 1);- this.links.splice(position - 1, 0, link);+ /**+ * Where a link sits right now. The drag payload only snapshots the list at+ * `dragstart`, and the drop may land in a different one.+ */+ #indexOfLink(linkId) {+ return this.links.findIndex((link) => link.id === linkId);}- @bind- reorder() {- return ajax(`/sidebar_sections/reorder`, {- type: "POST",- contentType: "application/json",- dataType: "json",- data: JSON.stringify({- sidebar_section_id: this.section.id,- links_order: this.links.map((link) => link.id),- }),+ #confirmPublicChange() {+ return new Promise((resolve) => {+ this.dialog.yesNoConfirm({+ message: i18n("sidebar.sections.custom.update_public_confirm"),+ didConfirm: () => resolve(true),+ didCancel: () => resolve(false),+ });});}++ async #reorderLink({ linkId }, dropIndex) {+ const fromIndex = this.#indexOfLink(linkId);+ if (fromIndex === -1) {+ return;+ }++ const toIndex = dropIndex ?? this.links.length;+ const ids = this.links.map((link) => link.id);+ ids.splice(fromIndex, 1);+ ids.splice(toIndex > fromIndex ? toIndex - 1 : toIndex, 0, linkId);++ try {+ const response = await ajax(+ `/sidebar_sections/${this.section.id}/reorder`,+ { type: "PUT", data: { links_order: ids } }+ );+ replaceUserSidebarSections(this.currentUser, [response.sidebar_section]);+ } catch (error) {+ popupAjaxError(error);+ }+ }++ async #transferLinkHere({ sectionId, linkId }, dropIndex) {+ try {+ const response = await ajax(`/sidebar_sections/${sectionId}/move_link`, {+ type: "PUT",+ data: {+ link_id: linkId,+ target_section_id: this.section.id,+ position: dropIndex ?? this.links.length,+ },+ });+ replaceUserSidebarSections(this.currentUser, response.sidebar_sections);+ } catch (error) {+ popupAjaxError(error);+ }+ }}diff --git a/frontend/discourse/app/services/capabilities.js b/frontend/discourse/app/services/capabilities.jsindex 9f38c931289..4842a9d9258 100644--- a/frontend/discourse/app/services/capabilities.js+++ b/frontend/discourse/app/services/capabilities.js@@ -11,6 +11,8 @@ const APPLE_USER_AGENT_DATA_PLATFORM = /macOS/;const ua = navigator.userAgent;const anyPointerCoarseQuery = new TrackedMediaQuery("(any-pointer: coarse)");+const pointerCoarseQuery = new TrackedMediaQuery("(pointer: coarse)");+/*** The primary pointer, not `any-pointer`: a phone with stylus support reports* a fine pointer among its inputs while its primary pointer stays coarse.@@ -183,6 +185,17 @@ class _Capabilities {return anyPointerCoarseQuery.matches;}+ /**+ * Whether the primary pointer is coarse, i.e. the device is touch-first.+ * Unlike {@link touch}, this stays false on a mouse-driven machine that+ * also has a touch screen.+ *+ * @returns {boolean}+ */+ get touchFirst() {+ return pointerCoarseQuery.matches;+ }+/*** Whether the device is likely to have a physical keyboard, so keyboard* shortcuts are worth showing. There is no direct signal for this, so it isdiff --git a/frontend/discourse/tests/acceptance/sidebar-link-drop-test.js b/frontend/discourse/tests/acceptance/sidebar-link-drop-test.jsindex 54d780008ab..15c62449ba3 100644--- a/frontend/discourse/tests/acceptance/sidebar-link-drop-test.js+++ b/frontend/discourse/tests/acceptance/sidebar-link-drop-test.js@@ -1,4 +1,6 @@import {+ click,+ fillIn,find,findAll,settled,@@ -6,12 +8,17 @@ import {visit,} from "@ember/test-helpers";import { test } from "qunit";+import sinon from "sinon";import { ADMIN_PANEL, MAIN_PANEL } from "discourse/lib/sidebar/panels";import { acceptance } from "discourse/tests/helpers/qunit-helpers";import {+ centerOf,dragEvent,+ dragOver,externalDragOver,+ simulateDrag,simulateExternalDrag,+ startDrag,} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";function linkDataTransfer() {@@ -395,3 +402,450 @@ acceptance(});});++function moveFixtureSections() {+ return [+ {+ id: 900,+ title: "Reading",+ slug: "reading",+ public: false,+ section_type: null,+ links: [+ {+ id: 901,+ // Not the "link" fallback, so a split-out that loses the icon fails.+ icon: "bookmark",+ name: "Existing link",+ value: "https://example.org/existing",+ external: true,+ segment: "primary",+ },+ {+ id: 902,+ name: "Second link",+ value: "https://example.org/second",+ icon: "link",+ external: true,+ segment: "primary",+ },+ ],+ },+ {+ id: 910,+ title: "Watching",+ slug: "watching",+ public: false,+ section_type: null,+ links: [+ {+ id: 911,+ name: "Other link",+ value: "https://example.org/other",+ icon: "link",+ external: true,+ segment: "primary",+ },+ ],+ },+ ];+}++acceptance("Sidebar link move", function (needs) {+ needs.user({ sidebar_sections: moveFixtureSections() });+ needs.settings({ navigation_menu: "sidebar" });++ let reorderRequests;+ let moveRequests;++ needs.hooks.beforeEach(function () {+ reorderRequests = [];+ moveRequests = [];+ });++ needs.pretender((server, helper) => {+ server.put("/sidebar_sections/900/reorder", (request) => {+ reorderRequests.push(helper.parsePostData(request.requestBody));+ const [reading] = moveFixtureSections();+ reading.links.reverse();+ return helper.response({ sidebar_section: reading });+ });+ server.put("/sidebar_sections/900/move_link", (request) => {+ moveRequests.push(helper.parsePostData(request.requestBody));+ const [reading, watching] = moveFixtureSections();+ watching.links.push(reading.links.shift());+ return helper.response({ sidebar_sections: [reading, watching] });+ });+ });++ const READING = '.sidebar-section[data-section-name="reading"]';+ const WATCHING = '.sidebar-section[data-section-name="watching"]';+ const FIRST_ROW = `${READING} li[data-sidebar-custom-link]:nth-of-type(1)`;++ test("dragging a link below its sibling reorders the section", async function (assert) {+ await visit("/");++ const rows = findAll(`${READING} [data-sidebar-custom-link]`);+ const target = rows[1].getBoundingClientRect();++ await simulateDrag(FIRST_ROW, READING, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: { clientY: target.bottom - 2 },+ });++ assert.strictEqual(reorderRequests.length, 1, "commits one reorder");+ assert.deepEqual(+ reorderRequests[0]["links_order[]"],+ ["902", "901"],+ "sends the new id order"+ );+ assert+ .dom(".sidebar-section-form-modal")+ .doesNotExist("a move opens no form");+ assert+ .dom(+ `${READING} li[data-sidebar-custom-link]:nth-of-type(1) [data-link-name]`+ )+ .hasAttribute(+ "data-link-name",+ "Second link",+ "the section re-renders in the committed order"+ );+ });++ test("dragging a link into another section moves it", async function (assert) {+ await visit("/");++ await simulateDrag(FIRST_ROW, WATCHING, {+ dataTransfer: new DataTransfer(),+ });++ assert.strictEqual(moveRequests.length, 1, "commits one move");+ assert.strictEqual(moveRequests[0].link_id, "901", "names the link");+ assert.strictEqual(+ moveRequests[0].target_section_id,+ "910",+ "names the destination"+ );+ assert.true("position" in moveRequests[0], "carries the drop position");+ assert+ .dom(`${WATCHING} [data-link-name="Existing link"]`)+ .exists("the link now renders in the target section");+ assert+ .dom(`${READING} [data-link-name="Existing link"]`)+ .doesNotExist("and left its old section");+ });++ test("dropping a link back onto its own position changes nothing", async function (assert) {+ await visit("/");++ const rows = findAll(`${READING} [data-sidebar-custom-link]`);+ const own = rows[0].getBoundingClientRect();++ await simulateDrag(FIRST_ROW, READING, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: { clientY: own.top + 2 },+ });++ assert.strictEqual(reorderRequests.length, 0, "no reorder request");+ assert.strictEqual(moveRequests.length, 0, "no move request");+ assert+ .dom(".sidebar-section-form-modal")+ .doesNotExist("and no form either");+ });++ test("a touch screen beside a fine pointer keeps links draggable", async function (assert) {+ sinon+ .stub(this.owner.lookup("service:capabilities"), "touch")+ .get(() => true);++ await visit("/");++ assert+ .dom(`${READING} li[data-sidebar-custom-link][data-drag-source]`)+ .exists({ count: 2 }, "rows still drag with the mouse");+ });++ test("a coarse primary pointer turns link dragging off", async function (assert) {+ sinon+ .stub(this.owner.lookup("service:capabilities"), "touchFirst")+ .get(() => true);++ await visit("/");++ assert+ .dom(`${READING} li[data-sidebar-custom-link][data-drag-source]`)+ .doesNotExist("the press stays reserved for scrolling");+ });+});++function publicMoveFixtureSections() {+ return [+ {+ id: 900,+ title: "Reading",+ slug: "reading",+ public: false,+ section_type: null,+ links: [+ {+ id: 901,+ name: "Existing link",+ value: "https://example.org/existing",+ icon: "link",+ external: true,+ segment: "primary",+ },+ ],+ },+ {+ id: 920,+ title: "Announcements",+ slug: "announcements",+ public: true,+ section_type: null,+ links: [+ {+ id: 921,+ name: "First public",+ value: "https://example.org/first-public",+ icon: "link",+ external: true,+ segment: "primary",+ },+ {+ id: 922,+ name: "Second public",+ value: "https://example.org/second-public",+ icon: "link",+ external: true,+ segment: "primary",+ },+ ],+ },+ ];+}++acceptance("Sidebar link move | public section", function (needs) {+ needs.user({ admin: true, sidebar_sections: publicMoveFixtureSections() });+ needs.settings({ navigation_menu: "sidebar" });++ let requests;++ needs.hooks.beforeEach(function () {+ requests = [];+ });++ needs.pretender((server, helper) => {+ server.put("/sidebar_sections/920/reorder", (request) => {+ requests.push(helper.parsePostData(request.requestBody));+ const [, announcements] = publicMoveFixtureSections();+ announcements.links.reverse();+ return helper.response({ sidebar_section: announcements });+ });+ server.put("/sidebar_sections/920/move_link", (request) => {+ requests.push(helper.parsePostData(request.requestBody));+ const [reading, announcements] = publicMoveFixtureSections();+ reading.links.push(announcements.links.shift());+ return helper.response({ sidebar_sections: [announcements, reading] });+ });+ });++ const PUBLIC = '.sidebar-section[data-section-name="announcements"]';+ const PRIVATE = '.sidebar-section[data-section-name="reading"]';+ const PUBLIC_FIRST_ROW = `${PUBLIC} li[data-sidebar-custom-link]:nth-of-type(1)`;++ test("reordering a public section asks first, and cancel commits nothing", async function (assert) {+ await visit("/");++ const rows = findAll(`${PUBLIC} [data-sidebar-custom-link]`);+ const target = rows[1].getBoundingClientRect();++ await simulateDrag(PUBLIC_FIRST_ROW, PUBLIC, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: { clientY: target.bottom - 2 },+ });++ assert+ .dom(".dialog-container .dialog-content")+ .exists("the change is visible to everyone, so it asks first");+ assert.strictEqual(requests.length, 0, "nothing committed while asking");++ await click(".dialog-footer .btn-default");+ assert.strictEqual(requests.length, 0, "declining commits nothing");+ assert+ .dom(+ `${PUBLIC} li[data-sidebar-custom-link]:nth-of-type(1) [data-link-name]`+ )+ .hasAttribute("data-link-name", "First public", "the order is untouched");+ });++ test("confirming the public reorder commits it", async function (assert) {+ await visit("/");++ const rows = findAll(`${PUBLIC} [data-sidebar-custom-link]`);+ const target = rows[1].getBoundingClientRect();++ await simulateDrag(PUBLIC_FIRST_ROW, PUBLIC, {+ dataTransfer: new DataTransfer(),+ targetCoordinates: { clientY: target.bottom - 2 },+ });+ await click(".dialog-footer .btn-primary");++ assert.strictEqual(requests.length, 1, "the confirmed reorder commits");+ assert.deepEqual(+ requests[0]["links_order[]"],+ ["922", "921"],+ "with the new order"+ );+ });++ test("moving a public link into a private section still asks", async function (assert) {+ await visit("/");++ await simulateDrag(PUBLIC_FIRST_ROW, PRIVATE, {+ dataTransfer: new DataTransfer(),+ });++ assert+ .dom(".dialog-container .dialog-content")+ .exists("taking a link out of a public section is a public change");++ await click(".dialog-footer .btn-primary");+ assert.strictEqual(requests.length, 1, "the confirmed move commits");+ assert.strictEqual(requests[0].link_id, "921", "moving the public link");+ assert.strictEqual(+ requests[0].target_section_id,+ "900",+ "into the private section"+ );+ });+});++acceptance("Sidebar link move | split out to a new section", function (needs) {+ needs.user({ sidebar_sections: moveFixtureSections() });+ needs.settings({ navigation_menu: "sidebar" });++ let createRequests;+ let cleanupRequests;++ needs.hooks.beforeEach(function () {+ createRequests = [];+ cleanupRequests = [];+ });++ needs.pretender((server, helper) => {+ server.post("/sidebar_sections", (request) => {+ createRequests.push(helper.parsePostData(request.requestBody));+ return helper.response({+ sidebar_section: {+ id: 930,+ title: "Split",+ slug: "split",+ public: false,+ section_type: null,+ links: [+ {+ id: 931,+ name: "Existing link",+ value: "https://example.org/existing",+ icon: "link",+ external: true,+ segment: "primary",+ },+ ],+ },+ });+ });+ server.put("/sidebar_sections/900", (request) => {+ cleanupRequests.push(helper.parsePostData(request.requestBody));+ const [reading] = moveFixtureSections();+ reading.links.shift();+ return helper.response({ sidebar_section: reading });+ });+ });++ const READING = '.sidebar-section[data-section-name="reading"]';+ const FIRST_ROW = `${READING} li[data-sidebar-custom-link]:nth-of-type(1)`;++ async function dragRowToRevealedZone() {+ const dataTransfer = new DataTransfer();+ await startDrag(FIRST_ROW, { dataTransfer });++ const scroller = find(".sidebar-sections").getBoundingClientRect();+ await dragOver(".sidebar-sections", {+ dataTransfer,+ coordinates: {+ clientX: scroller.left + scroller.width / 2,+ clientY: scroller.top + scroller.height / 2,+ },+ });+ await settled();++ await dragOver(".sidebar-link-drop-target", { dataTransfer });++ // Captured before the drop: the zone hides the moment the drag ends.+ const zonePoint = centerOf(".sidebar-link-drop-target");+ await dragEvent(".sidebar-link-drop-target", "drop", {+ dataTransfer,+ ...zonePoint,+ });+ await dragEvent(FIRST_ROW, "dragend", { dataTransfer, ...zonePoint });+ }++ test("dropping a row on the zone creates a section and removes the original on save", async function (assert) {+ await visit("/");++ await dragRowToRevealedZone();++ assert+ .dom(".sidebar-section-form-modal")+ .exists("the create form opens for the split-out section");+ assert+ .dom('input[name="link-name"]')+ .hasValue("Existing link", "prefilled with the dragged link");+ assert+ .dom('input[name="link-url"]')+ .hasValue("https://example.org/existing", "and its URL");++ await fillIn('input[name="section-name"]', "Split");+ await click("#save-section");++ assert.strictEqual(createRequests.length, 1, "creates the new section");+ assert.strictEqual(+ createRequests[0].links[0].value,+ "https://example.org/existing",+ "with the moved link"+ );+ assert.strictEqual(+ createRequests[0].links[0].icon,+ "bookmark",+ "carrying the row's own icon rather than the generic fallback"+ );+ assert.strictEqual(+ cleanupRequests.length,+ 1,+ "and removes the link from its origin section"+ );+ const links = cleanupRequests[0].links;+ const removed = links.find((link) => `${link.id}` === "901");+ const kept = links.find((link) => `${link.id}` === "902");+ assert.strictEqual(removed._destroy, "1", "the moved link is destroyed");+ assert.strictEqual(kept._destroy, undefined, "its sibling is kept");+ });++ test("cancelling the split-out leaves the origin untouched", async function (assert) {+ await visit("/");++ await dragRowToRevealedZone();+ assert.dom(".sidebar-section-form-modal").exists("the create form opens");++ await click(".d-modal .modal-close");++ assert.strictEqual(createRequests.length, 0, "nothing was created");+ assert.strictEqual(cleanupRequests.length, 0, "nothing was removed");+ assert+ .dom(`${READING} [data-link-name="Existing link"]`)+ .exists("the link stays where it was");+ });+});diff --git a/frontend/discourse/tests/integration/components/sidebar/section-test.gjs b/frontend/discourse/tests/integration/components/sidebar/section-test.gjsindex 0170cb64ddc..0a177cb2237 100644--- a/frontend/discourse/tests/integration/components/sidebar/section-test.gjs+++ b/frontend/discourse/tests/integration/components/sidebar/section-test.gjs@@ -1,3 +1,4 @@+import { hash } from "@ember/helper";import {click,find,@@ -12,9 +13,12 @@ import {centerOf,dragEvent,dragEventNow,+ dragOver,externalDragOver,simulateExternalDrag,+ startDrag,} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";+import dDragAndDropSource from "discourse/ui-kit/modifiers/d-drag-and-drop-source";/** A drag carrying a real URL, the way a link dragged from another tab arrives. */function urlTransfer() {@@ -349,6 +353,35 @@ module("Integration | Component | Sidebar | Section", function (hooks) {);});+ test("opens under one of its own links being moved over it", async function (assert) {+ const movable = <template>+ <div+ data-test-row+ {{dDragAndDropSource+ type="sidebar-link"+ data=(hash sectionId=1 linkId=2 index=0)+ effectAllowed="move"+ }}+ >a row from elsewhere</div>+ <collapsedSection />+ </template>;+ await render(movable);+ await click(".sidebar-section-header-caret");++ assert.dom(".sidebar-section-content").doesNotExist("starts collapsed");++ const dataTransfer = new DataTransfer();+ await startDrag("[data-test-row]", { dataTransfer });+ await dragOver(".sidebar-section", { dataTransfer });+ await settled();++ assert+ .dom(".sidebar-section-content")+ .exists(+ "a link being moved opens a collapsed section the same way an incoming one does"+ );+ });+test("appends rather than claiming the top while still closed", async function (assert) {let index = "not called";await renderCollapsed((_source, linkDropIndex) => {diff --git a/frontend/discourse/tests/unit/lib/sidebar/link-drop-test.js b/frontend/discourse/tests/unit/lib/sidebar/link-drop-test.jsindex 394fac44259..14649de3892 100644--- a/frontend/discourse/tests/unit/lib/sidebar/link-drop-test.js+++ b/frontend/discourse/tests/unit/lib/sidebar/link-drop-test.js@@ -1,5 +1,8 @@import { module, test } from "qunit";-import { extractDroppedWebLink } from "discourse/lib/sidebar/link-drop";+import {+ extractDroppedWebLink,+ linkDropEffectFor,+} from "discourse/lib/sidebar/link-drop";/*** Stands in for the decorated payload a drop target hands its consumer. Each@@ -17,6 +20,26 @@ function externalSource({ urls = [], html = null, text = null, strings = {} }) {}module("Unit | Lib | Sidebar | link-drop", function () {+ // Only a system spec can check the wiring: `effectAllowed` is not settable on+ // the DataTransfer a synthetic drag carries. This pins the mapping.+ test("answers a row's own drag with move, and anything else with copy", function (assert) {+ assert.strictEqual(+ linkDropEffectFor({ type: "sidebar-link" }),+ "move",+ "a row is taken from where it was"+ );+ assert.strictEqual(+ linkDropEffectFor({ type: undefined }),+ "copy",+ "a link dragged in from elsewhere is copied"+ );+ assert.strictEqual(+ linkDropEffectFor({ type: "something-else" }),+ "copy",+ "and so is any other registered drag"+ );+ });+test("takes the first URL it can actually use", function (assert) {const link = extractDroppedWebLink(externalSource({diff --git a/spec/models/sidebar_section_spec.rb b/spec/models/sidebar_section_spec.rbindex 2abce077df6..2892fe9488c 100644--- a/spec/models/sidebar_section_spec.rb+++ b/spec/models/sidebar_section_spec.rb@@ -38,4 +38,47 @@ RSpec.describe SidebarSection do],)end++ describe "#apply_links_order!" do+ fab!(:first_url) { Fabricate(:sidebar_url, name: "First", value: "/first") }+ fab!(:second_url) { Fabricate(:sidebar_url, name: "Second", value: "/second") }+ fab!(:third_url) { Fabricate(:sidebar_url, name: "Third", value: "/third") }+ fab!(:first_link) { Fabricate(:sidebar_section_link, sidebar_section:, linkable: first_url) }+ fab!(:second_link) { Fabricate(:sidebar_section_link, sidebar_section:, linkable: second_url) }+ fab!(:third_link) { Fabricate(:sidebar_section_link, sidebar_section:, linkable: third_url) }++ it "orders the links to match the requested order" do+ sidebar_section.apply_links_order!([third_url.id, first_url.id, second_url.id])++ expect(sidebar_section.sidebar_urls.reload.map(&:id)).to eq(+ [third_url.id, first_url.id, second_url.id],+ )+ end++ it "sorts links missing from the requested order last" do+ sidebar_section.apply_links_order!([third_url.id, first_url.id])++ expect(sidebar_section.sidebar_urls.reload.map(&:id)).to eq(+ [third_url.id, first_url.id, second_url.id],+ )+ end++ it "reassigns positions already occupied by other links" do+ sidebar_section.apply_links_order!([third_url.id, second_url.id, first_url.id])++ positions = sidebar_section.sidebar_section_links.reload.map(&:position)+ expect(positions.uniq.size).to eq(3)+ expect(sidebar_section.sidebar_urls.reload.map(&:id)).to eq(+ [third_url.id, second_url.id, first_url.id],+ )+ end++ it "is a no-op for a section without links" do+ empty_section = Fabricate(:sidebar_section, title: "Empty", user: user)++ expect { empty_section.apply_links_order!([first_url.id]) }.not_to change {+ SidebarSectionLink.pluck(:id, :position).sort+ }+ end+ endenddiff --git a/spec/requests/sidebar_sections_controller_spec.rb b/spec/requests/sidebar_sections_controller_spec.rbindex 1b70cbea2b5..011212b76a4 100644--- a/spec/requests/sidebar_sections_controller_spec.rb+++ b/spec/requests/sidebar_sections_controller_spec.rb@@ -1244,4 +1244,201 @@ RSpec.describe SidebarSectionsController doexpect(response.status).to eq(403)endend++ describe "#reorder" do+ fab!(:sidebar_section) { Fabricate(:sidebar_section, user: user) }+ fab!(:sidebar_url_1) { Fabricate(:sidebar_url, name: "tags", value: "/tags") }+ fab!(:sidebar_url_2) { Fabricate(:sidebar_url, name: "categories", value: "/categories") }+ fab!(:section_link_1) do+ Fabricate(:sidebar_section_link, sidebar_section: sidebar_section, linkable: sidebar_url_1)+ end+ fab!(:section_link_2) do+ Fabricate(:sidebar_section_link, sidebar_section: sidebar_section, linkable: sidebar_url_2)+ end++ it "reorders the links of the user's own section" do+ sign_in(user)++ put "/sidebar_sections/#{sidebar_section.id}/reorder.json",+ params: {+ links_order: [sidebar_url_2.id, sidebar_url_1.id],+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["sidebar_section"]["links"].map { |link| link["id"] }).to eq(+ [sidebar_url_2.id, sidebar_url_1.id],+ )+ expect(sidebar_section.sidebar_urls.reload.map(&:id)).to eq(+ [sidebar_url_2.id, sidebar_url_1.id],+ )+ end++ it "returns 404 for an unknown section" do+ sign_in(user)++ put "/sidebar_sections/-999/reorder.json",+ params: {+ links_order: [sidebar_url_2.id, sidebar_url_1.id],+ }++ expect(response.status).to eq(404)+ end++ it "doesn't allow to reorder another user's section" do+ sign_in(moderator)++ put "/sidebar_sections/#{sidebar_section.id}/reorder.json",+ params: {+ links_order: [sidebar_url_2.id, sidebar_url_1.id],+ }++ expect(response.status).to eq(403)+ expect(sidebar_section.sidebar_urls.reload.map(&:id)).to eq(+ [sidebar_url_1.id, sidebar_url_2.id],+ )+ end++ it "returns 400 when links_order is missing" do+ sign_in(user)++ put "/sidebar_sections/#{sidebar_section.id}/reorder.json"++ expect(response.status).to eq(400)+ expect(response.parsed_body["errors"]).to be_present+ end++ it "says which parameter was wrong when the order misses a link" do+ sign_in(user)++ put "/sidebar_sections/#{sidebar_section.id}/reorder.json",+ params: {+ links_order: [sidebar_url_1.id],+ }++ expect(response.status).to eq(400)+ expect(response.parsed_body["errors"].join).to include("links_order")+ expect(sidebar_section.sidebar_urls.reload.map(&:id)).to eq(+ [sidebar_url_1.id, sidebar_url_2.id],+ )+ end+ end++ describe "#move_link" do+ fab!(:source_section) { Fabricate(:sidebar_section, title: "Source section", user: user) }+ fab!(:target_section) { Fabricate(:sidebar_section, title: "Target section", user: user) }+ fab!(:moved_url) { Fabricate(:sidebar_url, name: "moved", value: "/moved") }+ fab!(:target_url) { Fabricate(:sidebar_url, name: "existing", value: "/existing") }+ fab!(:moved_link) do+ Fabricate(:sidebar_section_link, sidebar_section: source_section, linkable: moved_url)+ end+ fab!(:target_link) do+ Fabricate(:sidebar_section_link, sidebar_section: target_section, linkable: target_url)+ end++ it "moves the link between the user's own sections and returns both serialized sections" do+ sign_in(user)++ put "/sidebar_sections/#{source_section.id}/move_link.json",+ params: {+ link_id: moved_url.id,+ target_section_id: target_section.id,+ position: 0,+ }++ expect(response.status).to eq(200)++ sections = response.parsed_body["sidebar_sections"]+ expect(sections.map { |section| section["id"] }).to eq([source_section.id, target_section.id])+ expect(sections.first["links"]).to eq([])+ expect(sections.last["links"].map { |link| link["id"] }).to eq([moved_url.id, target_url.id])+ expect(moved_link.reload.sidebar_section_id).to eq(target_section.id)+ end++ it "returns 404 for an unknown source section" do+ sign_in(user)++ put "/sidebar_sections/-999/move_link.json",+ params: {+ link_id: moved_url.id,+ target_section_id: target_section.id,+ }++ expect(response.status).to eq(404)+ end++ it "returns 404 when the link is not in the source section" do+ sign_in(user)++ put "/sidebar_sections/#{source_section.id}/move_link.json",+ params: {+ link_id: target_url.id,+ target_section_id: target_section.id,+ }++ expect(response.status).to eq(404)+ end++ it "doesn't allow to move links of another user's section" do+ sign_in(moderator)++ put "/sidebar_sections/#{source_section.id}/move_link.json",+ params: {+ link_id: moved_url.id,+ target_section_id: target_section.id,+ }++ expect(response.status).to eq(403)+ expect(moved_link.reload.sidebar_section_id).to eq(source_section.id)+ end++ it "returns 400 for a negative position" do+ sign_in(user)++ put "/sidebar_sections/#{source_section.id}/move_link.json",+ params: {+ link_id: moved_url.id,+ target_section_id: target_section.id,+ position: -1,+ }++ expect(response.status).to eq(400)+ expect(response.parsed_body["errors"]).to be_present+ end++ it "names the limit when the target section is full" do+ SiteSetting.max_sidebar_section_links = 1+ sign_in(user)++ put "/sidebar_sections/#{source_section.id}/move_link.json",+ params: {+ link_id: moved_url.id,+ target_section_id: target_section.id,+ }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to eq(+ [+ I18n.t(+ "activerecord.errors.models.sidebar_section.attributes.base.too_many_sidebar_urls",+ limit: 1,+ count: 2,+ ),+ ],+ )+ expect(moved_link.reload.sidebar_section_id).to eq(source_section.id)+ end++ it "returns 400 when the target section is the source section" do+ sign_in(user)++ put "/sidebar_sections/#{source_section.id}/move_link.json",+ params: {+ link_id: moved_url.id,+ target_section_id: source_section.id,+ }++ expect(response.status).to eq(400)+ expect(response.parsed_body["errors"]).to be_present+ end+ endenddiff --git a/spec/services/sidebar_section/move_link_spec.rb b/spec/services/sidebar_section/move_link_spec.rbnew file mode 100644index 00000000000..7784945ecd6--- /dev/null+++ b/spec/services/sidebar_section/move_link_spec.rb@@ -0,0 +1,228 @@+# frozen_string_literal: true++RSpec.describe SidebarSection::MoveLink do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:source_section_id) }+ it { is_expected.to validate_presence_of(:link_id) }+ it { is_expected.to validate_presence_of(:target_section_id) }+ it { is_expected.to allow_values(nil, 0, 5).for(:position) }+ it { is_expected.not_to allow_values(-1).for(:position) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:current_user, :user)+ fab!(:source_section) { Fabricate(:sidebar_section, title: "Source", user: current_user) }+ fab!(:target_section) { Fabricate(:sidebar_section, title: "Target", user: current_user) }+ fab!(:moved_url) { Fabricate(:sidebar_url, name: "Moved", value: "/moved") }+ fab!(:first_target_url) { Fabricate(:sidebar_url, name: "First", value: "/first") }+ fab!(:second_target_url) { Fabricate(:sidebar_url, name: "Second", value: "/second") }+ fab!(:moved_link) do+ Fabricate(:sidebar_section_link, sidebar_section: source_section, linkable: moved_url)+ end+ fab!(:first_target_link) do+ Fabricate(:sidebar_section_link, sidebar_section: target_section, linkable: first_target_url)+ end+ fab!(:second_target_link) do+ Fabricate(:sidebar_section_link, sidebar_section: target_section, linkable: second_target_url)+ end++ let(:params) { { source_section_id:, link_id:, target_section_id:, position: } }+ let(:dependencies) { { guardian: } }+ let(:guardian) { current_user.guardian }+ let(:source_section_id) { source_section.id }+ let(:link_id) { moved_url.id }+ let(:target_section_id) { target_section.id }+ let(:position) { 0 }+ let(:messages) { MessageBus.track_publish("/refresh-sidebar-sections") { result } }++ context "when contract is invalid" do+ let(:position) { -1 }++ it { is_expected.to fail_a_contract }+ end++ context "when source section is not found" do+ let(:source_section_id) { 0 }++ it { is_expected.to fail_to_find_a_model(:source_section) }+ end++ context "when target section is not found" do+ let(:target_section_id) { 0 }++ it { is_expected.to fail_to_find_a_model(:target_section) }+ end++ context "when source and target sections are the same" do+ let(:target_section_id) { source_section.id }++ it { is_expected.to fail_a_policy(:sections_are_distinct) }+ end++ context "when acting user cannot edit the source section" do+ fab!(:current_user, :user)++ it { is_expected.to fail_a_policy(:can_edit_source_section) }+ end++ context "when acting user cannot edit the target section" do+ before { target_section.update!(public: true) }++ it { is_expected.to fail_a_policy(:can_edit_target_section) }+ end++ context "when the target section is full" do+ before { SiteSetting.max_sidebar_section_links = 2 }++ it { is_expected.to fail_a_policy(:target_section_has_room) }+ end++ context "when the link is not in the source section" do+ let(:link_id) { first_target_url.id }++ it { is_expected.to fail_to_find_a_model(:link) }+ end++ # Signed in as an admin, who may edit a built-in section. The refusal can+ # only come from the section being built in, not from permission.+ context "when the source section is built in" do+ let(:community_section) { SidebarSection.find_by(section_type: :community) }+ let(:source_section_id) { community_section.id }+ let(:link_id) { community_section.sidebar_urls.first.id }++ before { current_user.update!(admin: true) }++ it { is_expected.to fail_a_policy(:sections_are_custom) }+ end++ context "when the target section is built in" do+ let(:community_section) { SidebarSection.find_by(section_type: :community) }+ let(:target_section_id) { community_section.id }++ before { current_user.update!(admin: true) }++ it { is_expected.to fail_a_policy(:sections_are_custom) }+ end++ context "when everything's ok" do+ it { is_expected.to run_successfully }++ it "moves the existing link row to the target section" do+ expect { result }.to change { moved_link.reload.sidebar_section_id }.from(+ source_section.id,+ ).to(target_section.id)+ end++ it "keeps the same sidebar URL without destroying or recreating records" do+ expect { result }.to not_change { SidebarSectionLink.count }.and not_change {+ SidebarUrl.count+ }+ expect(moved_link.reload.linkable_id).to eq(moved_url.id)+ expect(SidebarUrl.exists?(moved_url.id)).to eq(true)+ end++ it "places the link first in the target section" do+ result+ expect(target_section.sidebar_urls.reload.map(&:id)).to eq(+ [moved_url.id, first_target_url.id, second_target_url.id],+ )+ end++ it "removes the link from the source section" do+ expect { result }.to change { source_section.sidebar_urls.reload.map(&:id) }.from(+ [moved_url.id],+ ).to([])+ end++ it "does not log a staff action" do+ expect { result }.not_to change { UserHistory.count }+ end++ it "does not publish a sidebar refresh" do+ expect(messages).to be_empty+ end++ context "with a middle position" do+ let(:position) { 1 }++ it "places the link between the existing target links" do+ result+ expect(target_section.sidebar_urls.reload.map(&:id)).to eq(+ [first_target_url.id, moved_url.id, second_target_url.id],+ )+ end+ end++ context "with no position" do+ let(:position) { nil }++ it "appends the link to the target section" do+ result+ expect(target_section.sidebar_urls.reload.map(&:id)).to eq(+ [first_target_url.id, second_target_url.id, moved_url.id],+ )+ end+ end++ context "with a position beyond the target size" do+ let(:position) { 100 }++ it "appends the link to the target section" do+ result+ expect(target_section.sidebar_urls.reload.map(&:id)).to eq(+ [first_target_url.id, second_target_url.id, moved_url.id],+ )+ end+ end+ end++ context "when the target section is public" do+ fab!(:current_user, :admin)++ before do+ source_section.update!(user: current_user)+ target_section.update!(public: true)+ end++ it { is_expected.to run_successfully }++ it "reassigns the link to the target section's user" do+ expect { result }.to change { moved_link.reload.user_id }.to(Discourse.system_user.id)+ end++ it "logs the staff action for the public section" do+ expect { result }.to change { UserHistory.count }.by(1)+ expect(UserHistory.last).to have_attributes(+ action: UserHistory.actions[:update_public_sidebar_section],+ acting_user_id: current_user.id,+ subject: target_section.title,+ )+ end++ it "publishes a single sidebar refresh" do+ expect(messages.map(&:channel)).to eq(["/refresh-sidebar-sections"])+ end+ end++ context "when both sections are public" do+ fab!(:current_user, :admin)++ before do+ source_section.update!(public: true)+ target_section.update!(public: true)+ end++ it { is_expected.to run_successfully }++ it "logs the staff action for both sections" do+ expect { result }.to change { UserHistory.count }.by(2)+ end++ it "publishes a single sidebar refresh" do+ expect(messages.map(&:channel)).to eq(["/refresh-sidebar-sections"])+ end+ end+ end+enddiff --git a/spec/services/sidebar_section/reorder_links_spec.rb b/spec/services/sidebar_section/reorder_links_spec.rbnew file mode 100644index 00000000000..b48d63fae01--- /dev/null+++ b/spec/services/sidebar_section/reorder_links_spec.rb@@ -0,0 +1,105 @@+# frozen_string_literal: true++RSpec.describe SidebarSection::ReorderLinks do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:section_id) }+ it { is_expected.to validate_presence_of(:links_order) }++ it "coerces links_order values to integers and discards non-numeric ones" do+ contract = described_class.new(links_order: ["1", "junk", 2])+ contract.validate+ expect(contract.links_order).to eq([1, 2])+ end+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:current_user, :user)+ fab!(:section) { Fabricate(:sidebar_section, user: current_user) }+ fab!(:first_url) { Fabricate(:sidebar_url, name: "First", value: "/first") }+ fab!(:second_url) { Fabricate(:sidebar_url, name: "Second", value: "/second") }+ fab!(:first_link) do+ Fabricate(:sidebar_section_link, sidebar_section: section, linkable: first_url)+ end+ fab!(:second_link) do+ Fabricate(:sidebar_section_link, sidebar_section: section, linkable: second_url)+ end++ let(:params) { { section_id:, links_order: } }+ let(:dependencies) { { guardian: } }+ let(:guardian) { current_user.guardian }+ let(:section_id) { section.id }+ let(:links_order) { [second_url.id, first_url.id] }+ let(:messages) { MessageBus.track_publish("/refresh-sidebar-sections") { result } }++ context "when contract is invalid" do+ let(:links_order) { [] }++ it { is_expected.to fail_a_contract }+ end++ context "when section is not found" do+ let(:section_id) { 0 }++ it { is_expected.to fail_to_find_a_model(:section) }+ end++ context "when acting user cannot edit the section" do+ fab!(:current_user, :user)++ it { is_expected.to fail_a_policy(:can_edit_section) }+ end++ context "when links_order does not cover every link" do+ let(:links_order) { [first_url.id] }++ it { is_expected.to fail_a_policy(:order_covers_every_link) }+ end++ context "when everything's ok" do+ it { is_expected.to run_successfully }++ it "applies the requested order" do+ expect { result }.to change { section.sidebar_urls.reload.map(&:id) }.from(+ [first_url.id, second_url.id],+ ).to([second_url.id, first_url.id])+ end++ it "does not log a staff action" do+ expect { result }.not_to change { UserHistory.count }+ end++ it "does not publish a sidebar refresh" do+ expect(messages).to be_empty+ end+ end++ context "when the section is public" do+ fab!(:current_user, :admin)++ before { section.update!(public: true) }++ it { is_expected.to run_successfully }++ it "applies the requested order" do+ expect { result }.to change { section.sidebar_urls.reload.map(&:id) }.to(+ [second_url.id, first_url.id],+ )+ end++ it "logs the staff action" do+ expect { result }.to change { UserHistory.count }.by(1)+ expect(UserHistory.last).to have_attributes(+ action: UserHistory.actions[:update_public_sidebar_section],+ acting_user_id: current_user.id,+ subject: section.title,+ )+ end++ it "publishes a sidebar refresh" do+ expect(messages.map(&:channel)).to eq(["/refresh-sidebar-sections"])+ end+ end+ end+enddiff --git a/spec/support/system_helpers.rb b/spec/support/system_helpers.rbindex fb052365dee..ebde802df7c 100644--- a/spec/support/system_helpers.rb+++ b/spec/support/system_helpers.rb@@ -451,6 +451,63 @@ module SystemHelpersendend+ # A native drag that pauses over an intermediate element before dropping, for+ # a destination that only appears once a drag has dwelt somewhere.+ #+ # `drag_and_drop` cannot express this. Playwright's own drag is one atomic+ # call, so there is no point during it at which to wait.+ #+ # The drag is driven by hand instead. That needs CDP drag interception, or+ # Chromium treats the press as an OS drag and stops reporting the moves after.+ #+ # `over:` is the element to dwell on, `to:` the one to drop on. The block runs+ # while the drag is still open, which is where to wait for what it reveals.+ #+ # Like `drag_and_drop`, this bypasses Capybara's client-settle wait, so assert+ # through a retrying matcher rather than a value read once.+ def drag_and_hold(from:, over:, to:, steps: 10)+ page.driver.with_playwright_page do |pw_page|+ session = pw_page.context.new_cdp_session(pw_page)+ session.send_message("Input.setInterceptDrags", params: { "enabled" => true })++ start_x, start_y = viewport_centre_of(pw_page, from)+ over_x, over_y = viewport_centre_of(pw_page, over)++ pw_page.mouse.move(start_x, start_y)+ pw_page.mouse.down+ # Stepped, so the drag is seen crossing the threshold rather than+ # teleporting past it, and so the dwell sees more than one move.+ pw_page.mouse.move(over_x, over_y, steps: steps)+ end++ begin+ # Outside the driver block, so Capybara's own matchers work normally in it.+ yield if block_given?+ page.driver.with_playwright_page do |pw_page|+ drop_x, drop_y = viewport_centre_of(pw_page, to)+ pw_page.mouse.move(drop_x, drop_y, steps: steps)+ end+ ensure+ # Released even when an in-drag assertion fails, so the example does not+ # run its remaining hooks with the button still held.+ page.driver.with_playwright_page { |pw_page| pw_page.mouse.up }+ end+ end++ # Waited for rather than queried once. `query_selector` returns nil without+ # waiting, so a missing element fails as a NoMethodError naming nothing useful.+ def viewport_centre_of(pw_page, selector)+ node =+ pw_page.wait_for_selector(+ selector,+ state: "visible",+ timeout: Capybara.default_max_wait_time * 1000,+ )+ node.scroll_into_view_if_needed+ box = node.bounding_box+ [box["x"] + box["width"] / 2, box["y"] + box["height"] / 2]+ end+# Drives a press-drag-release with the real mouse, for the surfaces built on# pointer events rather than native drag-and-drop.#diff --git a/spec/system/custom_sidebar_sections_spec.rb b/spec/system/custom_sidebar_sections_spec.rbindex 7ba2ebd79b1..05bd480b330 100644--- a/spec/system/custom_sidebar_sections_spec.rb+++ b/spec/system/custom_sidebar_sections_spec.rb@@ -303,6 +303,93 @@ describe "Custom sidebar sections" doexpect(page).not_to have_css(".sidebar-section-form-link .draggable")end+ it "reorders links in the sidebar with drag and drop" 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")++ rows = "[data-section-name='my-section'] li[data-sidebar-custom-link]"+ expect(page).to have_css("#{rows}[data-drag-source]", count: 2)+ # The row drags as a registered source, so its anchor must not drag too.+ # Checked on the rendered value: the binding only works as a real boolean.+ expect(page).to have_css("#{rows} a[draggable='false']", count: 2)++ # Dropped below the target row's midpoint: its exact center sits on the+ # boundary the insertion index is measured against.+ drag_and_drop(+ source: "#{rows}:first-child",+ target: "#{rows}:last-child",+ target_position: {+ x: 30,+ y: 26,+ },+ )++ expect(page).to have_css("#{rows}:first-child [data-link-name='Sidebar Categories']")+ expect(sidebar.primary_section_links("my-section")).to eq(+ ["Sidebar Categories", "Sidebar Tags"],+ )+ end++ # The browser refuses a drop whose effect mismatches the row's `effectAllowed`,+ # with no `drop` event. A synthetic drag cannot see that, so this must be real.+ it "splits a link out into a new section by dropping it on the zone" 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")++ rows = "[data-section-name='my-section'] li[data-sidebar-custom-link]"+ expect(page).to have_css("#{rows}[data-drag-source]", count: 2)++ drag_and_hold(+ from: "#{rows}:first-child",+ over: ".sidebar-sections",+ to: ".sidebar-link-drop-target",+ ) { expect(page).to have_css(".sidebar-link-drop-target:not(.is-arming)") }++ expect(page).to have_css(".sidebar-section-form-modal")+ expect(find("input[name='link-name']").value).to eq("Sidebar Tags")++ find("input[name='section-name']").fill_in(with: "Split out")+ find("#save-section").click++ expect(page).to have_css("[data-section-name='split-out']")+ expect(sidebar.primary_section_links("split-out")).to eq(["Sidebar Tags"])+ expect(sidebar.primary_section_links("my-section")).to eq(["Sidebar Categories"])+ end++ it "does not make sidebar links draggable 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++ sign_in user+ visit("/latest")+ sidebar.open_on_mobile++ rows = "[data-section-name='my-section'] li[data-sidebar-custom-link]"+ expect(page).to have_css(rows)+ expect(page).not_to have_css("#{rows}[data-drag-source]")+ # With no registered drag to make room for, the attribute is left off and+ # the anchor keeps the browser default.+ expect(page).not_to have_css("#{rows} a[draggable]")+ end+it "does not allow the user to edit public section" dosidebar_section = Fabricate(:sidebar_section, title: "Public section", public: true)sidebar_url_1 = Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags")