Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add sidebar links with drag and drop (#42495)

Sérgio Saquetim750abb41a5df
diff --git a/app/assets/stylesheets/common/base/sidebar-section.scss b/app/assets/stylesheets/common/base/sidebar-section.scss
index f59fb668db1..ff33f7c4b0c 100644
--- a/app/assets/stylesheets/common/base/sidebar-section.scss
+++ b/app/assets/stylesheets/common/base/sidebar-section.scss
@@ -1,6 +1,18 @@
@use "lib/viewport";
.sidebar-section-wrapper {
+ position: relative;
+
+ /* No outline: the insertion line already says where the link lands, and it
+ tracks the pointer, so a box around the section only repeats it. Row hover
+ and active backgrounds go quiet for the duration, since a row under a drag
+ is not one being clicked. */
+
+ &.is-link-drop-active {
+ --d-sidebar-highlight-background: transparent;
+ --d-sidebar-active-background: transparent;
+ }
+
@include viewport.from(sm) {
padding-block: var(--space-1);
border-bottom: 1px solid var(--d-sidebar-section-border-color);
@@ -155,6 +167,24 @@
}
}
+.sidebar-section-link-drop-indicator,
+.sidebar-section-link-wrapper.is-link-drop-before::before {
+ position: absolute;
+ z-index: 1;
+ inset-inline: var(--d-sidebar-row-horizontal-padding);
+ pointer-events: none;
+ border-block-start: 2px solid var(--d-drag-indicator-color);
+}
+
+.sidebar-section-link-drop-indicator {
+ inset-block-end: 0;
+}
+
+.sidebar-section-link-wrapper.is-link-drop-before::before {
+ content: "";
+ inset-block-start: 0;
+}
+
.sidebar-section-header-global-indicator__content {
.d-icon-shield-halved {
padding-right: var(--space-1);
diff --git a/app/assets/stylesheets/common/base/sidebar.scss b/app/assets/stylesheets/common/base/sidebar.scss
index aa8a4882319..520341d38d1 100644
--- a/app/assets/stylesheets/common/base/sidebar.scss
+++ b/app/assets/stylesheets/common/base/sidebar.scss
@@ -67,6 +67,38 @@
}
}
+.sidebar-link-drop-target {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-2);
+ margin-block: var(--space-1);
+ padding: var(--space-3);
+ color: var(--token-color-text-default);
+ background: var(--token-color-surface-selected);
+ border-radius: var(--d-border-radius);
+ font-weight: var(--token-font-weight-semibold);
+ animation: sidebar-link-drop-target-reveal 0.15s ease-out;
+
+ /* Native drag hit-testing honors this, so while it applies the zone cannot
+ take a drop. */
+
+ &.is-arming {
+ pointer-events: none;
+ }
+
+ &.is-active {
+ outline: 2px solid var(--d-drag-indicator-color);
+ outline-offset: -2px;
+ }
+}
+
+@keyframes sidebar-link-drop-target-reveal {
+ from {
+ opacity: 0;
+ }
+}
+
.sidebar-row {
box-sizing: border-box;
height: var(--d-sidebar-row-height);
@@ -96,6 +128,7 @@
@include unselectable;
.sidebar-container {
+ position: relative;
display: flex;
flex-direction: column;
box-sizing: border-box;
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 37f11bc004b..9349a5bc871 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -6282,6 +6282,7 @@ en:
custom:
add: "Add custom section"
edit: "Edit custom section"
+ drop_to_add: "Drop here to add a new section"
save: "Save"
delete: "Delete"
delete_confirm: "Are you sure you want to delete this section?"
@@ -6334,6 +6335,7 @@ en:
other: "Name must be shorter than %{count} characters"
value:
label: "Link"
+ duplicate: "Another link in this section already points here"
validation:
blank: "Link cannot be blank"
maximum:
diff --git a/docs/developer-guides/docs/03-code-internals/29-drag-and-gesture-primitives.md b/docs/developer-guides/docs/03-code-internals/29-drag-and-gesture-primitives.md
index 9cbfc9f07c1..2ce01c31f28 100644
--- a/docs/developer-guides/docs/03-code-internals/29-drag-and-gesture-primitives.md
+++ b/docs/developer-guides/docs/03-code-internals/29-drag-and-gesture-primitives.md
@@ -140,22 +140,22 @@ Accepts element drags and reports where the drop would land.
## Arguments
-| Argument | Type | Purpose |
-| --------------- | -------------------------------------------- | ------------------------------------------------------------- |
-| `accepts` | `string \| string[]` | Which source types engage the target. Omit to accept any. |
-| `adopts` | `NativeDragAdoption \| NativeDragAdoption[]` | Also take browser-started page content. See below. |
-| `acceptsSelf` | `boolean` | `false` refuses a drop whose dragged element is this element. |
-| `position` | `"before" \| "after" \| "inside"` | A fixed position, which wins over midpoint math. |
-| `axis` | `"vertical" \| "horizontal"` | Which midpoint is measured. Defaults to `"vertical"`. |
-| `indicator` | `boolean` | `false` suppresses the indicator class. |
-| `canDrop` | `(feedback) => boolean` | Gate asked while hovering. `false` defers to an ancestor. |
-| `getDropEffect` | `(feedback) => DropEffect` | The cursor feedback the browser shows. |
-| `getData` | `() => object` | Metadata attached to the drag's record of this target. |
-| `getIsSticky` | `() => boolean` | Whether the target stays current after the pointer leaves. |
-| `onDragEnter` | `(event) => void` | This target became the deepest accepted target. |
-| `onDrag` | `(event) => void` | Throttled, while it stays the deepest accepted target. |
-| `onDragLeave` | `(event) => void` | It stopped being the deepest accepted target. |
-| `onDrop` | `(event) => void` | The drag was released here. |
+| Argument | Type | Purpose |
+| ------------- | -------------------------------------------- | ------------------------------------------------------------- |
+| `accepts` | `string \| string[]` | Which source types engage the target. Omit to accept any. |
+| `adopts` | `NativeDragAdoption \| NativeDragAdoption[]` | Also take browser-started page content. See below. |
+| `acceptsSelf` | `boolean` | `false` refuses a drop whose dragged element is this element. |
+| `position` | `"before" \| "after" \| "inside"` | A fixed position, which wins over midpoint math. |
+| `axis` | `"vertical" \| "horizontal"` | Which midpoint is measured. Defaults to `"vertical"`. |
+| `indicator` | `boolean` | `false` suppresses the indicator class. |
+| `canDrop` | `(feedback) => boolean` | Gate asked while hovering. `false` defers to an ancestor. |
+| `dropEffect` | `DropEffect` or `(feedback) => DropEffect` | The cursor feedback the browser shows. |
+| `getData` | `() => object` | Metadata attached to the drag's record of this target. |
+| `getIsSticky` | `() => boolean` | Whether the target stays current after the pointer leaves. |
+| `onDragEnter` | `(event) => void` | This target became the deepest accepted target. |
+| `onDrag` | `(event) => void` | Throttled, while it stays the deepest accepted target. |
+| `onDragLeave` | `(event) => void` | It stopped being the deepest accepted target. |
+| `onDrop` | `(event) => void` | The drag was released here. |
A registered target carries `data-drop-target`.
@@ -245,7 +245,7 @@ sees a drag that began on this page.
| `axis` | `"vertical" \| "horizontal"` | Same, from the pointer against the midpoint. |
It shares every kernel argument with the element target: `canDrop`,
-`getDropEffect`, `getData`, `getIsSticky`, `indicator`, and the four lifecycle
+`dropEffect`, `getData`, `getIsSticky`, `indicator`, and the four lifecycle
callbacks.
Without `position` or `axis` the target is one destination rather than a slot:
@@ -307,15 +307,16 @@ asked, external ones, and tests its own rectangle against the pointer. It
never joins the drop-target hierarchy: no indicator, no positions, and it
composes freely with a real target on the same element.
-| Argument | Type | Purpose |
-| --------------- | ----------------------- | --------------------------------------------------------------------------------- |
-| `types` | `string \| string[]` | Element drag types to watch. Omit to watch all. |
-| `externalKinds` | external kinds or array | External kinds to watch. Omitting it, or naming no kinds, refuses external drags. |
-| `delay` | `number` | Milliseconds of hovering before the dwell fires; defaults to 500. |
-| `canDwell` | `(feedback) => boolean` | Gates candidacy; shares a drop target's `canDrop` feedback shape. |
-| `acceptsSelf` | `boolean` | Whether the element's own drag may dwell. Defaults to `true`. |
-| `onDwell` | `(event) => void` | The drag hovered long enough. |
-| `onDwellEnd` | `(event) => void` | The candidacy ended; the place to undo what `onDwell` did. |
+| Argument | Type | Purpose |
+| --------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
+| `types` | `string \| string[]` | Element drag types to watch. Omit to watch all. |
+| `externalKinds` | external kinds or array | External kinds to watch. Omitting it, or naming no kinds, refuses external drags. |
+| `delay` | `boolean \| number` | Hover before the dwell fires: `true` (default) the standard 500 ms, `false` immediate, or milliseconds. |
+| `leaveDelay` | `boolean \| number` | Grace before a fired dwell is undone on leave: `true` (default) mirrors the entry delay, `false` immediate, or milliseconds. |
+| `canDwell` | `(feedback) => boolean` | Gates candidacy; shares a drop target's `canDrop` feedback shape. |
+| `acceptsSelf` | `boolean` | Whether the element's own drag may dwell. Defaults to `true`. |
+| `onDwell` | `(event) => void` | The drag hovered long enough. |
+| `onDwellEnd` | `(event) => void` | The candidacy ended; the place to undo what `onDwell` did. |
```gjs
<div
diff --git a/frontend/discourse/app/components/modal/sidebar-section-form.gjs b/frontend/discourse/app/components/modal/sidebar-section-form.gjs
index 8ad8c1d8f5c..cd45ad75b9c 100644
--- a/frontend/discourse/app/components/modal/sidebar-section-form.gjs
+++ b/frontend/discourse/app/components/modal/sidebar-section-form.gjs
@@ -21,7 +21,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 { not } from "discourse/truth-helpers";
+import { eq, has, not } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
import DModal from "discourse/ui-kit/d-modal";
import DSelect from "discourse/ui-kit/d-select";
@@ -393,16 +393,21 @@ export default class SidebarSectionForm extends Component {
locale: sectionLocale,
});
} else {
+ const locale = this.siteSettings.default_locale;
+ const link = this.model?.link;
+
return new Section({
links: [
- new SectionLink({
- router: this.router,
- objectId: this.nextObjectId,
- segment: "primary",
- locale: this.siteSettings.default_locale,
- }),
+ link
+ ? this.initLink(link, locale)
+ : new SectionLink({
+ router: this.router,
+ objectId: this.nextObjectId,
+ segment: "primary",
+ locale,
+ }),
],
- locale: this.siteSettings.default_locale,
+ locale,
});
}
}
@@ -553,12 +558,62 @@ export default class SidebarSectionForm extends Component {
return this.transformedModel.links.filter((link) => !link._destroy);
}
+ get initialFocusLinkObjectId() {
+ const index = this.model?.focusLinkIndex;
+ return index === undefined ? undefined : this.activeLinks[index]?.objectId;
+ }
+
+ get modalAutofocus() {
+ return this.model?.focusLinkIndex === undefined;
+ }
+
get activeSecondaryLinks() {
return this.transformedModel.secondaryLinks?.filter(
(link) => !link._destroy
);
}
+ /**
+ * Links whose URL an earlier link in the same section already uses.
+ *
+ * Worth pointing out, since a link dropped onto a section it is already in
+ * looks like nothing happened, but not worth refusing: two links to one place
+ * under different names are a reasonable thing to want. Only the later
+ * occurrence is marked, so the row that was already there does not start
+ * looking like the mistake.
+ */
+ get duplicateLinkObjectIds() {
+ const seen = new Set();
+ const duplicates = new Set();
+
+ for (const link of [
+ ...this.activeLinks,
+ ...(this.activeSecondaryLinks ?? []),
+ ]) {
+ const value = link.value?.trim();
+
+ if (!value) {
+ continue;
+ }
+
+ if (seen.has(value)) {
+ duplicates.add(link.objectId);
+ } else {
+ seen.add(value);
+ }
+ }
+
+ return duplicates;
+ }
+
+ get lastActiveLinkIndex() {
+ return this.activeLinks.length - 1;
+ }
+
+ get lastActiveSecondaryLinkIndex() {
+ return (this.activeSecondaryLinks?.length ?? 0) - 1;
+ }
+
@cached
get activeLocalizations() {
return this.#activeLocalizations(this.transformedModel);
@@ -1158,6 +1213,7 @@ export default class SidebarSectionForm extends Component {
<template>
<DModal
+ @autofocus={{this.modalAutofocus}}
@closeModal={{@closeModal}}
@inline={{@inline}}
@flash={{this.flash}}
@@ -1348,9 +1404,19 @@ export default class SidebarSectionForm extends Component {
</div>
</div>
- {{#each this.activeLinks as |link|}}
+ {{#each this.activeLinks key="objectId" as |link index|}}
<SectionFormLink
@link={{link}}
+ @index={{index}}
+ @lastIndex={{this.lastActiveLinkIndex}}
+ @focusNameInput={{eq
+ link.objectId
+ this.initialFocusLinkObjectId
+ }}
+ @duplicateValue={{has
+ this.duplicateLinkObjectIds
+ link.objectId
+ }}
@deleteLink={{this.deleteLink}}
@reorderCallback={{this.reorder}}
@setDraggedLinkCallback={{this.setDraggedLink}}
@@ -1370,9 +1436,15 @@ export default class SidebarSectionForm extends Component {
{{#if this.transformedModel.sectionType}}
<hr />
<h3>{{i18n "sidebar.sections.custom.more_menu"}}</h3>
- {{#each this.activeSecondaryLinks as |link|}}
+ {{#each this.activeSecondaryLinks key="objectId" as |link index|}}
<SectionFormLink
@link={{link}}
+ @index={{index}}
+ @lastIndex={{this.lastActiveSecondaryLinkIndex}}
+ @duplicateValue={{has
+ this.duplicateLinkObjectIds
+ link.objectId
+ }}
@deleteLink={{this.deleteLink}}
@reorderCallback={{this.reorder}}
@setDraggedLinkCallback={{this.setDraggedLink}}
diff --git a/frontend/discourse/app/components/sidebar.gjs b/frontend/discourse/app/components/sidebar.gjs
index 8d7c8490943..8a4c53e5c46 100644
--- a/frontend/discourse/app/components/sidebar.gjs
+++ b/frontend/discourse/app/components/sidebar.gjs
@@ -1,4 +1,5 @@
import Component from "@glimmer/component";
+import { action } from "@ember/object";
import { service } from "@ember/service";
import PluginOutlet from "discourse/components/plugin-outlet";
import ApiPanels from "discourse/components/sidebar/api-panels";
@@ -7,6 +8,13 @@ import Sections from "discourse/components/sidebar/sections";
import SwitchPanelButtons from "discourse/components/sidebar/switch-panel-buttons";
import bodyClass from "discourse/helpers/body-class";
import { bind } from "discourse/lib/decorators";
+import {
+ WEB_LINK_ADOPTION,
+ WEB_LINK_KINDS,
+ webLinkPayload,
+} from "discourse/lib/sidebar/link-drop";
+import dDragAndDropExternalTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-external-target";
+import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
import { i18n } from "discourse-i18n";
export default class Sidebar extends Component {
@@ -25,6 +33,7 @@ export default class Sidebar extends Component {
willDestroy() {
super.willDestroy(...arguments);
+
if (this.site.mobileView) {
document.removeEventListener("click", this.collapseSidebar);
}
@@ -34,6 +43,26 @@ export default class Sidebar extends Component {
return this.siteSettings.default_sidebar_switch_panel_position === "top";
}
+ get #canAcceptLinkDrop() {
+ return this.currentUser && this.sidebarState.showMainPanel;
+ }
+
+ /**
+ * The target stays registered whatever the sidebar is showing, and refuses
+ * here instead, so a panel switch cannot leave a half-built registration
+ * behind mid-drag.
+ *
+ * Files are their own drag with their own destinations, and this one only
+ * knows what to do with a URL.
+ */
+ @action
+ canDropLink({ source }) {
+ return (
+ Boolean(this.#canAcceptLinkDrop) &&
+ !webLinkPayload(source).containsFiles()
+ );
+ }
+
get switchPanelButtons() {
if (
!this.sidebarState.displaySwitchPanelButtons ||
@@ -72,7 +101,26 @@ export default class Sidebar extends Component {
<template>
{{bodyClass "has-sidebar-page"}}
+ {{! A drop suppressor, not a destination: dragging a link over the sidebar
+ is invited, so a drop that misses the real targets inside must cancel
+ with a no-drop cursor rather than take the browser default of
+ navigating to the dropped URL. No callbacks, so nothing can mistake it
+ for handling the drop. }}
<nav
+ {{dDragAndDropExternalTarget
+ accepts=WEB_LINK_KINDS
+ canDrop=this.canDropLink
+ dropEffect="none"
+ indicator=false
+ }}
+ {{! The same suppression, for a link the browser started dragging from
+ this page rather than from outside the window. }}
+ {{dDragAndDropTarget
+ adopts=WEB_LINK_ADOPTION
+ canDrop=this.canDropLink
+ dropEffect="none"
+ indicator=false
+ }}
id="d-sidebar"
class="sidebar-container"
aria-label={{i18n "sidebar.title"}}
@@ -87,6 +135,7 @@ export default class Sidebar extends Component {
<Sections
@currentUser={{this.currentUser}}
@collapsableSections={{true}}
+ @enableLinkDrop={{true}}
@panel={{this.sidebarState.currentPanel}}
/>
{{else}}
diff --git a/frontend/discourse/app/components/sidebar/common/custom-section.gjs b/frontend/discourse/app/components/sidebar/common/custom-section.gjs
index 94851ae0429..2db8f170cd0 100644
--- a/frontend/discourse/app/components/sidebar/common/custom-section.gjs
+++ b/frontend/discourse/app/components/sidebar/common/custom-section.gjs
@@ -4,7 +4,7 @@ import { service } from "@ember/service";
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 { or } from "discourse/truth-helpers";
+import { and, eq, or } from "discourse/truth-helpers";
import dReplaceEmoji from "discourse/ui-kit/helpers/d-replace-emoji";
import MoreSectionLink from "../more-section-link";
import MoreSectionLinks from "../more-section-links";
@@ -54,10 +54,15 @@ export default class SidebarCustomSection extends Component {
@headerActions={{this.section.headerActions}}
@headerActionsIcon={{this.section.headerActionIcon}}
@hideSectionHeader={{this.section.hideSectionHeader}}
+ @linkDropEnabled={{and @enableLinkDrop this.section.canAcceptLinkDrop}}
+ @onLinkDrop={{this.section.dropLink}}
class={{this.section.dragCss}}
+ as |linkDrop|
>
- {{#each this.section.links as |link|}}
+ {{#each this.section.links as |link index|}}
<SectionLink
+ data-sidebar-custom-link="true"
+ class={{if (eq linkDrop.linkDropIndex index) "is-link-drop-before"}}
@badgeText={{link.badgeText}}
@content={{dReplaceEmoji link.text}}
@currentWhen={{link.currentWhen}}
diff --git a/frontend/discourse/app/components/sidebar/common/custom-sections.gjs b/frontend/discourse/app/components/sidebar/common/custom-sections.gjs
index 77fb068dc70..bcbfbcce235 100644
--- a/frontend/discourse/app/components/sidebar/common/custom-sections.gjs
+++ b/frontend/discourse/app/components/sidebar/common/custom-sections.gjs
@@ -22,6 +22,7 @@ export default class SidebarCustomSections extends Component {
<CustomSection
@sectionData={{section}}
@collapsable={{@collapsable}}
+ @enableLinkDrop={{@enableLinkDrop}}
@toggleNavigationMenu={{@toggleNavigationMenu}}
/>
{{/each}}
diff --git a/frontend/discourse/app/components/sidebar/section-form-link.gjs b/frontend/discourse/app/components/sidebar/section-form-link.gjs
index 7c01ceed1cb..b49abc7f014 100644
--- a/frontend/discourse/app/components/sidebar/section-form-link.gjs
+++ b/frontend/discourse/app/components/sidebar/section-form-link.gjs
@@ -11,6 +11,7 @@ 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 dIcon from "discourse/ui-kit/helpers/d-icon";
+import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";
import { i18n } from "discourse-i18n";
export default class SectionFormLink extends Component {
@@ -123,6 +124,7 @@ export default class SectionFormLink extends Component {
<div class="input-group" role="cell">
{{! eslint-disable-next-line ember/template-no-nested-interactive }}
<Input
+ {{(if @focusNameInput (modifier dAutoFocus selectText=true))}}
{{on "input" (withEventValue (fn (mut @link.name)))}}
@type="text"
@value={{@link.name}}
@@ -154,6 +156,12 @@ export default class SectionFormLink extends Component {
<div role="alert" aria-live="assertive" class="value warning">
{{@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>
diff --git a/frontend/discourse/app/components/sidebar/section.gjs b/frontend/discourse/app/components/sidebar/section.gjs
index 6a537d4700f..65a44089072 100644
--- a/frontend/discourse/app/components/sidebar/section.gjs
+++ b/frontend/discourse/app/components/sidebar/section.gjs
@@ -1,5 +1,6 @@
import Component from "@glimmer/component";
-import { fn } from "@ember/helper";
+import { tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
@@ -13,10 +14,18 @@ import {
getCollapsedSidebarSectionKey,
getSidebarSectionContentId,
} from "discourse/lib/sidebar/helpers";
+import {
+ WEB_LINK_ADOPTION,
+ WEB_LINK_KINDS,
+ webLinkPayload,
+} from "discourse/lib/sidebar/link-drop";
import DButton from "discourse/ui-kit/d-button";
import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
+import dDragAndDropExternalTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-external-target";
+import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
+import dDragDwell from "discourse/ui-kit/modifiers/d-drag-dwell";
import { i18n } from "discourse-i18n";
import SectionHeader from "./section-header";
@@ -25,11 +34,18 @@ export default class SidebarSection extends Component {
@service router;
@service sidebarState;
+ @tracked linkDropActive = false;
+ @tracked linkDropIndex;
+ @tracked linkDropLinkCount = 0;
+
sidebarSectionContentId = getSidebarSectionContentId(this.args.sectionName);
collapsedSidebarSectionKey = getCollapsedSidebarSectionKey(
this.args.sectionName
);
+ /** Whether this section is only open because a drag asked it to be. */
+ #openedForDrag = false;
+
constructor() {
super(...arguments);
@@ -39,6 +55,7 @@ export default class SidebarSection extends Component {
willDestroy() {
super.willDestroy(...arguments);
+ this.#collapseIfOpenedForDrag();
this.router.off("routeDidChange", this, this.expandIfActive);
this.args.willDestroy?.();
@@ -147,6 +164,123 @@ export default class SidebarSection extends Component {
}
}
+ get linkDropAtEnd() {
+ return this.linkDropActive && this.linkDropIndex === this.linkDropLinkCount;
+ }
+
+ /**
+ * Files are their own drag with their own destinations, and a section only
+ * knows what to do with a URL. Gated here rather than by leaving the target
+ * off, so a section that becomes droppable mid-drag does not have to register
+ * one halfway through.
+ */
+ @action
+ canDropLink({ source }) {
+ return (
+ Boolean(this.args.linkDropEnabled) &&
+ !webLinkPayload(source).containsFiles()
+ );
+ }
+
+ /**
+ * Tracks where in this section's links a drop would land.
+ *
+ * The section is the drop target, not the rows: a link row is not somewhere a
+ * drop can land in its own right, it only marks an offset within the section
+ * the drop is already going to. So the position is measured here against the
+ * rows rather than delegated to a target on each of them.
+ */
+ @action
+ trackLinkDrop({ 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();
+
+ if (!this.linkDropActive) {
+ this.linkDropIndex = undefined;
+ return;
+ }
+
+ if (!this.displaySectionContent) {
+ // Reporting a position here would be inventing one: there is nothing on
+ // screen for the pointer to be above or below, and an index of 0 would
+ // put the link ahead of links the user cannot see. Leaving it unset
+ // appends, until dwelling opens the section and the rows can be measured.
+ this.linkDropIndex = undefined;
+ this.linkDropLinkCount = 0;
+ return;
+ }
+
+ const links = Array.from(
+ element.querySelectorAll("[data-sidebar-custom-link]")
+ );
+ const { clientY } = location.current.input;
+ const index = links.findIndex((link) => {
+ const { top, height } = link.getBoundingClientRect();
+ return clientY < top + height / 2;
+ });
+
+ this.linkDropLinkCount = links.length;
+ this.linkDropIndex = index === -1 ? links.length : index;
+ }
+
+ @action
+ clearLinkDrop() {
+ this.linkDropLinkCount = 0;
+ this.linkDropActive = false;
+ this.linkDropIndex = undefined;
+ }
+
+ @action
+ dropLink({ source }) {
+ const linkDropIndex = this.linkDropIndex;
+ this.clearLinkDrop();
+ // 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);
+ }
+
+ /**
+ * Arms the open-on-hover dwell: only for a drag carrying a real URL, and
+ * only while this section is closed. An open section has nothing to reveal.
+ */
+ @action
+ canDwellToOpen({ source }) {
+ return (
+ !this.displaySectionContent &&
+ this.canDropLink({ source }) &&
+ webLinkPayload(source).containsURLs()
+ );
+ }
+
+ /**
+ * Opens this section once a link has dwelled over it long enough, the way a
+ * folder opens under a file held over it.
+ *
+ * Uses the transient active-expansion rather than the collapse toggle, so a
+ * drag that wanders off again leaves no trace in the stored collapsed state.
+ */
+ @action
+ openForLinkDwell() {
+ this.#openedForDrag = true;
+ this.activeExpanded = true;
+ }
+
+ /**
+ * Closes the section again when the dwell ends without a drop landing in
+ * it. A drop here keeps it open: the link the user just added is inside,
+ * and closing would hide the result of their own drop.
+ */
+ @action
+ endLinkDwell({ droppedHere }) {
+ if (droppedHere) {
+ this.#openedForDrag = false;
+ return;
+ }
+
+ this.#collapseIfOpenedForDrag();
+ }
+
get headerCaretIcon() {
return this.displaySectionContent ? "angle-down" : "angle-right";
}
@@ -167,14 +301,51 @@ export default class SidebarSection extends Component {
return this.args.displaySection;
}
+ #collapseIfOpenedForDrag() {
+ if (this.#openedForDrag) {
+ this.#openedForDrag = false;
+ this.activeExpanded = false;
+ }
+ }
+
<template>
{{#if this.displaySection}}
<div
{{didInsert this.setExpandedState}}
+ {{dDragAndDropExternalTarget
+ accepts=WEB_LINK_KINDS
+ canDrop=this.canDropLink
+ dropEffect="copy"
+ indicator=false
+ onDragEnter=this.trackLinkDrop
+ onDrag=this.trackLinkDrop
+ onDragLeave=this.clearLinkDrop
+ onDrop=this.dropLink
+ }}
+ {{! The same drop, for a link the browser started dragging from this
+ page rather than from outside the window. }}
+ {{dDragAndDropTarget
+ adopts=WEB_LINK_ADOPTION
+ canDrop=this.canDropLink
+ dropEffect="copy"
+ indicator=false
+ onDragEnter=this.trackLinkDrop
+ onDrag=this.trackLinkDrop
+ onDragLeave=this.clearLinkDrop
+ onDrop=this.dropLink
+ }}
+ {{dDragDwell
+ types=WEB_LINK_ADOPTION.type
+ externalKinds=WEB_LINK_KINDS
+ canDwell=this.canDwellToOpen
+ onDwell=this.openForLinkDwell
+ onDwellEnd=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"
@@ -265,9 +436,16 @@ export default class SidebarSection extends Component {
id={{this.sidebarSectionContentId}}
class="sidebar-section-content"
>
- {{yield}}
+ {{yield (hash linkDropIndex=this.linkDropIndex)}}
</ul>
{{/if}}
+
+ {{#if this.linkDropAtEnd}}
+ <div
+ class="sidebar-section-link-drop-indicator"
+ aria-hidden="true"
+ ></div>
+ {{/if}}
</div>
{{/if}}
</template>
diff --git a/frontend/discourse/app/components/sidebar/sections.gjs b/frontend/discourse/app/components/sidebar/sections.gjs
index 56f46d068cd..0b6141d1be1 100644
--- a/frontend/discourse/app/components/sidebar/sections.gjs
+++ b/frontend/discourse/app/components/sidebar/sections.gjs
@@ -5,6 +5,7 @@ const SidebarSections = <template>
{{#if @currentUser}}
<UserSections
@collapsableSections={{@collapsableSections}}
+ @enableLinkDrop={{@enableLinkDrop}}
@panel={{@panel}}
@hideApiSections={{@hideApiSections}}
@toggleNavigationMenu={{@toggleNavigationMenu}}
diff --git a/frontend/discourse/app/components/sidebar/user/sections.gjs b/frontend/discourse/app/components/sidebar/user/sections.gjs
index 7c75f716a17..2dffbebcfe4 100644
--- a/frontend/discourse/app/components/sidebar/user/sections.gjs
+++ b/frontend/discourse/app/components/sidebar/user/sections.gjs
@@ -1,22 +1,190 @@
import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+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 discourseLater from "discourse/lib/later";
+import {
+ extractDroppedWebLink,
+ WEB_LINK_ADOPTION,
+ WEB_LINK_KINDS,
+ webLinkPayload,
+} from "discourse/lib/sidebar/link-drop";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import dDragAndDropAutoScroll from "discourse/ui-kit/modifiers/d-drag-and-drop-auto-scroll";
+import dDragAndDropExternalTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-external-target";
+import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
+import dDragDwell from "discourse/ui-kit/modifiers/d-drag-dwell";
+import { i18n } from "discourse-i18n";
import ApiSections from "../api-sections";
import CategoriesSection from "./categories-section";
import CustomSections from "./custom-sections";
import TagsSection from "./tags-section";
+/**
+ * How long the revealed drop zone stays inert. Revealing shifts everything
+ * below it down, so a pointer resting there would land inside the zone the
+ * moment it appears; the beat lets the user see it before it can take a drop.
+ */
+const ZONE_ARM_DELAY = 250;
+
export default class SidebarUserSections extends Component {
@service currentUser;
+ @service modal;
+
+ /** Whether the new-section drop zone is on screen. */
+ @tracked zoneRevealed = false;
+
+ /** Whether the zone can take a drop yet. See `ZONE_ARM_DELAY`. */
+ @tracked zoneArmed = false;
+
+ /** Whether the dragged link is over the zone. */
+ @tracked zoneHovered = false;
+
+ #armTimer = null;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ cancel(this.#armTimer);
+ }
+
+ /**
+ * Arms the reveal dwell: only where link drop is enabled at all, and only
+ * for a drag that declares a real URL. A drag carrying only text may well
+ * turn out to hold nothing droppable.
+ */
+ @action
+ canDwellForNewSection({ source }) {
+ const payload = webLinkPayload(source);
+ return (
+ Boolean(this.args.enableLinkDrop) &&
+ payload.containsURLs() &&
+ !payload.containsFiles()
+ );
+ }
+
+ @action
+ revealZone() {
+ this.zoneRevealed = true;
+ this.#armTimer = discourseLater(() => {
+ this.zoneArmed = true;
+ }, ZONE_ARM_DELAY);
+ }
+
+ /**
+ * Hides the zone for every way the dwell ends: the drop, if there was one,
+ * has already been dispatched to its target by the time the dwell monitor
+ * reports the drag over.
+ */
+ @action
+ hideZone() {
+ cancel(this.#armTimer);
+ this.#armTimer = null;
+ this.zoneRevealed = false;
+ this.zoneArmed = false;
+ this.zoneHovered = false;
+ }
+
+ @action
+ trackZoneHover() {
+ this.zoneHovered = true;
+ }
+
+ @action
+ clearZoneHover() {
+ this.zoneHovered = false;
+ }
+
+ /**
+ * Files are their own drag with their own destinations, and this zone only
+ * knows what to do with a URL.
+ */
+ @action
+ canDropLink({ source }) {
+ return !webLinkPayload(source).containsFiles();
+ }
+
+ @action
+ createSectionFromLink({ source }) {
+ const link = extractDroppedWebLink(webLinkPayload(source));
+ if (!link) {
+ return;
+ }
+
+ // No focused link: the link arrived filled in, and the title is the one
+ // field the new section still needs, so the form's default focus lands
+ // there.
+ this.modal.show(SidebarSectionForm, {
+ model: { link },
+ });
+ }
<template>
- <div class="sidebar-sections">
+ {{! This is the element that scrolls, so a link dragged in can only reach a
+ section below the fold if the scrolling happens here. Both origins are
+ named, since a drag from the page and one from outside the window arrive
+ through different adapters. }}
+ <div
+ class="sidebar-sections"
+ {{dDragAndDropAutoScroll
+ types=WEB_LINK_ADOPTION.type
+ externalKinds=WEB_LINK_KINDS
+ }}
+ {{dDragDwell
+ types=WEB_LINK_ADOPTION.type
+ externalKinds=WEB_LINK_KINDS
+ canDwell=this.canDwellForNewSection
+ onDwell=this.revealZone
+ onDwellEnd=this.hideZone
+ }}
+ >
<BlockOutlet @name="sidebar-blocks" />
<CustomSections
@collapsable={{@collapsableSections}}
+ @enableLinkDrop={{@enableLinkDrop}}
@toggleNavigationMenu={{@toggleNavigationMenu}}
/>
+ {{#if this.zoneRevealed}}
+ {{! Where a section created from the drop would go: after the last
+ custom section. Pointer-only, like the drag it serves; creating a
+ section by keyboard keeps its own path. }}
+ <div
+ class={{dConcatClass
+ "sidebar-link-drop-target"
+ (unless this.zoneArmed "is-arming")
+ (if this.zoneHovered "is-active")
+ }}
+ aria-hidden="true"
+ {{dDragAndDropExternalTarget
+ accepts=WEB_LINK_KINDS
+ canDrop=this.canDropLink
+ dropEffect="copy"
+ indicator=false
+ onDragEnter=this.trackZoneHover
+ onDragLeave=this.clearZoneHover
+ onDrop=this.createSectionFromLink
+ }}
+ {{! The same drop, for a link the browser started dragging from this
+ page rather than from outside the window. }}
+ {{dDragAndDropTarget
+ adopts=WEB_LINK_ADOPTION
+ canDrop=this.canDropLink
+ dropEffect="copy"
+ indicator=false
+ onDragEnter=this.trackZoneHover
+ onDragLeave=this.clearZoneHover
+ onDrop=this.createSectionFromLink
+ }}
+ >
+ {{dIcon "plus"}}
+ <span>{{i18n "sidebar.sections.custom.drop_to_add"}}</span>
+ </div>
+ {{/if}}
+
<CategoriesSection
@collapsable={{@collapsableSections}}
@toggleNavigationMenu={{@toggleNavigationMenu}}
diff --git a/frontend/discourse/app/lib/-internals/drag-and-drop/drag-dwell.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/drag-dwell.ts
index 20f7c74006a..8a02ba772a7 100644
--- a/frontend/discourse/app/lib/-internals/drag-and-drop/drag-dwell.ts
+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/drag-dwell.ts
@@ -5,7 +5,7 @@ import discourseLater from "discourse/lib/later";
const EMPTY = Symbol("empty drag dwell");
/** The dwell delay used when the consumer does not pick one. */
-const DEFAULT_DELAY = 500;
+export const DEFAULT_DRAG_DWELL_DELAY = 500;
/** Options for {@link createDragDwell}. */
export interface DragDwellOptions<Target> {
@@ -76,7 +76,12 @@ export interface DragDwell<Target> {
export default function createDragDwell<Target>(
options: DragDwellOptions<Target>
): DragDwell<Target> {
- const { delay = DEFAULT_DELAY, destroyable, identity, onDwell } = options;
+ const {
+ delay = DEFAULT_DRAG_DWELL_DELAY,
+ destroyable,
+ identity,
+ onDwell,
+ } = options;
let currentKey: unknown | typeof EMPTY = EMPTY;
let latestTarget: Target | null = null;
let timer: ReturnType<typeof discourseLater> | null = null;
diff --git a/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts
index 794caed3064..aaf2423638d 100644
--- a/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts
+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts
@@ -15,8 +15,15 @@ export type DragLocation = DragLocationHistory;
/** Where a drop would land relative to its target. */
export type DropPosition = "before" | "after" | "inside";
-/** The cursor feedback the browser shows for a drop. */
-export type DropEffect = "copy" | "link" | "move";
+/**
+ * The cursor feedback the browser shows for a drop.
+ *
+ * `"none"` refuses the drop at the cursor: the browser cancels the drag at
+ * release instead of firing a drop event, so the target's `onDrop` never runs
+ * and the browser's own default (such as navigating to a dropped URL) is
+ * suppressed.
+ */
+export type DropEffect = "copy" | "link" | "move" | "none";
/** How a target decides where a drop would land. */
export interface DropPositionOptions {
@@ -63,8 +70,13 @@ export interface DropTargetKernelArgs<Source> extends DropPositionOptions {
*/
canDrop?: (feedback: DropTargetKernelFeedback<Source>) => boolean | void;
- /** Determines the cursor feedback browsers show during the drag. */
- getDropEffect?: (feedback: DropTargetKernelFeedback<Source>) => DropEffect;
+ /**
+ * The cursor feedback browsers show during the drag: a fixed effect, or a
+ * function consulted with the drag's feedback when the effect depends on it.
+ */
+ dropEffect?:
+ | DropEffect
+ | ((feedback: DropTargetKernelFeedback<Source>) => DropEffect);
/** Metadata attached to the drag's record of this target under `.data`. */
getData?: () => object;
@@ -127,7 +139,9 @@ export type DropTargetRegistrationArgs<Payload> = {
getData: (
args: LibraryFeedbackArgs<Payload>
) => Record<string | symbol, unknown>;
- getDropEffect: (args: LibraryFeedbackArgs<Payload>) => DropEffect | undefined;
+ getDropEffect: (
+ args: LibraryFeedbackArgs<Payload>
+ ) => Exclude<DropEffect, "none"> | undefined;
getIsSticky: (args: LibraryFeedbackArgs<Payload>) => boolean;
onDropTargetChange: (args: LibraryEventArgs<Payload>) => void;
onDragEnter: (args: LibraryEventArgs<Payload>) => void;
@@ -394,13 +408,17 @@ export function registerDropTargetKernel<Payload, Source>({
unknown
>,
getDropEffect: ({ source, input }) =>
- consumerMayThrow(() =>
- getArgs().getDropEffect?.({
- source: decorateSource(source),
- input,
- element,
- })
- ),
+ // The library's type bans "none" so a target cannot opt a nested stack
+ // out of its drop by accident; a suppressor target opts out on purpose,
+ // and the runtime assigns the value to `dataTransfer.dropEffect`
+ // verbatim. The cast is the one place that deviation crosses into the
+ // library.
+ consumerMayThrow(() => {
+ const dropEffect = getArgs().dropEffect;
+ return typeof dropEffect === "function"
+ ? dropEffect({ source: decorateSource(source), input, element })
+ : dropEffect;
+ }) as Exclude<DropEffect, "none"> | undefined,
getIsSticky: () =>
consumerMayThrow(() => getArgs().getIsSticky?.() === true, false),
onDragEnter: ({ source, location }) =>
diff --git a/frontend/discourse/app/lib/sidebar/link-drop.js b/frontend/discourse/app/lib/sidebar/link-drop.js
new file mode 100644
index 00000000000..95f737d1e09
--- /dev/null
+++ b/frontend/discourse/app/lib/sidebar/link-drop.js
@@ -0,0 +1,177 @@
+import { SIDEBAR_URL } from "discourse/lib/constants";
+
+/**
+ * The external drag kinds a dragged-in web link can arrive as, for a target's
+ * `accepts` filter. Broader than the URL types alone because some sources
+ * expose a link only as HTML or as plain text.
+ */
+export const WEB_LINK_KINDS = ["urls", "html", "text"];
+
+/**
+ * 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 drag
+ * source, and there are far too many kinds to.
+ *
+ * Matches on the anchor rather than on the payload's declared kinds: a web link
+ * has to accept plain text, since some sources publish a URL only that way, and
+ * a dragged text selection carries plain text too. Requiring an `http(s)` anchor
+ * is what separates them.
+ */
+export const WEB_LINK_ADOPTION = {
+ type: "web-link",
+ match: ({ element }) => {
+ const anchor = element.closest("a[href]");
+ if (!anchor) {
+ return false;
+ }
+ try {
+ return ["http:", "https:"].includes(new URL(anchor.href).protocol);
+ } catch {
+ return false;
+ }
+ },
+};
+
+/**
+ * The native payload, wherever the drag came from.
+ *
+ * An external drop target hands its payload directly; an adopted one carries it
+ * on `native`, because the rest of that source describes an element drag. Both
+ * read the same from here on.
+ *
+ * @param {Object} source - The source a drop target reported.
+ */
+export function webLinkPayload(source) {
+ return source.native ?? source;
+}
+
+/**
+ * Turns an incoming external drag into a sidebar link, or nothing when it
+ * carries no usable web URL.
+ *
+ * Reads the payload through the drop target's decorated source rather than a
+ * raw `DataTransfer`, so the URL types are already parsed: comment lines are
+ * stripped from a uri-list, and Firefox's alternating URL/title format is
+ * reduced to its URLs. What is left here is deciding which candidate to take
+ * and what to call it.
+ *
+ * @param {Object} source - The decorated external drag payload.
+ * @returns {Object|undefined} A link ready for the section form.
+ */
+export function extractDroppedWebLink(source) {
+ if (!source) {
+ return;
+ }
+
+ const htmlLink = linkFromHtml(source.getHTML());
+ const firefoxNames = firefoxUrlNames(source);
+ const candidate = [
+ ...source.getURLs().map((value, index) => ({
+ value,
+ // A uri-list carries no titles, so the dragged anchor's own text names its
+ // first entry. Firefox sends titles of its own, which pair off by index.
+ name: firefoxNames[index] ?? (index === 0 ? htmlLink?.name : undefined),
+ })),
+ htmlLink,
+ { value: (source.getText() || "").trim() },
+ ]
+ .filter(Boolean)
+ .find(({ value }) => validWebUrl(value));
+
+ if (!candidate) {
+ return;
+ }
+
+ const value = validWebUrl(candidate.value);
+
+ return {
+ icon: "link",
+ // Named from the absolute URL, since the hostname is the fallback name and
+ // stripping it first would leave nothing to fall back to.
+ name: suitableName(candidate.name) || defaultName(value),
+ value: withoutOwnHost(value),
+ segment: "primary",
+ };
+}
+
+/**
+ * Titles from Firefox's own URL format, which alternates URL and title lines.
+ *
+ * Only consulted when the standard type is absent, because that is the same
+ * order the URLs were resolved in: reading titles from one format while the
+ * URLs came from the other would pair each link with a stranger's name.
+ */
+function firefoxUrlNames(source) {
+ if (source.getStringData("text/uri-list") != null) {
+ return [];
+ }
+
+ const raw = source.getStringData("text/x-moz-url");
+ if (!raw) {
+ return [];
+ }
+
+ return raw
+ .split("\n")
+ .filter((_, index) => index % 2 === 1)
+ .map((line) => line.trim());
+}
+
+function linkFromHtml(value) {
+ if (!value) {
+ return;
+ }
+
+ const link = new DOMParser()
+ .parseFromString(value, "text/html")
+ .querySelector("a[href]");
+
+ if (!link) {
+ return;
+ }
+
+ return {
+ value: link.getAttribute("href"),
+ name: link.textContent.trim(),
+ };
+}
+
+function validWebUrl(value) {
+ if (!value) {
+ return;
+ }
+
+ try {
+ const url = new URL(value);
+ return ["http:", "https:"].includes(url.protocol) ? url.href : undefined;
+ } catch {
+ return;
+ }
+}
+
+/**
+ * Reduces a link to this same site to a path.
+ *
+ * The server does this on save regardless, so leaving it absolute would only
+ * mean showing the user a URL in the form and storing a different one. A path
+ * also keeps working when the site is reached by another hostname.
+ */
+function withoutOwnHost(value) {
+ const url = new URL(value);
+
+ if (url.host !== window.location.host) {
+ return value;
+ }
+
+ return `${url.pathname}${url.search}${url.hash}`;
+}
+
+function suitableName(value) {
+ const name = value?.replace(/\s+/g, " ").trim();
+ return name && name.length <= SIDEBAR_URL.max_name_length ? name : undefined;
+}
+
+function defaultName(value) {
+ const hostname = new URL(value).hostname.replace(/^www\./, "");
+ return hostname || value;
+}
diff --git a/frontend/discourse/app/lib/sidebar/section.js b/frontend/discourse/app/lib/sidebar/section.js
index 06ae423f957..15a4572417e 100644
--- a/frontend/discourse/app/lib/sidebar/section.js
+++ b/frontend/discourse/app/lib/sidebar/section.js
@@ -4,7 +4,9 @@ import { service } from "@ember/service";
import { isPresent } from "@ember/utils";
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 { extractDroppedWebLink } from "discourse/lib/sidebar/link-drop";
import SectionLink from "discourse/lib/sidebar/section-link";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import { unicodeSlugify } from "discourse/lib/utilities";
@@ -39,22 +41,75 @@ export default class Section {
return this.section.public && this.currentUser?.staff;
}
+ /**
+ * Whether the current user may change this section's links at all. A public
+ * section is an admin's to edit; anyone else only owns their own.
+ */
+ get #canEditLinks() {
+ return !this.section.public || this.currentUser?.admin;
+ }
+
+ /**
+ * Dropping a link onto a section is a way of editing it, so it follows the
+ * same permission. Offering a section that cannot be edited would leave an
+ * admin dragging onto a public section and being handed a new one instead.
+ *
+ * A built-in section is excluded on top of that: its links come from the
+ * server and are not the user's to add to.
+ */
+ get canAcceptLinkDrop() {
+ return Boolean(this.#canEditLinks) && !this.section.section_type;
+ }
+
+ async openForm(link, linkDropIndex) {
+ const json = await ajax(`/sidebar_sections/${this.section.id}.json`).catch(
+ popupAjaxError
+ );
+
+ if (!json) {
+ return;
+ }
+
+ const section = json.sidebar_section;
+ let focusLinkIndex;
+
+ if (link) {
+ const insertionIndex = Math.min(
+ Math.max(linkDropIndex ?? section.links.length, 0),
+ section.links.length
+ );
+ focusLinkIndex = section.links
+ .slice(0, insertionIndex)
+ .filter((sectionLink) => sectionLink.segment === "primary").length;
+ section.links.splice(insertionIndex, 0, {
+ ...link,
+ locale: section.locale,
+ });
+ }
+
+ return this.modal.show(SidebarSectionForm, {
+ model: {
+ focusLinkIndex,
+ hideSectionHeader: this.hideSectionHeader,
+ section,
+ },
+ });
+ }
+
+ @bind
+ dropLink(source, linkDropIndex) {
+ const link = extractDroppedWebLink(source);
+
+ if (link) {
+ return this.openForm(link, linkDropIndex);
+ }
+ }
+
get headerActions() {
- if (!this.section.public || this.currentUser?.admin) {
+ if (this.#canEditLinks) {
return [
{
- action: async () => {
- const json = await ajax(
- `/sidebar_sections/${this.section.id}.json`
- );
-
- return this.modal.show(SidebarSectionForm, {
- model: {
- hideSectionHeader: this.hideSectionHeader,
- section: json.sidebar_section,
- },
- });
- },
+ action: () => this.openForm(),
title: i18n("sidebar.sections.custom.edit"),
},
];
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts
index 33bc58f8cf8..f20b97a0422 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts
@@ -16,7 +16,7 @@ import {
} from "discourse/lib/-internals/drag-and-drop/external-vocabulary";
import type { Axis } from "discourse/lib/geometry";
-/** What a synchronous gate (`canDrop`, `getDropEffect`) is asked about. */
+/** What a synchronous gate (`canDrop`, a `dropEffect` function) is asked about. */
export type ExternalDropTargetFeedback =
DropTargetKernelFeedback<ExternalDragPayload>;
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-source.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-source.ts
index 676db1bab0b..83012fb0a2c 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-source.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-source.ts
@@ -81,7 +81,7 @@ interface DDragAndDropSourceSignature {
* browser badging the pointer with its copy offer.
*
* A source whose drop duplicates wants `"copyMove"`: a target's
- * `getDropEffect` may only return an effect this permits.
+ * `dropEffect` may only name an effect this permits.
*/
effectAllowed?: DataTransfer["effectAllowed"];
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts
index 2e043f198b9..cd13f9d3cf5 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts
@@ -40,7 +40,7 @@ export {
*/
export type DropTargetSource = NormalizedDragSource;
-/** What a synchronous gate (`canDrop`, `getDropEffect`) is asked about. */
+/** What a synchronous gate (`canDrop`, a `dropEffect` function) is asked about. */
export type DropTargetFeedback = DropTargetKernelFeedback<DropTargetSource>;
/** What a lifecycle callback is told. */
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.ts
index 07ac9e2d2d3..c749a0f8762 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.ts
@@ -1,4 +1,5 @@
import { destroy } from "@ember/destroyable";
+import { cancel } from "@ember/runloop";
import type { ElementDragPayload } from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter";
import type { ExternalDragPayload as NativeExternalDragPayload } from "@atlaskit/pragmatic-drag-and-drop/adapter/external-adapter-types";
import { monitorForElements } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
@@ -7,6 +8,7 @@ import type { CleanupFn } from "@atlaskit/pragmatic-drag-and-drop/types";
import { modifier } from "ember-modifier";
import { consumerMayThrow } from "discourse/lib/-internals/drag-and-drop/consumer-may-throw";
import createDragDwell, {
+ DEFAULT_DRAG_DWELL_DELAY,
type DragDwell,
} from "discourse/lib/-internals/drag-and-drop/drag-dwell";
import type {
@@ -25,9 +27,11 @@ import {
normalizeDragSource,
} from "discourse/lib/-internals/drag-and-drop/vocabulary";
import { makeArray } from "discourse/lib/helpers";
+import discourseLater from "discourse/lib/later";
export {
default as createDragDwell,
+ DEFAULT_DRAG_DWELL_DELAY,
type DragDwell,
type DragDwellOptions,
} from "discourse/lib/-internals/drag-and-drop/drag-dwell";
@@ -120,10 +124,23 @@ interface DDragDwellSignature {
externalKinds?: ExternalDragKind | ExternalDragKind[];
/**
- * Milliseconds of qualifying hover before `onDwell` fires. Defaults to
- * `500`. Sampled when the first candidacy arms.
+ * How long a qualifying hover lasts before `onDwell` fires. `true`, the
+ * default, is the standard 500 ms; `false` fires on the first qualifying
+ * frame; a number is the wait in milliseconds. Sampled when the first
+ * candidacy arms.
*/
- delay?: number;
+ delay?: boolean | number;
+
+ /**
+ * Grace before a fired dwell is undone once the drag leaves the
+ * element. `true`, the default, mirrors the entry delay, or the
+ * standard 500 ms when entry is immediate; `false` ends it in the
+ * leaving frame; a number is the grace in milliseconds. A drag
+ * returning within the grace keeps the dwell as if it never left, and
+ * a drag ending during it reports `drag-ended` instead. A candidacy
+ * that has not fired yet ends immediately either way.
+ */
+ leaveDelay?: boolean | number;
/**
* Whether a drag hovering the element may start or continue a pending
@@ -159,6 +176,39 @@ interface DDragDwellSignature {
*/
export type DragDwellArgs = DDragDwellSignature["Args"]["Named"];
+/**
+ * The entry delay in milliseconds: `true` and omission are the standard
+ * delay, `false` is immediate, and a number stands as given.
+ */
+export function resolveDwellDelay(delay: boolean | number | undefined): number {
+ if (delay === false) {
+ return 0;
+ }
+ if (delay === true || delay == null) {
+ return DEFAULT_DRAG_DWELL_DELAY;
+ }
+ return delay;
+}
+
+/**
+ * The leave grace in milliseconds: `true` and omission mirror the resolved
+ * entry delay and fall back to the standard delay when entry is immediate,
+ * `false` is immediate, and a number stands as given.
+ */
+export function resolveDwellLeaveDelay(
+ leaveDelay: boolean | number | undefined,
+ delay: boolean | number | undefined
+): number {
+ if (leaveDelay === false) {
+ return 0;
+ }
+ if (leaveDelay === true || leaveDelay == null) {
+ const entry = resolveDwellDelay(delay);
+ return entry > 0 ? entry : DEFAULT_DRAG_DWELL_DELAY;
+ }
+ return leaveDelay;
+}
+
function isWithin(input: DragInput, clientRect: DOMRect) {
return (
input.clientX >= clientRect.x &&
@@ -192,8 +242,16 @@ export function registerDragDwell(
let hovering = false;
let fired = false;
let lastEvent: DragDwellEvent | null = null;
+ let pendingLeave: ReturnType<typeof discourseLater> | null = null;
let isDestroying = false;
+ const cancelPendingLeave = () => {
+ if (pendingLeave) {
+ cancel(pendingLeave);
+ pendingLeave = null;
+ }
+ };
+
const passesGate = (event: DragDwellEvent) => {
const callback = getArgsRef().canDwell;
if (!callback) {
@@ -212,10 +270,9 @@ export function registerDragDwell(
return dwell;
}
- const { delay } = getArgsRef();
dwell = createDragDwell<DragDwellEvent>({
destroyable: lifetime,
- delay,
+ delay: resolveDwellDelay(getArgsRef().delay),
identity: () => element,
onDwell: () => {
if (isDestroying || !hovering || !lastEvent) {
@@ -268,7 +325,37 @@ export function registerDragDwell(
}
if (!qualifies) {
- if (!hovering) {
+ if (!hovering || pendingLeave) {
+ return;
+ }
+
+ const args = getArgsRef();
+ const leaveDelay = fired
+ ? resolveDwellLeaveDelay(args.leaveDelay, args.delay)
+ : 0;
+ if (leaveDelay > 0) {
+ // The factory's latched identity is left untouched while the grace
+ // runs, so a drag returning in time continues the fired candidacy
+ // instead of arming a second dwell.
+ pendingLeave = discourseLater(() => {
+ pendingLeave = null;
+ if (isDestroying || !hovering || !lastEvent) {
+ return;
+ }
+ const endEvent = lastEvent;
+ dwell?.update(null);
+ consumerMayThrow(() =>
+ getArgsRef().onDwellEnd?.({
+ ...endEvent,
+ reason: "left",
+ fired,
+ droppedHere: false,
+ })
+ );
+ hovering = false;
+ fired = false;
+ lastEvent = null;
+ }, leaveDelay);
return;
}
@@ -289,6 +376,7 @@ export function registerDragDwell(
return;
}
+ cancelPendingLeave();
if (!hovering) {
hovering = true;
fired = false;
@@ -298,6 +386,9 @@ export function registerDragDwell(
};
const reportDragEnded = (location: DragLocation) => {
+ // A drag ending inside the grace beats it: the terminal event reports
+ // once, as a drag end.
+ cancelPendingLeave();
if (isDestroying || !hovering || !lastEvent) {
return;
}
@@ -376,6 +467,7 @@ export function registerDragDwell(
return () => {
isDestroying = true;
+ cancelPendingLeave();
cleanupElements();
cleanupExternal();
destroy(lifetime);
diff --git a/frontend/discourse/tests/acceptance/sidebar-link-drop-test.js b/frontend/discourse/tests/acceptance/sidebar-link-drop-test.js
new file mode 100644
index 00000000000..54d780008ab
--- /dev/null
+++ b/frontend/discourse/tests/acceptance/sidebar-link-drop-test.js
@@ -0,0 +1,397 @@
+import {
+ find,
+ findAll,
+ settled,
+ triggerEvent,
+ visit,
+} from "@ember/test-helpers";
+import { test } from "qunit";
+import { ADMIN_PANEL, MAIN_PANEL } from "discourse/lib/sidebar/panels";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+import {
+ dragEvent,
+ externalDragOver,
+ simulateExternalDrag,
+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";
+
+function linkDataTransfer() {
+ const dataTransfer = new DataTransfer();
+ dataTransfer.setData("text/uri-list", "https://example.com/useful");
+ dataTransfer.setData(
+ "text/html",
+ '<a href="https://example.com/useful">Useful link</a>'
+ );
+ return dataTransfer;
+}
+
+acceptance("Sidebar web link drop", function (needs) {
+ needs.user({
+ sidebar_sections: [
+ {
+ 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: 902,
+ name: "Second link",
+ value: "https://example.org/second",
+ icon: "link",
+ external: true,
+ segment: "primary",
+ },
+ ],
+ },
+ ],
+ });
+ needs.settings({ navigation_menu: "sidebar" });
+ needs.pretender((server, helper) => {
+ server.get("/sidebar_sections/900.json", () =>
+ helper.response({
+ sidebar_section: {
+ id: 900,
+ title: "Reading",
+ public: false,
+ section_type: null,
+ locale: "en",
+ localizations: [],
+ links: [
+ {
+ id: 901,
+ name: "Existing link",
+ value: "https://example.org/existing",
+ icon: "link",
+ external: true,
+ segment: "primary",
+ locale: "en",
+ localizations: [],
+ },
+ {
+ id: 902,
+ name: "Second link",
+ value: "https://example.org/second",
+ icon: "link",
+ external: true,
+ segment: "primary",
+ locale: "en",
+ localizations: [],
+ },
+ ],
+ },
+ })
+ );
+ });
+
+ test("dropping a web link on the revealed zone creates a prefilled custom section", async function (assert) {
+ await visit("/");
+
+ const dataTransfer = linkDataTransfer();
+ const scroller = find(".sidebar-sections").getBoundingClientRect();
+ const coordinates = {
+ clientX: scroller.left + scroller.width / 2,
+ clientY: scroller.top + scroller.height / 2,
+ };
+
+ await externalDragOver("#d-sidebar", { dataTransfer, coordinates });
+
+ assert
+ .dom(".sidebar-custom-sections + .sidebar-link-drop-target")
+ .exists(
+ "dwelling over the sections reveals the drop zone where the new section would go, after the last custom section"
+ );
+ assert
+ .dom(".sidebar-link-drop-target.is-arming")
+ .doesNotExist("the zone has armed and can take the drop");
+
+ await dragEvent("#d-sidebar", "dragleave", {
+ dataTransfer,
+ ...coordinates,
+ });
+ assert
+ .dom(".sidebar-link-drop-target")
+ .doesNotExist("hides the zone when the drag leaves the sidebar");
+
+ await externalDragOver("#d-sidebar", { dataTransfer, coordinates });
+ await simulateExternalDrag(".sidebar-link-drop-target", { dataTransfer });
+
+ assert
+ .dom(".sidebar-section-form-modal")
+ .exists("opens the custom section form");
+ assert
+ .dom('input[name="section-name"]')
+ .isFocused(
+ "focuses the title, the one field the new section still needs"
+ );
+ assert
+ .dom('input[name="link-name"]')
+ .hasValue("Useful link", "prefills the dragged link name");
+ assert
+ .dom('input[name="link-url"]')
+ .hasValue("https://example.com/useful", "prefills the dragged link URL");
+ });
+
+ test("dropping a web link inserts it at the indicated position", async function (assert) {
+ await visit("/");
+
+ const section = '.sidebar-section[data-section-name="reading"]';
+ const existingLinks = findAll(`${section} [data-sidebar-custom-link]`);
+ const clientY = existingLinks[1].getBoundingClientRect().top;
+ const dataTransfer = linkDataTransfer();
+ await externalDragOver(section, { dataTransfer, coordinates: { clientY } });
+
+ assert
+ .dom(existingLinks[1])
+ .hasClass(
+ "is-link-drop-before",
+ "shows a line between the existing links"
+ );
+ assert
+ .dom(".sidebar-link-drop-target")
+ .exists(
+ "the new-section zone is revealed too, but the hovered section claims the drop"
+ );
+
+ await triggerEvent(section, "drop", { dataTransfer, clientY });
+
+ assert
+ .dom(".sidebar-section-form-modal")
+ .exists("opens the existing section form");
+ const linkNameInputs = findAll(
+ '.sidebar-section-form-link-wrapper input[name="link-name"]'
+ );
+ const linkUrlInputs = findAll(
+ '.sidebar-section-form-link-wrapper input[name="link-url"]'
+ );
+ assert.strictEqual(linkUrlInputs.length, 3, "inserts one link");
+ assert.dom(linkNameInputs[1]).isFocused("focuses the inserted link name");
+ assert
+ .dom(linkUrlInputs[1])
+ .hasValue(
+ "https://example.com/useful",
+ "inserts the link at the indicated gap"
+ );
+ assert
+ .dom(".sidebar-link-drop-target")
+ .doesNotExist("the zone clears once the drag ends");
+ });
+
+ test("a drop on the sidebar background does not create a section", async function (assert) {
+ await visit("/");
+
+ const dataTransfer = linkDataTransfer();
+ const scroller = find(".sidebar-sections").getBoundingClientRect();
+ const coordinates = {
+ clientX: scroller.left + scroller.width / 2,
+ clientY: scroller.top + scroller.height / 2,
+ };
+
+ await externalDragOver("#d-sidebar", { dataTransfer, coordinates });
+ assert.dom(".sidebar-link-drop-target").exists("the zone is revealed");
+
+ // A real browser would not even fire this drop: the sidebar refuses with a
+ // "none" drop effect, so releasing over it cancels the drag. The synthetic
+ // drop proves that one arriving anyway lands on nothing that handles it.
+ await dragEvent("#d-sidebar", "drop", { dataTransfer, ...coordinates });
+
+ assert
+ .dom(".sidebar-section-form-modal")
+ .doesNotExist("no section form opens for a drop outside the zone");
+ assert
+ .dom(".sidebar-link-drop-target")
+ .doesNotExist("the zone clears once the drag ends");
+ });
+
+ test("scrolls the sections while a dragged link hovers the bottom edge", async function (assert) {
+ await visit("/");
+
+ // The fixture's sections do not overflow the test viewport on their own,
+ // so the scroller is constrained to force it. It is a flex child sized by
+ // the flex algorithm, so a height alone would be ignored.
+ const scroller = find(".sidebar-sections");
+ scroller.style.flex = "none";
+ scroller.style.minHeight = "0";
+ scroller.style.height = "100px";
+ scroller.style.overflowY = "auto";
+
+ const dataTransfer = linkDataTransfer();
+ const { left, bottom, width } = scroller.getBoundingClientRect();
+ const point = { clientX: left + width / 2, clientY: bottom - 2 };
+ await dragEvent(scroller, "dragenter", { dataTransfer, ...point });
+ // Auto-scroll runs off its own animation-frame loop and eases in over
+ // time, so a single event moves nothing measurable.
+ for (let frame = 0; frame < 12; frame++) {
+ await dragEvent(scroller, "dragover", { dataTransfer, ...point });
+ }
+
+ assert.true(
+ scroller.scrollTop > 0,
+ "a link held against the bottom edge scrolls the sections into reach"
+ );
+ });
+
+ test("points out a dropped link the section already has", async function (assert) {
+ await visit("/");
+
+ const section = '.sidebar-section[data-section-name="reading"]';
+ const dataTransfer = new DataTransfer();
+ dataTransfer.setData("text/uri-list", "https://example.org/existing");
+
+ await simulateExternalDrag(section, { dataTransfer });
+
+ assert
+ .dom(".sidebar-section-form-modal")
+ .exists("still opens the form, since a repeat is allowed");
+ assert
+ .dom(".sidebar-section-form-link-wrapper .duplicate-link")
+ .exists({ count: 1 }, "marks the repeat, and only the repeat");
+ assert
+ .dom("#save-section")
+ .isNotDisabled("a repeated link is a warning, not a refusal");
+ });
+});
+
+/**
+ * A public section, which only an admin may edit. Whether a link can be dropped
+ * into one has to follow that, or the drag offers a new section to the very
+ * people who could have edited this one.
+ */
+function publicSection() {
+ return [
+ {
+ id: 910,
+ title: "Announcements",
+ slug: "announcements",
+ public: true,
+ section_type: null,
+ links: [
+ {
+ id: 911,
+ name: "Existing link",
+ value: "https://example.org/existing",
+ icon: "link",
+ external: true,
+ segment: "primary",
+ },
+ ],
+ },
+ ];
+}
+
+const PUBLIC_SECTION = '.sidebar-section[data-section-name="announcements"]';
+
+acceptance("Sidebar web link drop | public section, admin", function (needs) {
+ needs.user({ admin: true, sidebar_sections: publicSection() });
+ needs.settings({ navigation_menu: "sidebar" });
+ needs.pretender((server, helper) => {
+ server.get("/sidebar_sections/910.json", () =>
+ helper.response({
+ sidebar_section: {
+ id: 910,
+ title: "Announcements",
+ public: true,
+ section_type: null,
+ locale: "en",
+ localizations: [],
+ links: [
+ {
+ id: 911,
+ name: "Existing link",
+ value: "https://example.org/existing",
+ icon: "link",
+ external: true,
+ segment: "primary",
+ locale: "en",
+ localizations: [],
+ },
+ ],
+ },
+ })
+ );
+ });
+
+ test("still takes a dragged link after a panel switch and back", async function (assert) {
+ await visit("/");
+
+ const sidebarState = this.container.lookup("service:sidebar-state");
+ sidebarState.setPanel(ADMIN_PANEL);
+ await settled();
+ sidebarState.setPanel(MAIN_PANEL);
+ await settled();
+
+ const dataTransfer = linkDataTransfer();
+ await externalDragOver(PUBLIC_SECTION, { dataTransfer });
+
+ assert
+ .dom(PUBLIC_SECTION)
+ .hasClass(
+ "is-link-drop-active",
+ "the section still takes the drop after the sections were remounted"
+ );
+ assert
+ .dom(".sidebar-link-drop-target")
+ .exists("the dwell still reveals the zone after the remount");
+
+ await simulateExternalDrag(PUBLIC_SECTION, { dataTransfer });
+ assert
+ .dom(".sidebar-section-form-modal")
+ .exists("and the drop still opens the section form");
+ });
+
+ test("a public section takes a dropped link for someone who can edit it", async function (assert) {
+ await visit("/");
+
+ await externalDragOver(PUBLIC_SECTION, {
+ dataTransfer: linkDataTransfer(),
+ });
+
+ assert
+ .dom(PUBLIC_SECTION)
+ .hasClass(
+ "is-link-drop-active",
+ "an admin can edit a public section, so a link dropped on it goes in"
+ );
+ assert
+ .dom(".sidebar-link-drop-target")
+ .exists(
+ "the new-section zone is revealed alongside, for a drop outside the section"
+ );
+ });
+});
+
+acceptance(
+ "Sidebar web link drop | public section, regular user",
+ function (needs) {
+ needs.user({ admin: false, sidebar_sections: publicSection() });
+ needs.settings({ navigation_menu: "sidebar" });
+
+ test("a public section refuses a dropped link for someone who cannot edit it", async function (assert) {
+ await visit("/");
+
+ await externalDragOver(PUBLIC_SECTION, {
+ dataTransfer: linkDataTransfer(),
+ });
+
+ assert
+ .dom(PUBLIC_SECTION)
+ .doesNotHaveClass(
+ "is-link-drop-active",
+ "a section this user cannot edit does not take the drop"
+ );
+ assert
+ .dom(".sidebar-link-drop-target")
+ .exists(
+ "the dwell still reveals the zone, offering a section of their own"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/components/sidebar/section-test.gjs b/frontend/discourse/tests/integration/components/sidebar/section-test.gjs
index 0ef5a1cb877..0170cb64ddc 100644
--- a/frontend/discourse/tests/integration/components/sidebar/section-test.gjs
+++ b/frontend/discourse/tests/integration/components/sidebar/section-test.gjs
@@ -1,7 +1,50 @@
-import { click, render } from "@ember/test-helpers";
+import {
+ click,
+ find,
+ render,
+ settled,
+ triggerEvent,
+} from "@ember/test-helpers";
import { module, test } from "qunit";
import Section from "discourse/components/sidebar/section";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ centerOf,
+ dragEvent,
+ dragEventNow,
+ externalDragOver,
+ simulateExternalDrag,
+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";
+
+/** A drag carrying a real URL, the way a link dragged from another tab arrives. */
+function urlTransfer() {
+ const dataTransfer = new DataTransfer();
+ dataTransfer.setData("text/uri-list", "https://example.com/dropped");
+ return dataTransfer;
+}
+
+/** Selected text, which may or may not turn out to contain a URL. */
+function textTransfer() {
+ const dataTransfer = new DataTransfer();
+ dataTransfer.setData("text/html", "<p>some selected text</p>");
+ dataTransfer.setData("text/plain", "some selected text");
+ return dataTransfer;
+}
+
+function fileTransfer() {
+ const dataTransfer = new DataTransfer();
+ dataTransfer.items.add(
+ new File(["payload"], "a.txt", { type: "text/plain" })
+ );
+ return dataTransfer;
+}
+
+/** Past the midpoint of every link, so a drop lands at the end of the list. */
+function belowAllLinks() {
+ return {
+ clientY: find(".sidebar-section").getBoundingClientRect().bottom - 2,
+ };
+}
module("Integration | Component | Sidebar | Section", function (hooks) {
setupRenderingTest(hooks);
@@ -72,4 +115,299 @@ module("Integration | Component | Sidebar | Section", function (hooks) {
.dom(".sidebar-section-content")
.doesNotExist("does not show content after collapsing");
});
+
+ test("accepts web link drops when enabled", async function (assert) {
+ this.onLinkDrop = (source, linkDropIndex) => {
+ assert.step("drop");
+ assert.strictEqual(
+ source.getURLs()[0],
+ "https://example.com/dropped",
+ "passes the dropped payload to the handler"
+ );
+ assert.strictEqual(linkDropIndex, 2, "drops after the final link");
+ };
+
+ await render(
+ <template>
+ <Section
+ @sectionName="test"
+ @headerLinkText="test header"
+ @linkDropEnabled={{true}}
+ @onLinkDrop={{this.onLinkDrop}}
+ >
+ <li data-sidebar-custom-link="true">First link</li>
+ <li data-sidebar-custom-link="true">Second link</li>
+ </Section>
+ </template>
+ );
+
+ const dataTransfer = urlTransfer();
+ await externalDragOver(".sidebar-section", {
+ dataTransfer,
+ coordinates: belowAllLinks(),
+ });
+
+ assert
+ .dom(".sidebar-section")
+ .hasClass("is-link-drop-active", "shows an active drop state");
+ assert
+ .dom(".sidebar-section-link-drop-indicator")
+ .exists("shows where the link will be appended");
+
+ await triggerEvent(".sidebar-section", "drop", {
+ dataTransfer,
+ ...belowAllLinks(),
+ });
+
+ assert.verifySteps(["drop"], "invokes the drop handler once");
+ assert
+ .dom(".sidebar-section")
+ .doesNotHaveClass("is-link-drop-active", "clears the drop state");
+ assert
+ .dom(".sidebar-section-link-drop-indicator")
+ .doesNotExist("clears the insertion indicator");
+ });
+
+ test("does not advertise ambiguous text as a link", async function (assert) {
+ await render(
+ <template>
+ <Section
+ @sectionName="test"
+ @headerLinkText="test header"
+ @linkDropEnabled={{true}}
+ />
+ </template>
+ );
+
+ await externalDragOver(".sidebar-section", {
+ dataTransfer: textTransfer(),
+ });
+
+ assert
+ .dom(".sidebar-section")
+ .doesNotHaveClass(
+ "is-link-drop-active",
+ "does not show a drop affordance for selected text"
+ );
+ });
+
+ test("stays active while the cursor is over its own contents", async function (assert) {
+ await render(
+ <template>
+ <Section
+ @sectionName="test"
+ @headerLinkText="test header"
+ @linkDropEnabled={{true}}
+ />
+ </template>
+ );
+
+ const dataTransfer = urlTransfer();
+ await externalDragOver(".sidebar-section", { dataTransfer });
+
+ // Driven event by event: the header text is deliberately not a drop target,
+ // which is what this test is about, so the helper's registration guard
+ // would refuse it.
+ const overHeader = centerOf(".sidebar-section-header-text");
+ await dragEvent(".sidebar-section-header-text", "dragenter", {
+ dataTransfer,
+ ...overHeader,
+ });
+ await dragEvent(".sidebar-section-header-text", "dragover", {
+ dataTransfer,
+ ...overHeader,
+ });
+
+ assert
+ .dom(".sidebar-section")
+ .hasClass(
+ "is-link-drop-active",
+ "a descendant that is not itself a drop target does not take the section's place"
+ );
+
+ await triggerEvent(".sidebar-section", "dragleave", { dataTransfer });
+
+ assert
+ .dom(".sidebar-section")
+ .doesNotHaveClass(
+ "is-link-drop-active",
+ "clears the state after leaving the section"
+ );
+ });
+
+ test("clears the drop state when the drag is abandoned", async function (assert) {
+ await render(
+ <template>
+ <Section
+ @sectionName="test"
+ @headerLinkText="test header"
+ @linkDropEnabled={{true}}
+ />
+ </template>
+ );
+
+ const dataTransfer = urlTransfer();
+ await externalDragOver(".sidebar-section", { dataTransfer });
+ assert
+ .dom(".sidebar-section")
+ .hasClass("is-link-drop-active", "shows the active drop state");
+
+ await triggerEvent(document, "dragend", { dataTransfer });
+
+ assert
+ .dom(".sidebar-section")
+ .doesNotHaveClass(
+ "is-link-drop-active",
+ "a drag released outside any target still ends the hover state"
+ );
+ });
+
+ test("does not accept non-link drops", async function (assert) {
+ this.onLinkDrop = () => assert.step("drop");
+
+ await render(
+ <template>
+ <Section
+ @sectionName="test"
+ @headerLinkText="test header"
+ @linkDropEnabled={{true}}
+ @onLinkDrop={{this.onLinkDrop}}
+ />
+ </template>
+ );
+
+ await simulateExternalDrag(".sidebar-section", {
+ dataTransfer: fileTransfer(),
+ });
+
+ assert
+ .dom(".sidebar-section")
+ .doesNotHaveClass("is-link-drop-active", "does not show a drop state");
+ assert.verifySteps([], "does not invoke the drop handler");
+ });
+
+ test("does not accept web link drops when disabled", async function (assert) {
+ this.onLinkDrop = () => assert.step("drop");
+
+ await render(
+ <template>
+ <Section
+ @sectionName="test"
+ @headerLinkText="test header"
+ @linkDropEnabled={{false}}
+ @onLinkDrop={{this.onLinkDrop}}
+ />
+ </template>
+ );
+
+ await simulateExternalDrag(".sidebar-section", {
+ dataTransfer: urlTransfer(),
+ });
+
+ assert
+ .dom(".sidebar-section")
+ .doesNotHaveClass("is-link-drop-active", "does not show a drop state");
+ assert.verifySteps([], "does not invoke the drop handler");
+ });
+
+ module("dragging over a collapsed section", function () {
+ const collapsedSection = <template>
+ <Section
+ @sectionName="test"
+ @headerLinkText="test header"
+ @collapsable={{true}}
+ @linkDropEnabled={{true}}
+ @onLinkDrop={{@onLinkDrop}}
+ >
+ <li data-sidebar-custom-link="true">First link</li>
+ <li data-sidebar-custom-link="true">Second link</li>
+ </Section>
+ </template>;
+
+ async function renderCollapsed(onLinkDrop) {
+ await render(
+ <template><collapsedSection @onLinkDrop={{onLinkDrop}} /></template>
+ );
+ await click(".sidebar-section-header-caret");
+ }
+
+ test("opens under a link held over it", async function (assert) {
+ await renderCollapsed();
+
+ assert
+ .dom(".sidebar-section-content")
+ .doesNotExist("starts collapsed, so there is nothing to aim at");
+
+ await externalDragOver(".sidebar-section", {
+ dataTransfer: urlTransfer(),
+ });
+
+ assert
+ .dom(".sidebar-section-content")
+ .exists(
+ "holding a link over a collapsed section opens it, so the drop can be aimed at a row"
+ );
+ });
+
+ test("appends rather than claiming the top while still closed", async function (assert) {
+ let index = "not called";
+ await renderCollapsed((_source, linkDropIndex) => {
+ index = linkDropIndex;
+ });
+
+ const aim = {
+ dataTransfer: urlTransfer(),
+ ...centerOf(".sidebar-section"),
+ ...belowAllLinks(),
+ };
+ // All in one task, so the dwell timer cannot open the section before
+ // the drop lands.
+ dragEventNow(".sidebar-section", "dragenter", aim);
+ dragEventNow(".sidebar-section", "dragover", aim);
+ dragEventNow(".sidebar-section", "drop", aim);
+ await settled();
+
+ assert.strictEqual(
+ index,
+ undefined,
+ "a section showing no rows has no position to report, so the link goes to the end rather than ahead of links the user cannot see"
+ );
+ });
+
+ test("closes again when the link wanders off before dropping", async function (assert) {
+ await renderCollapsed();
+
+ const dataTransfer = urlTransfer();
+ await externalDragOver(".sidebar-section", { dataTransfer });
+ assert.dom(".sidebar-section-content").exists("the dwell opened it");
+
+ const { left, bottom } = find(".sidebar-section").getBoundingClientRect();
+ await dragEvent(document.body, "dragover", {
+ dataTransfer,
+ clientX: left,
+ clientY: bottom + 50,
+ });
+ await settled();
+
+ assert
+ .dom(".sidebar-section-content")
+ .doesNotExist(
+ "a drag that wanders off undoes the reveal, leaving the section as the user had it"
+ );
+ });
+
+ test("stays open after the link is dropped into it", async function (assert) {
+ const dropped = [];
+ await renderCollapsed((link) => dropped.push(link));
+
+ await simulateExternalDrag(".sidebar-section", {
+ dataTransfer: urlTransfer(),
+ });
+
+ assert.strictEqual(dropped.length, 1, "the drop landed");
+ assert
+ .dom(".sidebar-section-content")
+ .exists("the section keeps showing the link the user just dropped");
+ });
+ });
});
diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-external-target-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-external-target-test.gjs
index cc5457db356..d83ad69e311 100644
--- a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-external-target-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-external-target-test.gjs
@@ -513,7 +513,7 @@ module(
throw new Error("external consumer blew up");
};
- test("a throwing external getDropEffect is reported and the drop still lands", async function (assert) {
+ test("a throwing external drop effect function is reported and the drop still lands", async function (assert) {
const reported = [];
setupOnerror((error) => reported.push(error));
@@ -526,7 +526,7 @@ module(
id="ext"
{{dDragAndDropExternalTarget
accepts="text"
- getDropEffect=blowUp
+ dropEffect=blowUp
onDrop=recordDrop
}}
>ext</div>
diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-test.gjs
index 6a8e349bfee..fdb7ae25ec3 100644
--- a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-test.gjs
@@ -3179,7 +3179,7 @@ module("Integration | ui-kit | Modifier | dragAndDrop", function (hooks) {
);
});
- test("getDropEffect decides the effect recorded against this target", async function (assert) {
+ test("a drop effect function decides the effect recorded against this target", async function (assert) {
const effects = [];
const copyEffect = () => "copy";
const recordDrop = ({ location }) =>
@@ -3197,7 +3197,7 @@ module("Integration | ui-kit | Modifier | dragAndDrop", function (hooks) {
>src</div>
<div
id="tgt"
- {{dDragAndDropTarget accepts="row" getDropEffect=copyEffect}}
+ {{dDragAndDropTarget accepts="row" dropEffect=copyEffect}}
>tgt</div>
</template>
);
@@ -3213,6 +3213,37 @@ module("Integration | ui-kit | Modifier | dragAndDrop", function (hooks) {
);
});
+ test("a plain drop effect string is taken as is", async function (assert) {
+ const effects = [];
+ const recordDrop = ({ location }) =>
+ effects.push(location.current.dropTargets[0].dropEffect);
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ effectAllowed="copyMove"
+ onDrop=recordDrop
+ }}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" dropEffect="copy"}}
+ >tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ assert.deepEqual(
+ effects,
+ ["copy"],
+ "a fixed effect needs no function around it"
+ );
+ });
+
test("getData attaches target metadata the drag carries to the source", async function (assert) {
const targets = [];
const describeTarget = () => ({ slot: "inbox" });
diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-dwell-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-dwell-test.gjs
index 82a8667dd84..cc53a0e2eae 100644
--- a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-dwell-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-dwell-test.gjs
@@ -21,6 +21,8 @@ import dDragAndDropSource from "discourse/ui-kit/modifiers/d-drag-and-drop-sourc
import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
import dDragDwell, {
registerDragDwell,
+ resolveDwellDelay,
+ resolveDwellLeaveDelay,
} from "discourse/ui-kit/modifiers/d-drag-dwell";
/* The dwell delay collapses to a 10ms runloop timer under test, which is
@@ -194,6 +196,171 @@ module("Integration | ui-kit | Modifier | dDragDwell", function (hooks) {
assert.true(ends[0].fired, "after having fired");
});
+ test("dDragDwell ends a fired dwell in the leaving frame when the grace is declined", async function (assert) {
+ const ends = [];
+ const onDwell = () => {};
+ const onDwellEnd = (event) => ends.push(event);
+
+ await render(
+ <template>
+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>
+ <div
+ data-test-dwell
+ style="display: block; height: 60px;"
+ {{dDragAndDropTarget accepts="card" indicator=false}}
+ {{dDragDwell
+ types="card"
+ leaveDelay=false
+ onDwell=onDwell
+ onDwellEnd=onDwellEnd
+ }}
+ >folder</div>
+ <div
+ data-test-outside
+ style="display: block; height: 60px; margin-top: 30px;"
+ {{dDragAndDropTarget accepts="card" indicator=false}}
+ >outside</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag(CHIP, { dataTransfer });
+ await dragOver(DWELL, { dataTransfer });
+ await settled();
+
+ dragEventNow(OUTSIDE, "dragenter", { dataTransfer, ...centerOf(OUTSIDE) });
+ assert.strictEqual(
+ ends.length,
+ 1,
+ "the end is reported in the leaving frame itself, before any timer"
+ );
+ assert.strictEqual(ends[0].reason, "left", "by leaving");
+ });
+
+ test("dDragDwell keeps a fired dwell through a brief leave by default", async function (assert) {
+ const dwells = [];
+ const ends = [];
+ const onDwell = (event) => dwells.push(event);
+ const onDwellEnd = (event) => ends.push(event);
+
+ await render(
+ <template>
+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>
+ <div
+ data-test-dwell
+ style="display: block; height: 60px;"
+ {{dDragAndDropTarget accepts="card" indicator=false}}
+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}
+ >folder</div>
+ <div
+ data-test-outside
+ style="display: block; height: 60px; margin-top: 30px;"
+ {{dDragAndDropTarget accepts="card" indicator=false}}
+ >outside</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag(CHIP, { dataTransfer });
+ await dragOver(DWELL, { dataTransfer });
+ await settled();
+ assert.strictEqual(dwells.length, 1, "fired");
+
+ // Leave and return in one task, beating the collapsed grace timer.
+ dragEventNow(OUTSIDE, "dragenter", { dataTransfer, ...centerOf(OUTSIDE) });
+ dragEventNow(DWELL, "dragenter", { dataTransfer, ...centerOf(DWELL) });
+ await settled();
+
+ assert.strictEqual(ends.length, 0, "the brief leave reported no end");
+ assert.strictEqual(dwells.length, 1, "and the return re-fired nothing");
+
+ await dragEvent(DWELL, "drop", { dataTransfer, ...centerOf(DWELL) });
+ await dragEvent(CHIP, "dragend", { dataTransfer, ...centerOf(DWELL) });
+ await settled();
+
+ assert.strictEqual(ends.length, 1, "the drop ended the candidacy");
+ assert.strictEqual(ends[0].reason, "drag-ended", "as a drag end");
+ assert.true(ends[0].fired, "still counted as fired");
+ assert.true(ends[0].droppedHere, "with the drop landing here");
+ });
+
+ test("dDragDwell reports a single left end once the grace expires", async function (assert) {
+ const ends = [];
+ const onDwell = () => {};
+ const onDwellEnd = (event) => ends.push(event);
+
+ await render(
+ <template>
+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>
+ <div
+ data-test-dwell
+ style="display: block; height: 60px;"
+ {{dDragAndDropTarget accepts="card" indicator=false}}
+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}
+ >folder</div>
+ <div
+ data-test-outside
+ style="display: block; height: 60px; margin-top: 30px;"
+ {{dDragAndDropTarget accepts="card" indicator=false}}
+ >outside</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag(CHIP, { dataTransfer });
+ await dragOver(DWELL, { dataTransfer });
+ await settled();
+
+ await dragEvent(OUTSIDE, "dragenter", {
+ dataTransfer,
+ ...centerOf(OUTSIDE),
+ });
+ await settled();
+
+ assert.strictEqual(ends.length, 1, "one end after the grace ran out");
+ assert.strictEqual(ends[0].reason, "left", "by leaving");
+ assert.true(ends[0].fired, "after having fired");
+ });
+
+ test("dDragDwell reports a drag ending inside the grace as drag-ended once", async function (assert) {
+ const ends = [];
+ const onDwell = () => {};
+ const onDwellEnd = (event) => ends.push(event);
+
+ await render(
+ <template>
+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>
+ <div
+ data-test-dwell
+ style="display: block; height: 60px;"
+ {{dDragAndDropTarget accepts="card" indicator=false}}
+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}
+ >folder</div>
+ <div
+ data-test-outside
+ style="display: block; height: 60px; margin-top: 30px;"
+ {{dDragAndDropTarget accepts="card" indicator=false}}
+ >outside</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag(CHIP, { dataTransfer });
+ await dragOver(DWELL, { dataTransfer });
+ await settled();
+
+ // Leave and drop elsewhere in one task, while the grace is still pending.
+ dragEventNow(OUTSIDE, "dragenter", { dataTransfer, ...centerOf(OUTSIDE) });
+ dragEventNow(OUTSIDE, "drop", { dataTransfer, ...centerOf(OUTSIDE) });
+ dragEventNow(CHIP, "dragend", { dataTransfer, ...centerOf(OUTSIDE) });
+ await settled();
+
+ assert.strictEqual(ends.length, 1, "exactly one end");
+ assert.strictEqual(ends[0].reason, "drag-ended", "the drag end wins");
+ assert.true(ends[0].fired, "after having fired");
+ assert.false(ends[0].droppedHere, "with the drop landing elsewhere");
+ });
+
test("dDragDwell reports the drop-target onDrop before onDwellEnd, with droppedHere", async function (assert) {
const order = [];
const onTargetDrop = () => order.push("target-drop");
@@ -961,4 +1128,57 @@ module("Integration | ui-kit | Modifier | dDragDwell", function (hooks) {
"and the host element"
);
});
+
+ module("delay resolution", function () {
+ test("resolveDwellDelay maps the boolean shorthands", function (assert) {
+ assert.strictEqual(resolveDwellDelay(undefined), 500, "omitted");
+ assert.strictEqual(resolveDwellDelay(true), 500, "true");
+ assert.strictEqual(resolveDwellDelay(false), 0, "false");
+ assert.strictEqual(resolveDwellDelay(300), 300, "a number stands");
+ assert.strictEqual(resolveDwellDelay(0), 0, "zero stands");
+ });
+
+ test("resolveDwellLeaveDelay mirrors the entry delay on true", function (assert) {
+ assert.strictEqual(
+ resolveDwellLeaveDelay(undefined, 300),
+ 300,
+ "omission mirrors, like true"
+ );
+ assert.strictEqual(
+ resolveDwellLeaveDelay(false, 300),
+ 0,
+ "false declines"
+ );
+ assert.strictEqual(
+ resolveDwellLeaveDelay(true, 300),
+ 300,
+ "true mirrors an explicit entry delay"
+ );
+ assert.strictEqual(
+ resolveDwellLeaveDelay(true, true),
+ 500,
+ "true mirrors the standard entry delay"
+ );
+ assert.strictEqual(
+ resolveDwellLeaveDelay(true, undefined),
+ 500,
+ "true mirrors the omitted entry delay"
+ );
+ assert.strictEqual(
+ resolveDwellLeaveDelay(true, false),
+ 500,
+ "an immediate entry falls back to the standard delay"
+ );
+ assert.strictEqual(
+ resolveDwellLeaveDelay(true, 0),
+ 500,
+ "so does an explicit zero entry"
+ );
+ assert.strictEqual(
+ resolveDwellLeaveDelay(250, false),
+ 250,
+ "a number stands on its own"
+ );
+ });
+ });
});
diff --git a/frontend/discourse/tests/unit/lib/sidebar/link-drop-test.js b/frontend/discourse/tests/unit/lib/sidebar/link-drop-test.js
new file mode 100644
index 00000000000..394fac44259
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/sidebar/link-drop-test.js
@@ -0,0 +1,156 @@
+import { module, test } from "qunit";
+import { extractDroppedWebLink } from "discourse/lib/sidebar/link-drop";
+
+/**
+ * Stands in for the decorated payload a drop target hands its consumer. Each
+ * accessor is stated outright rather than derived from the others, so a test
+ * says exactly what the browser put on the drag and cannot accidentally assert
+ * against a reimplementation of the library that normally parses it.
+ */
+function externalSource({ urls = [], html = null, text = null, strings = {} }) {
+ return {
+ getURLs: () => urls,
+ getHTML: () => html,
+ getText: () => text,
+ getStringData: (mediaType) => strings[mediaType] ?? null,
+ };
+}
+
+module("Unit | Lib | Sidebar | link-drop", function () {
+ test("takes the first URL it can actually use", function (assert) {
+ const link = extractDroppedWebLink(
+ externalSource({
+ urls: [
+ "not a URL",
+ "https://example.com/first",
+ "https://example.com/second",
+ ],
+ })
+ );
+
+ assert.deepEqual(
+ link,
+ {
+ icon: "link",
+ name: "example.com",
+ value: "https://example.com/first",
+ segment: "primary",
+ },
+ "entries that are not usable URLs are passed over rather than failing the drop"
+ );
+ });
+
+ test("uses dragged link text as the default name", function (assert) {
+ const link = extractDroppedWebLink(
+ externalSource({
+ urls: ["https://example.com/article"],
+ html: '<a href="https://example.com/article"> Example article </a>',
+ strings: { "text/uri-list": "https://example.com/article" },
+ })
+ );
+
+ assert.strictEqual(
+ link.name,
+ "Example article",
+ "HTML link text is normalized"
+ );
+ });
+
+ test("keeps the title Firefox supplies alongside its own URL format", function (assert) {
+ const link = extractDroppedWebLink(
+ externalSource({
+ urls: ["https://example.com/firefox"],
+ strings: {
+ "text/x-moz-url": "https://example.com/firefox\nFirefox title",
+ },
+ })
+ );
+
+ assert.strictEqual(
+ link.name,
+ "Firefox title",
+ "the title is read back out of the format the URL came from"
+ );
+ });
+
+ test("ignores Firefox titles when the URLs came from the standard type", function (assert) {
+ const link = extractDroppedWebLink(
+ externalSource({
+ urls: ["https://example.com/standard"],
+ strings: {
+ "text/uri-list": "https://example.com/standard",
+ "text/x-moz-url": "https://example.com/other\nA different page",
+ },
+ })
+ );
+
+ assert.strictEqual(
+ link.name,
+ "example.com",
+ "a title is only trusted to name the URL it was sent beside"
+ );
+ });
+
+ test("falls back to plain text, named after its host", function (assert) {
+ const link = extractDroppedWebLink(
+ externalSource({ text: "https://www.example.org/plain" })
+ );
+
+ assert.strictEqual(
+ link.name,
+ "example.org",
+ "the hostname is used for a plain URL"
+ );
+ });
+
+ test("accepts only absolute HTTP and HTTPS URLs", function (assert) {
+ for (const value of [
+ // eslint-disable-next-line no-script-url
+ "javascript:alert(1)",
+ "data:text/html,hello",
+ "mailto:[email protected]",
+ "/relative/path",
+ "selected text",
+ ]) {
+ assert.strictEqual(
+ extractDroppedWebLink(externalSource({ text: value })),
+ undefined,
+ `${value} is rejected`
+ );
+ }
+
+ assert.strictEqual(
+ extractDroppedWebLink(externalSource({ text: "http://example.com" }))
+ .value,
+ "http://example.com/",
+ "HTTP URLs are accepted"
+ );
+ });
+
+ test("stores a link to this very site as a path", function (assert) {
+ const link = extractDroppedWebLink(
+ externalSource({
+ urls: [`${window.location.origin}/t/a-topic/12?u=someone#post-3`],
+ html: `<a href="${window.location.origin}/t/a-topic/12">A topic</a>`,
+ })
+ );
+
+ assert.strictEqual(
+ link.value,
+ "/t/a-topic/12?u=someone#post-3",
+ "the hostname is dropped so the link survives the site moving, and the query and fragment are kept because they are part of where it points"
+ );
+ });
+
+ test("leaves a link to somewhere else absolute", function (assert) {
+ const link = extractDroppedWebLink(
+ externalSource({ urls: ["https://example.com/t/a-topic/12"] })
+ );
+
+ assert.strictEqual(
+ link.value,
+ "https://example.com/t/a-topic/12",
+ "another site's URL is not ours to shorten"
+ );
+ });
+});
diff --git a/frontend/discourse/type-tests/ui-kit/d-drag-dwell-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-drag-dwell-errors-test.gts
index 0a302bf7efe..ceff5796bc9 100644
--- a/frontend/discourse/type-tests/ui-kit/d-drag-dwell-errors-test.gts
+++ b/frontend/discourse/type-tests/ui-kit/d-drag-dwell-errors-test.gts
@@ -10,9 +10,12 @@ const Negatives = <template>
{{! @glint-expect-error - onDwell is required }}
<div {{dDragDwell types="card"}}></div>
- {{! @glint-expect-error - delay is a number of milliseconds }}
+ {{! @glint-expect-error - delay is a boolean or a number of milliseconds }}
<div {{dDragDwell types="card" delay="500" onDwell=open}}></div>
+ {{! @glint-expect-error - leaveDelay is a boolean or a number of milliseconds }}
+ <div {{dDragDwell types="card" leaveDelay="250" onDwell=open}}></div>
+
{{! @glint-expect-error - externalKinds is the closed external-kind vocabulary }}
<div {{dDragDwell externalKinds="images" onDwell=open}}></div>
diff --git a/frontend/discourse/type-tests/ui-kit/d-drag-dwell-test.gts b/frontend/discourse/type-tests/ui-kit/d-drag-dwell-test.gts
index d87611d0f1e..525ab515194 100644
--- a/frontend/discourse/type-tests/ui-kit/d-drag-dwell-test.gts
+++ b/frontend/discourse/type-tests/ui-kit/d-drag-dwell-test.gts
@@ -53,6 +53,7 @@ const Positives = <template>
types="card"
externalKinds="text"
delay=700
+ leaveDelay=250
canDwell=gate
acceptsSelf=false
onDwell=open
@@ -60,6 +61,11 @@ const Positives = <template>
}}
></div>
+ {{! Boolean shorthands for both delays. }}
+ <div
+ {{dDragDwell types="card" delay=false leaveDelay=true onDwell=open}}
+ ></div>
+
{{! Arrays for both filters. }}
<div
{{dDragDwell
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/drag-and-drop/sources/effect.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/drag-and-drop/sources/effect.gjs
index ce5b6231867..33b55f2a7c9 100644
--- a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/drag-and-drop/sources/effect.gjs
+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/drag-and-drop/sources/effect.gjs
@@ -5,9 +5,6 @@ import dDragAndDropSource from "discourse/ui-kit/modifiers/d-drag-and-drop-sourc
import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
import { i18n } from "discourse-i18n";
-const copyEffect = () => "copy";
-const moveEffect = () => "move";
-
export default class EffectExample extends Component {
@tracked effect;
@@ -34,7 +31,7 @@ export default class EffectExample extends Component {
{{dDragAndDropTarget
accepts="card"
position="inside"
- getDropEffect=copyEffect
+ dropEffect="copy"
}}
>{{i18n "styleguide.sections.drag_and_drop.asks_for_copy"}}</div>
@@ -43,7 +40,7 @@ export default class EffectExample extends Component {
{{dDragAndDropTarget
accepts="card"
position="inside"
- getDropEffect=moveEffect
+ dropEffect="move"
}}
>{{i18n "styleguide.sections.drag_and_drop.asks_for_move"}}</div>
</div>
diff --git a/plugins/styleguide/config/locales/client.en.yml b/plugins/styleguide/config/locales/client.en.yml
index d7e4fc523f2..7d99d1ef1c4 100644
--- a/plugins/styleguide/config/locales/client.en.yml
+++ b/plugins/styleguide/config/locales/client.en.yml
@@ -114,7 +114,7 @@ en:
disabled_try_this: "Switch it off, try to drag, then switch it back on."
draggable: "Draggable"
effect_title: "Declaring the effect"
- effect_description: "`dDragAndDropTarget` names the operation it would perform through getDropEffect, and the drag carries that effect on its record of the target."
+ effect_description: "`dDragAndDropTarget` names the operation it would perform through dropEffect, and the drag carries that effect on its record of the target."
effect_try_this: "Drop on each zone and compare the recorded effect."
effect_note: "The source's effectAllowed declares what it permits, but nothing here enforces the pair: a target may ask for an effect the source never permitted and no refusal follows. Keep the two consistent yourself."
asks_for_copy: "Asks for copy"