Skip to content

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

FEATURE: Bulk select posts and delete drafts (#34972)

Keegan Georgead21ae98ff15
diff --git a/app/assets/javascripts/discourse/app/components/post-list/bulk-controls.gjs b/app/assets/javascripts/discourse/app/components/post-list/bulk-controls.gjs
new file mode 100644
index 00000000000..6cabf885db8
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/post-list/bulk-controls.gjs
@@ -0,0 +1,90 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import DButton from "discourse/components/d-button";
+import DropdownMenu from "discourse/components/dropdown-menu";
+import { i18n } from "discourse-i18n";
+import DMenu from "float-kit/components/d-menu";
+
+/**
+ * Bulk selection controls for PostList component
+ *
+ * @component PostListBulkControls
+ *
+ * @args {PostBulkSelectHelper} bulkSelectHelper - The bulk selection helper
+ * @args {Array} bulkActions - Array of bulk action objects with label, action, icon properties
+ */
+export default class PostListBulkControls extends Component {
+ get selectedText() {
+ const count = this.args.bulkSelectHelper?.selectedCount || 0;
+ return i18n("post_list.bulk.selected", { count });
+ }
+
+ @action
+ async onBulkActionSelect(bulkAction) {
+ if (this.dMenu) {
+ await this.dMenu.close();
+ }
+
+ if (bulkAction.action && this.args.bulkSelectHelper?.selected) {
+ bulkAction.action(this.args.bulkSelectHelper.selected);
+ }
+ }
+
+ @action
+ onRegisterApi(api) {
+ this.dMenu = api;
+ }
+
+ <template>
+ <div class="post-list-bulk-controls">
+ <div class="post-list-bulk-controls__selection">
+ <div class="post-list-bulk-controls__count">
+ {{this.selectedText}}
+ </div>
+
+ <div class="post-list-bulk-controls__actions">
+ <DButton
+ @action={{@bulkSelectHelper.clearAll}}
+ @label="post_list.bulk.clear_all"
+ class="btn-transparent bulk-clear-all"
+ />
+ <DButton
+ @action={{@bulkSelectHelper.selectAll}}
+ @label="post_list.bulk.select_all"
+ class="btn-transparent bulk-select-all"
+ />
+
+ {{#if @bulkSelectHelper.hasSelection}}
+ <DMenu
+ @label={{i18n "post_list.bulk.actions"}}
+ @placement="bottom"
+ @icon="chevron-down"
+ @modalForMobile={{true}}
+ @autofocus={{true}}
+ @identifier="post-list-bulk-actions-dropdown"
+ @onRegisterApi={{this.onRegisterApi}}
+ class="bulk-actions-dropdown"
+ >
+ <:content>
+ <DropdownMenu as |dropdown|>
+ {{#each @bulkActions as |bulkAction|}}
+ <dropdown.item>
+ <DButton
+ @label={{bulkAction.label}}
+ @icon={{bulkAction.icon}}
+ @disabled={{@bulkSelectHelper.loading}}
+ class="btn-transparent {{bulkAction.class}}"
+ @action={{fn this.onBulkActionSelect bulkAction}}
+ />
+ </dropdown.item>
+ {{/each}}
+ </DropdownMenu>
+ </:content>
+ </DMenu>
+ {{/if}}
+ </div>
+ </div>
+ </div>
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/app/components/post-list/index.gjs b/app/assets/javascripts/discourse/app/components/post-list/index.gjs
index 45a25a0bd7b..b61e96a4bce 100644
--- a/app/assets/javascripts/discourse/app/components/post-list/index.gjs
+++ b/app/assets/javascripts/discourse/app/components/post-list/index.gjs
@@ -13,6 +13,9 @@
* @args {String} urlPath (optional) - The path to the key in the post object that contains the post URL
* @args {String} titlePath (optional) - The path to the key in the post object that contains the post title
* @args {String} usernamePath (optional) - The path to the key in the post object that contains the post author's username
+ * @args {Boolean} bulkSelectEnabled (optional) - Whether to enable bulk selection functionality
+ * @args {PostBulkSelectHelper} bulkSelectHelper (optional) - Helper for managing bulk selection state
+ * @args {Array} bulkActions (optional) - Array of bulk action objects for the bulk controls
*
* @template Usage Example:
* ```
@@ -22,7 +25,9 @@
* @fetchMorePosts={{this.loadMorePosts}}
* @emptyText={{i18n "custom_identifier.empty"}}
* @additionalItemClasses="custom-class"
- *
+ * @bulkSelectEnabled={{true}}
+ * @bulkSelectHelper={{this.bulkSelectHelper}}
+ * @bulkActions={{this.bulkActions}}
* />
* ```
*/
@@ -31,7 +36,9 @@ import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
import LoadMore from "discourse/components/load-more";
+import PostListBulkControls from "discourse/components/post-list/bulk-controls";
import PostListItem from "discourse/components/post-list/item";
+import concatClass from "discourse/helpers/concat-class";
import hideApplicationFooter from "discourse/helpers/hide-application-footer";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { i18n } from "discourse-i18n";
@@ -72,7 +79,22 @@ export default class PostList extends Component {
{{/if}}
<LoadMore @action={{this.loadMore}}>
- <div class="post-list" ...attributes>
+ {{#if @bulkSelectEnabled}}
+ {{#if @bulkSelectHelper.hasSelection}}
+ <PostListBulkControls
+ @bulkSelectHelper={{@bulkSelectHelper}}
+ @bulkActions={{@bulkActions}}
+ />
+ {{/if}}
+ {{/if}}
+
+ <div
+ class={{concatClass
+ "post-list"
+ (if @bulkSelectEnabled "post-list--bulk-select")
+ }}
+ ...attributes
+ >
{{#each @posts as |post|}}
<PostListItem
@post={{post}}
@@ -85,6 +107,8 @@ export default class PostList extends Component {
@showUserInfo={{@showUserInfo}}
@resumeDraft={{@resumeDraft}}
@removeDraft={{@removeDraft}}
+ @bulkSelectEnabled={{@bulkSelectEnabled}}
+ @bulkSelectHelper={{@bulkSelectHelper}}
>
<:abovePostItemHeader>
{{yield post to="abovePostItemHeader"}}
diff --git a/app/assets/javascripts/discourse/app/components/post-list/item/index.gjs b/app/assets/javascripts/discourse/app/components/post-list/item/index.gjs
index 8d5b474cad4..3ba4f8048dd 100644
--- a/app/assets/javascripts/discourse/app/components/post-list/item/index.gjs
+++ b/app/assets/javascripts/discourse/app/components/post-list/item/index.gjs
@@ -1,5 +1,7 @@
import Component from "@glimmer/component";
import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import { or } from "truth-helpers";
@@ -73,6 +75,33 @@ export default class PostListItem extends Component {
}
}
+ get isSelected() {
+ if (!this.args.bulkSelectEnabled || !this.args.bulkSelectHelper) {
+ return false;
+ }
+ return this.args.bulkSelectHelper.isSelected(this.args.post);
+ }
+
+ get itemClasses() {
+ return concatClass(
+ "post-list-item",
+ this.moderatorActionClass,
+ this.primaryGroupClass,
+ this.hiddenClass,
+ this.args.additionalItemClasses,
+ this.isSelected ? "post-list-item--selected" : ""
+ );
+ }
+
+ @action
+ toggleSelection(event) {
+ if (this.args.bulkSelectHelper) {
+ this.args.bulkSelectHelper.togglePost(this.args.post, {
+ shiftKey: event?.shiftKey || false,
+ });
+ }
+ }
+
@bind
decoratePostContent(element, helper) {
this.appEvents.trigger(
@@ -83,18 +112,21 @@ export default class PostListItem extends Component {
}
<template>
- <div
- class="post-list-item
- {{concatClass
- this.moderatorActionClass
- this.primaryGroupClass
- this.hiddenClass
- @additionalItemClasses
- }}"
- >
+ <div class={{this.itemClasses}}>
{{yield to="abovePostItemHeader"}}
<div class="post-list-item__header info">
+ {{#if @bulkSelectEnabled}}
+ <div class="post-list-item__bulk-select">
+ <input
+ type="checkbox"
+ checked={{this.isSelected}}
+ {{on "click" this.toggleSelection}}
+ class="bulk-select-checkbox"
+ />
+ </div>
+ {{/if}}
+
{{#if this.isDraft}}
<div class="draft-icon">
{{icon this.draftIcon class="icon"}}
diff --git a/app/assets/javascripts/discourse/app/components/user-stream.gjs b/app/assets/javascripts/discourse/app/components/user-stream.gjs
index b85b4d5758c..50b64282c44 100644
--- a/app/assets/javascripts/discourse/app/components/user-stream.gjs
+++ b/app/assets/javascripts/discourse/app/components/user-stream.gjs
@@ -2,6 +2,7 @@ import Component from "@glimmer/component";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { getOwner } from "@ember/owner";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { service } from "@ember/service";
import PluginOutlet from "discourse/components/plugin-outlet";
import PostActionDescription from "discourse/components/post-action-description";
@@ -12,6 +13,7 @@ import icon from "discourse/helpers/d-icon";
import lazyHash from "discourse/helpers/lazy-hash";
import { popupAjaxError } from "discourse/lib/ajax-error";
import ClickTrack from "discourse/lib/click-track";
+import PostBulkSelectHelper from "discourse/lib/post-bulk-select-helper";
import DiscourseURL from "discourse/lib/url";
import Draft from "discourse/models/draft";
import Post from "discourse/models/post";
@@ -22,6 +24,46 @@ export default class UserStreamComponent extends Component {
@service composer;
@service router;
+ bulkSelectHelper = new PostBulkSelectHelper(this);
+
+ constructor() {
+ super(...arguments);
+ this.updateBulkSelectPosts();
+ }
+
+ @action
+ updateBulkSelectPosts() {
+ if (this.isDraftsRoute && this.args.stream?.content) {
+ this.bulkSelectHelper.updatePosts(this.args.stream.content);
+ }
+ }
+
+ get isDraftsRoute() {
+ return this.router.currentRouteName === "userActivity.drafts";
+ }
+
+ get bulkSelectEnabled() {
+ return this.isDraftsRoute && this.args.stream?.content?.length > 0;
+ }
+
+ get showBulkSelectHelper() {
+ return this.isDraftsRoute ? this.bulkSelectHelper : null;
+ }
+
+ get bulkActions() {
+ if (this.isDraftsRoute) {
+ return [
+ {
+ label: "drafts.bulk_delete",
+ icon: "trash-can",
+ action: this.bulkDeleteDrafts,
+ class: "btn-danger",
+ },
+ ];
+ }
+ return [];
+ }
+
get filterClassName() {
const filter = this.args.stream?.filter;
@@ -91,6 +133,30 @@ export default class UserStreamComponent extends Component {
});
}
+ @action
+ async bulkDeleteDrafts(selectedDrafts) {
+ const count = selectedDrafts.length;
+ this.dialog.deleteConfirm({
+ title: i18n("drafts.bulk_delete_confirmation"),
+ message: i18n("drafts.bulk_delete_message", { count }),
+ didConfirm: async () => {
+ try {
+ await Draft.bulkClear(selectedDrafts);
+
+ // Batch DOM updates after successful bulk delete
+ selectedDrafts.forEach((draft) => {
+ this.args.stream.remove(draft);
+ });
+
+ // Clear the bulk selection after successful deletion
+ this.showBulkSelectHelper?.clearAll();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ },
+ });
+ }
+
@action
async loadMore() {
await this.args.stream.findItems();
@@ -126,8 +192,12 @@ export default class UserStreamComponent extends Component {
@showUserInfo={{false}}
@resumeDraft={{this.resumeDraft}}
@removeDraft={{this.removeDraft}}
+ @bulkSelectEnabled={{this.bulkSelectEnabled}}
+ @bulkSelectHelper={{this.showBulkSelectHelper}}
+ @bulkActions={{this.bulkActions}}
class={{concatClass "user-stream" this.filterClassName}}
{{on "click" this.handleClick}}
+ {{didUpdate this.updateBulkSelectPosts @stream.content}}
>
<:abovePostItemHeader as |post|>
<PluginOutlet
diff --git a/app/assets/javascripts/discourse/app/lib/post-bulk-select-helper.js b/app/assets/javascripts/discourse/app/lib/post-bulk-select-helper.js
new file mode 100644
index 00000000000..39f90c6f8bb
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/lib/post-bulk-select-helper.js
@@ -0,0 +1,183 @@
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { getOwner, setOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import { TrackedArray } from "@ember-compat/tracked-built-ins";
+
+/**
+ * Helper class for managing bulk selection of posts
+ * Similar to BulkSelectHelper but specialized for posts
+ *
+ * Features:
+ * - Individual post selection/deselection
+ * - Select All / Clear All functionality
+ * - Shift+click range selection (like topic lists)
+ * - Bulk action execution
+ */
+export default class PostBulkSelectHelper {
+ @service modal;
+
+ @tracked loading = false;
+ @tracked lastClickedPost = null;
+ @tracked posts = null;
+ selected = new TrackedArray();
+
+ constructor(context, posts = null) {
+ setOwner(this, getOwner(context));
+ this.posts = posts;
+ }
+
+ /**
+ * Update posts and clean up stale selections
+ * @param {Array} newPosts - New posts array
+ */
+ updatePosts(newPosts) {
+ this.posts = newPosts;
+ this.#cleanupStaleSelections();
+ }
+
+ /**
+ * Remove selections for posts that no longer exist
+ */
+ #cleanupStaleSelections() {
+ if (!this.posts) {
+ this.selected.length = 0;
+ return;
+ }
+
+ const validPostIds = new Set(
+ this.posts.map((post) => this.getPostId(post))
+ );
+ const validSelections = this.selected.filter((selected) =>
+ validPostIds.has(this.getPostId(selected))
+ );
+
+ // Only update if there are stale selections
+ if (validSelections.length !== this.selected.length) {
+ this.selected.length = 0;
+ this.selected.push(...validSelections);
+
+ // Clear last clicked if it's no longer valid
+ if (
+ this.lastClickedPost &&
+ !validPostIds.has(this.getPostId(this.lastClickedPost))
+ ) {
+ this.lastClickedPost = null;
+ }
+ }
+ }
+
+ get selectedCount() {
+ return this.selected.length;
+ }
+
+ get hasSelection() {
+ return this.selected.length > 0;
+ }
+
+ get allSelected() {
+ return this.posts && this.selected.length === this.posts.length;
+ }
+
+ @action
+ selectPost(post) {
+ if (!this.isSelected(post)) {
+ this.selected.push(post);
+ }
+ }
+
+ @action
+ deselectPost(post) {
+ const index = this.selected.findIndex(
+ (p) => this.getPostId(p) === this.getPostId(post)
+ );
+ if (index > -1) {
+ this.selected.splice(index, 1);
+ }
+ }
+
+ @action
+ togglePost(post, options = {}) {
+ const { shiftKey = false } = options;
+
+ if (shiftKey && this.lastClickedPost && this.posts) {
+ this.selectRange(this.lastClickedPost, post);
+ } else {
+ if (this.isSelected(post)) {
+ this.deselectPost(post);
+ } else {
+ this.selectPost(post);
+ }
+ this.lastClickedPost = post;
+ }
+ }
+
+ selectRange(startPost, endPost) {
+ if (!this.posts) {
+ return;
+ }
+
+ const startIndex = this.posts.findIndex(
+ (p) => this.getPostId(p) === this.getPostId(startPost)
+ );
+ const endIndex = this.posts.findIndex(
+ (p) => this.getPostId(p) === this.getPostId(endPost)
+ );
+
+ if (startIndex === -1 || endIndex === -1) {
+ return;
+ }
+
+ const minIndex = Math.min(startIndex, endIndex);
+ const maxIndex = Math.max(startIndex, endIndex);
+
+ // Select all posts in the range
+ for (let i = minIndex; i <= maxIndex; i++) {
+ const post = this.posts[i];
+ if (post && !this.isSelected(post)) {
+ this.selectPost(post);
+ }
+ }
+
+ this.lastClickedPost = endPost;
+ }
+
+ @action
+ selectAll() {
+ if (this.posts) {
+ this.selected.length = 0;
+ this.selected.push(...this.posts);
+ }
+ }
+
+ @action
+ clearAll() {
+ this.selected.length = 0;
+ this.lastClickedPost = null;
+ }
+
+ isSelected(post) {
+ return this.selected.some(
+ (p) => this.getPostId(p) === this.getPostId(post)
+ );
+ }
+
+ getPostId(post) {
+ // Support different post types with different id paths
+ return post.id || post.post_id || post.draft_key;
+ }
+
+ async performBulkAction(actionFn) {
+ if (!this.hasSelection) {
+ return;
+ }
+
+ this.loading = true;
+ try {
+ await actionFn(this.selected);
+ this.clearAll();
+ } finally {
+ this.loading = false;
+ }
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/models/draft.js b/app/assets/javascripts/discourse/app/models/draft.js
index 02033f1fc74..2b55be7f2c0 100644
--- a/app/assets/javascripts/discourse/app/models/draft.js
+++ b/app/assets/javascripts/discourse/app/models/draft.js
@@ -9,6 +9,19 @@ export default class Draft extends EmberObject {
});
}
+ static bulkClear(drafts) {
+ const draft_keys = drafts.map((d) => d.draft_key);
+ const sequences = {};
+ drafts.forEach((d) => {
+ sequences[d.draft_key] = d.sequence;
+ });
+
+ return ajax("/drafts/bulk_destroy.json", {
+ type: "DELETE",
+ data: { draft_keys, sequences },
+ });
+ }
+
static get(key) {
return ajax(`/drafts/${key}.json`);
}
diff --git a/app/assets/javascripts/discourse/tests/integration/components/post-list-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/post-list-test.gjs
index fd3dac6d7a6..cccf9c82f19 100644
--- a/app/assets/javascripts/discourse/tests/integration/components/post-list-test.gjs
+++ b/app/assets/javascripts/discourse/tests/integration/components/post-list-test.gjs
@@ -1,7 +1,8 @@
-import { render } from "@ember/test-helpers";
+import { click, render } from "@ember/test-helpers";
import { module, test } from "qunit";
import PostList from "discourse/components/post-list";
import { cloneJSON } from "discourse/lib/object";
+import PostBulkSelectHelper from "discourse/lib/post-bulk-select-helper";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import postModel from "../../fixtures/post-list";
@@ -114,4 +115,272 @@ module("Integration | Component | PostList | Index", function (hooks) {
.dom(".post-list-item__header .avatar-link")
.hasAttribute("data-user-card", "john");
});
+
+ module("bulk selection", function () {
+ test("shows checkboxes when @bulkSelectEnabled is true", async function (assert) {
+ const posts = cloneJSON(postModel);
+ const bulkSelectHelper = new PostBulkSelectHelper(this, posts);
+
+ await render(
+ <template>
+ <PostList
+ @posts={{posts}}
+ @bulkSelectEnabled={{true}}
+ @bulkSelectHelper={{bulkSelectHelper}}
+ />
+ </template>
+ );
+
+ assert.dom(".bulk-select-checkbox").exists({ count: 2 });
+ assert.dom(".post-list-item__bulk-select").exists({ count: 2 });
+ });
+
+ test("hides checkboxes when @bulkSelectEnabled is false", async function (assert) {
+ const posts = cloneJSON(postModel);
+
+ await render(
+ <template>
+ <PostList @posts={{posts}} @bulkSelectEnabled={{false}} />
+ </template>
+ );
+
+ assert.dom(".bulk-select-checkbox").doesNotExist();
+ assert.dom(".post-list-item__bulk-select").doesNotExist();
+ });
+
+ test("shows bulk controls only when items are selected", async function (assert) {
+ const posts = cloneJSON(postModel);
+ const bulkSelectHelper = new PostBulkSelectHelper(this, posts);
+
+ await render(
+ <template>
+ <PostList
+ @posts={{posts}}
+ @bulkSelectEnabled={{true}}
+ @bulkSelectHelper={{bulkSelectHelper}}
+ />
+ </template>
+ );
+
+ // Initially no controls should be visible
+ assert.dom(".post-list-bulk-controls").doesNotExist();
+
+ // Select a post
+ await click(".bulk-select-checkbox");
+
+ // Now controls should be visible
+ assert.dom(".post-list-bulk-controls").exists();
+ assert.dom(".post-list-bulk-controls__count").containsText("1");
+ });
+
+ test("selecting posts updates the selection count", async function (assert) {
+ const posts = cloneJSON(postModel);
+ const bulkSelectHelper = new PostBulkSelectHelper(this, posts);
+
+ await render(
+ <template>
+ <PostList
+ @posts={{posts}}
+ @bulkSelectEnabled={{true}}
+ @bulkSelectHelper={{bulkSelectHelper}}
+ />
+ </template>
+ );
+
+ // Select first post
+ await click(".post-list-item:first-child .bulk-select-checkbox");
+ assert.dom(".post-list-bulk-controls__count").containsText("1");
+
+ // Select second post
+ await click(".post-list-item:last-child .bulk-select-checkbox");
+ assert.dom(".post-list-bulk-controls__count").containsText("2");
+ });
+
+ test("select all button selects all posts", async function (assert) {
+ const posts = cloneJSON(postModel);
+ const bulkSelectHelper = new PostBulkSelectHelper(this, posts);
+
+ await render(
+ <template>
+ <PostList
+ @posts={{posts}}
+ @bulkSelectEnabled={{true}}
+ @bulkSelectHelper={{bulkSelectHelper}}
+ />
+ </template>
+ );
+
+ // Select one post to show controls
+ await click(".bulk-select-checkbox");
+
+ // Click select all
+ await click(".bulk-select-all");
+
+ // All checkboxes should be checked
+ assert.dom(".bulk-select-checkbox:checked").exists({ count: 2 });
+ assert.dom(".post-list-bulk-controls__count").containsText("2");
+ });
+
+ test("clear all button deselects all posts", async function (assert) {
+ const posts = cloneJSON(postModel);
+ const bulkSelectHelper = new PostBulkSelectHelper(this, posts);
+
+ await render(
+ <template>
+ <PostList
+ @posts={{posts}}
+ @bulkSelectEnabled={{true}}
+ @bulkSelectHelper={{bulkSelectHelper}}
+ />
+ </template>
+ );
+
+ // Select all posts
+ await click(".bulk-select-checkbox");
+ await click(".bulk-select-all");
+
+ // Clear all
+ await click(".bulk-clear-all");
+
+ // No checkboxes should be checked and controls should be hidden
+ assert.dom(".bulk-select-checkbox:checked").doesNotExist();
+ assert.dom(".post-list-bulk-controls").doesNotExist();
+ });
+
+ test("shows selected class on selected items", async function (assert) {
+ const posts = cloneJSON(postModel);
+ const bulkSelectHelper = new PostBulkSelectHelper(this, posts);
+
+ await render(
+ <template>
+ <PostList
+ @posts={{posts}}
+ @bulkSelectEnabled={{true}}
+ @bulkSelectHelper={{bulkSelectHelper}}
+ />
+ </template>
+ );
+
+ // Initially no items should have selected class
+ assert.dom(".post-list-item--selected").doesNotExist();
+
+ // Select first post
+ await click(".post-list-item:first-child .bulk-select-checkbox");
+
+ // First item should have selected class
+ assert
+ .dom(".post-list-item:first-child")
+ .hasClass("post-list-item--selected");
+ assert
+ .dom(".post-list-item:last-child")
+ .doesNotHaveClass("post-list-item--selected");
+ });
+
+ test("bulk actions dropdown appears when items are selected", async function (assert) {
+ const posts = cloneJSON(postModel);
+ const bulkSelectHelper = new PostBulkSelectHelper(this, posts);
+ const bulkActions = [
+ {
+ label: "test.bulk_delete",
+ icon: "trash-can",
+ action: () => {},
+ class: "btn-danger",
+ },
+ ];
+
+ await render(
+ <template>
+ <PostList
+ @posts={{posts}}
+ @bulkSelectEnabled={{true}}
+ @bulkSelectHelper={{bulkSelectHelper}}
+ @bulkActions={{bulkActions}}
+ />
+ </template>
+ );
+
+ // Initially no dropdown should be visible
+ assert.dom(".bulk-actions-dropdown").doesNotExist();
+
+ // Select a post
+ await click(".bulk-select-checkbox");
+
+ // Dropdown should now be visible
+ assert.dom(".bulk-actions-dropdown").exists();
+ });
+
+ test("toggles selection when clicking checkbox", async function (assert) {
+ const posts = cloneJSON(postModel);
+ const bulkSelectHelper = new PostBulkSelectHelper(this, posts);
+
+ await render(
+ <template>
+ <PostList
+ @posts={{posts}}
+ @bulkSelectEnabled={{true}}
+ @bulkSelectHelper={{bulkSelectHelper}}
+ />
+ </template>
+ );
+
+ const checkbox = ".post-list-item:first-child .bulk-select-checkbox";
+
+ // Initially unchecked
+ assert.dom(checkbox).isNotChecked();
+
+ // Click to select
+ await click(checkbox);
+ assert.dom(checkbox).isChecked();
+
+ // Click to deselect
+ await click(checkbox);
+ assert.dom(checkbox).isNotChecked();
+ assert.dom(".post-list-bulk-controls").doesNotExist();
+ });
+
+ test("bulk action execution calls provided action function", async function (assert) {
+ const posts = cloneJSON(postModel);
+ const bulkSelectHelper = new PostBulkSelectHelper(this, posts);
+
+ let bulkActionCalled = false;
+ let bulkActionPosts = null;
+
+ const bulkActions = [
+ {
+ label: "test.bulk_delete",
+ icon: "trash-can",
+ action: (selectedPosts) => {
+ bulkActionCalled = true;
+ bulkActionPosts = selectedPosts;
+ },
+ class: "btn-danger",
+ },
+ ];
+
+ await render(
+ <template>
+ <PostList
+ @posts={{posts}}
+ @bulkSelectEnabled={{true}}
+ @bulkSelectHelper={{bulkSelectHelper}}
+ @bulkActions={{bulkActions}}
+ />
+ </template>
+ );
+
+ // Select a post
+ await click(".bulk-select-checkbox");
+
+ // Open dropdown and click bulk action
+ await click(".bulk-actions-dropdown");
+ await click(".dropdown-menu .btn-danger");
+
+ assert.true(bulkActionCalled, "Bulk action should have been called");
+ assert.strictEqual(
+ bulkActionPosts.length,
+ 1,
+ "Should pass selected posts to action"
+ );
+ });
+ });
});
diff --git a/app/assets/stylesheets/common/components/post-list.scss b/app/assets/stylesheets/common/components/post-list.scss
index 8fc9584f7bc..d856461a9fd 100644
--- a/app/assets/stylesheets/common/components/post-list.scss
+++ b/app/assets/stylesheets/common/components/post-list.scss
@@ -1,6 +1,27 @@
+@use "lib/viewport";
+
.post-list {
margin: 0;
+ &--bulk-select {
+ .post-list-item {
+ &--selected {
+ background: var(--d-selected);
+ border-left: 3px solid var(--tertiary);
+ }
+
+ &__bulk-select {
+ margin-right: 0.75rem;
+ align-self: flex-start;
+ margin-top: 0.2rem;
+
+ .bulk-select-checkbox {
+ margin: 0;
+ }
+ }
+ }
+ }
+
.post-list-item {
background: var(--d-content-background, var(--secondary));
border-bottom: 1px solid var(--content-border-color);
@@ -91,3 +112,41 @@
display: flex;
}
}
+
+// Bulk controls styles
+.post-list-bulk-controls {
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ padding: 0.75rem 1rem;
+ margin-bottom: 1rem;
+ border-radius: var(--d-border-radius);
+
+ &__selection {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+
+ @include viewport.until(sm) {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.5rem;
+ }
+ }
+
+ &__count {
+ font-weight: 500;
+ color: var(--primary);
+ }
+
+ &__actions {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+
+ .btn {
+ margin: 0;
+ }
+ }
+}
diff --git a/app/controllers/drafts_controller.rb b/app/controllers/drafts_controller.rb
index b2629fa7994..da11cec64d1 100644
--- a/app/controllers/drafts_controller.rb
+++ b/app/controllers/drafts_controller.rb
@@ -154,6 +154,63 @@ class DraftsController < ApplicationController
render json: success_json
end
+ def bulk_destroy
+ params.require(:draft_keys)
+
+ draft_keys = params[:draft_keys]
+ sequences = params[:sequences] || {}
+
+ return render json: success_json.merge(deleted_count: 0) if draft_keys.empty?
+
+ user =
+ if is_api?
+ if @guardian.is_admin?
+ fetch_user_from_params
+ else
+ raise Discourse::InvalidAccess
+ end
+ else
+ current_user
+ end
+
+ # Validate all sequences first (fail fast)
+ sequence_errors = []
+ draft_keys.each do |draft_key|
+ begin
+ current_sequence = DraftSequence.current(user, draft_key)
+ provided_sequence = sequences[draft_key].to_i
+ sequence_errors << draft_key if provided_sequence != current_sequence
+ rescue StandardError
+ # If we can't get sequence for some reason, skip validation for this draft
+ # This maintains the same lenient behavior as the single delete
+ end
+ end
+
+ if sequence_errors.any?
+ render json:
+ failed_json.merge(
+ errors: "Draft sequence conflict for keys: #{sequence_errors.join(", ")}",
+ ),
+ status: 409
+ return
+ end
+
+ # Bulk delete in single transaction
+ deleted_count = 0
+ begin
+ ActiveRecord::Base.transaction do
+ deleted_count = Draft.where(user_id: user.id, draft_key: draft_keys).destroy_all.length
+
+ # Update user draft count
+ UserStat.update_draft_count(user.id)
+ end
+ rescue StandardError => e
+ return render json: failed_json.merge(errors: e.message), status: 500
+ end
+
+ render json: success_json.merge(deleted_count: deleted_count)
+ end
+
private
def reached_max_drafts_per_user?(params)
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index ed15b24730e..b70562ae0fc 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -605,6 +605,11 @@ en:
resume: "Resume"
remove: "Remove"
remove_confirmation: "Are you sure you want to delete this draft?"
+ bulk_delete: "Delete selected"
+ bulk_delete_confirmation: "Delete drafts"
+ bulk_delete_message:
+ one: "Are you sure you want to delete this draft?"
+ other: "Are you sure you want to delete these %{count} drafts?"
new_topic: "New topic draft"
new_private_message: "New personal message draft"
edit_topic: "Edit topic draft"
@@ -4073,6 +4078,13 @@ en:
title: "Latest posts"
empty: "There are no posts"
aria_post_number: "%{title} - post #%{postNumber}"
+ bulk:
+ selected:
+ one: "%{count} post selected"
+ other: "%{count} posts selected"
+ select_all: "Select all"
+ clear_all: "Clear all"
+ actions: "Bulk actions"
post:
confirm_delete: "Are you sure you want to delete this post?"
diff --git a/config/routes.rb b/config/routes.rb
index 6f4a99b6c52..fcf65f8c711 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1608,7 +1608,9 @@ Discourse::Application.routes.draw do
get "message-bus/poll" => "message_bus#poll"
- resources :drafts, only: %i[index create show destroy]
+ resources :drafts, only: %i[index create show destroy] do
+ collection { delete :bulk_destroy }
+ end
get "/service-worker.js" => "static#service_worker_asset", :format => :js
diff --git a/spec/requests/drafts_controller_spec.rb b/spec/requests/drafts_controller_spec.rb
index aa77f328599..42ace161243 100644
--- a/spec/requests/drafts_controller_spec.rb
+++ b/spec/requests/drafts_controller_spec.rb
@@ -443,4 +443,168 @@ RSpec.describe DraftsController do
end
end
end
+
+ describe "#bulk_destroy" do
+ it "requires you to be logged in" do
+ delete "/drafts/bulk_destroy.json"
+ expect(response.status).to eq(403)
+ end
+
+ it "destroys multiple drafts when required" do
+ sign_in(user)
+
+ # Create multiple drafts
+ Draft.set(user, "draft1", 0, '{"reply": "draft 1 content"}')
+ Draft.set(user, "draft2", 0, '{"reply": "draft 2 content"}')
+ Draft.set(user, "draft3", 0, '{"reply": "draft 3 content"}')
+
+ expect(Draft.where(user: user).count).to eq(3)
+
+ delete "/drafts/bulk_destroy.json",
+ params: {
+ draft_keys: %w[draft1 draft2],
+ sequences: {
+ "draft1" => 0,
+ "draft2" => 0,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq("OK")
+ expect(response.parsed_body["deleted_count"]).to eq(2)
+
+ # Verify drafts were deleted
+ expect(Draft.get(user, "draft1", 0)).to eq(nil)
+ expect(Draft.get(user, "draft2", 0)).to eq(nil)
+ expect(Draft.get(user, "draft3", 0)).to be_present
+ expect(Draft.where(user: user).count).to eq(1)
+ end
+
+ it "handles empty draft_keys array" do
+ sign_in(user)
+
+ delete "/drafts/bulk_destroy.json", params: { draft_keys: [] }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["deleted_count"]).to eq(0)
+ end
+
+ it "validates sequences and returns error for conflicts" do
+ sign_in(user)
+
+ Draft.set(user, "draft1", 0, '{"reply": "draft 1 content"}')
+ Draft.set(user, "draft2", 0, '{"reply": "draft 2 content"}')
+
+ delete "/drafts/bulk_destroy.json",
+ params: {
+ draft_keys: %w[draft1 draft2],
+ sequences: {
+ "draft1" => 0,
+ "draft2" => 99,
+ }, # Wrong sequence for draft2
+ }
+
+ expect(response.status).to eq(409)
+ expect(response.parsed_body["failed"]).to eq("FAILED")
+ expect(response.parsed_body["errors"]).to include("draft2")
+
+ # Verify no drafts were deleted due to sequence conflict
+ expect(Draft.get(user, "draft1", 0)).to be_present
+ expect(Draft.get(user, "draft2", 0)).to be_present
+ end
+
+ it "handles missing sequences parameter gracefully" do
+ sign_in(user)
+
+ Draft.set(user, "draft1", 0, '{"reply": "draft 1 content"}')
+
+ delete "/drafts/bulk_destroy.json", params: { draft_keys: ["draft1"] }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["deleted_count"]).to eq(1)
+ expect(Draft.get(user, "draft1", 0)).to eq(nil)
+ end
+
+ it "requires draft_keys parameter" do
+ sign_in(user)
+
+ delete "/drafts/bulk_destroy.json", params: {}
+
+ expect(response.status).to eq(400)
+ end
+
+ it "updates user draft count after bulk deletion" do
+ sign_in(user)
+
+ # Create multiple drafts
+ 3.times { |i| Draft.set(user, "draft#{i}", 0, '{"reply": "content"}') }
+
+ initial_draft_count = user.user_stat.draft_count
+ expect(initial_draft_count).to be >= 3
+
+ delete "/drafts/bulk_destroy.json",
+ params: {
+ draft_keys: %w[draft0 draft1 draft2],
+ sequences: {
+ "draft0" => 0,
+ "draft1" => 0,
+ "draft2" => 0,
+ },
+ }
+
+ expect(response.status).to eq(200)
+
+ # Verify user draft count was updated
+ user.user_stat.reload
+ expect(user.user_stat.draft_count).to eq(initial_draft_count - 3)
+ end
+
+ context "when using API access" do
+ it "allows admin to delete other user's drafts via API" do
+ admin = Fabricate(:admin)
+ api_key = Fabricate(:api_key, user: admin)
+
+ Draft.set(user, "draft1", 0, '{"reply": "draft content"}')
+
+ delete "/drafts/bulk_destroy.json",
+ params: {
+ draft_keys: ["draft1"],
+ sequences: {
+ "draft1" => 0,
+ },
+ username: user.username,
+ },
+ headers: {
+ "Api-Key" => api_key.key,
+ "Api-Username" => admin.username,
+ }
+
+ expect(response.status).to eq(200)
+ expect(Draft.get(user, "draft1", 0)).to eq(nil)
+ end
+
+ it "denies non-admin API access to other user's drafts" do
+ non_admin = Fabricate(:user)
+ api_key = Fabricate(:api_key, user: non_admin)
+
+ Draft.set(user, "draft1", 0, '{"reply": "draft content"}')
+
+ delete "/drafts/bulk_destroy.json",
+ params: {
+ draft_keys: ["draft1"],
+ sequences: {
+ "draft1" => 0,
+ },
+ username: user.username,
+ },
+ headers: {
+ "Api-Key" => api_key.key,
+ "Api-Username" => non_admin.username,
+ }
+
+ expect(response.status).to eq(403)
+ expect(Draft.get(user, "draft1", 0)).to be_present
+ end
+ end
+ end
end
diff --git a/spec/system/page_objects/pages/user_activity_drafts.rb b/spec/system/page_objects/pages/user_activity_drafts.rb
new file mode 100644
index 00000000000..eb21bd49739
--- /dev/null
+++ b/spec/system/page_objects/pages/user_activity_drafts.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ class UserActivityDrafts < PageObjects::Pages::Base
+ def visit(user)
+ page.visit("/u/#{user.username_lower}/activity/drafts")
+ self
+ end
+
+ def has_drafts?(count: 1)
+ page.has_css?(".post-list-item", count: count)
+ end
+
+ def has_no_drafts?
+ page.has_css?(".post-list__empty-text")
+ end
+
+ def has_bulk_select_checkboxes?
+ page.has_css?(".bulk-select-checkbox", minimum: 1)
+ end
+
+ def has_no_bulk_select_checkboxes?
+ page.has_no_css?(".bulk-select-checkbox")
+ end
+
+ def has_bulk_controls?
+ page.has_css?(".post-list-bulk-controls")
+ end
+
+ def has_no_bulk_controls?
+ page.has_no_css?(".post-list-bulk-controls")
+ end
+
+ def select_draft(index = 0)
+ checkboxes = page.all(".bulk-select-checkbox")
+ checkboxes[index].click
+ self
+ end
+
+ def select_all_drafts
+ click_bulk_select_all
+ self
+ end
+
+ def clear_all_selections
+ click_bulk_clear_all
+ self
+ end
+
+ def click_bulk_select_all
+ page.find(".bulk-select-all").click
+ self
+ end
+
+ def click_bulk_clear_all
+ page.find(".bulk-clear-all").click
+ self
+ end
+
+ def click_bulk_actions
+ page.find("button", text: "Bulk actions").click
+ self
+ end
+
+ def click_bulk_delete
+ click_bulk_actions
+ page.find(".dropdown-menu .btn-danger").click
+ self
+ end
+
+ def selected_count_text
+ page.find(".post-list-bulk-controls__count").text
+ end
+
+ def has_selected_count?(count)
+ if count == 1
+ page.has_content?("#{count} post selected")
+ else
+ page.has_content?("#{count} posts selected")
+ end
+ end
+
+ def has_draft_selected?(index = 0)
+ drafts = page.all(".post-list-item")
+ drafts[index].has_css?(".post-list-item--selected")
+ end
+
+ def has_no_draft_selected?(index = 0)
+ drafts = page.all(".post-list-item")
+ drafts[index].has_no_css?(".post-list-item--selected")
+ end
+
+ def has_checkbox_checked?(index = 0)
+ checkboxes = page.all(".bulk-select-checkbox")
+ checkboxes[index].checked?
+ end
+
+ def has_checkbox_unchecked?(index = 0)
+ checkboxes = page.all(".bulk-select-checkbox")
+ !checkboxes[index].checked?
+ end
+ end
+ end
+end
diff --git a/spec/system/user_activity_drafts_spec.rb b/spec/system/user_activity_drafts_spec.rb
new file mode 100644
index 00000000000..0a9d8558b4d
--- /dev/null
+++ b/spec/system/user_activity_drafts_spec.rb
@@ -0,0 +1,181 @@
+# frozen_string_literal: true
+
+describe "User activity drafts", type: :system do
+ fab!(:user)
+ let(:drafts_page) { PageObjects::Pages::UserActivityDrafts.new }
+
+ before { sign_in(user) }
+
+ describe "bulk selection functionality" do
+ before do
+ # Create some drafts for testing
+ Draft.set(
+ user,
+ "#{Draft::NEW_TOPIC}_1",
+ 0,
+ { title: "Draft topic 1", reply: "First draft content" }.to_json,
+ )
+ Draft.set(
+ user,
+ "#{Draft::NEW_TOPIC}_2",
+ 0,
+ { title: "Draft topic 2", reply: "Second draft content" }.to_json,
+ )
+ Draft.set(
+ user,
+ "#{Draft::NEW_TOPIC}_3",
+ 0,
+ { title: "Draft topic 3", reply: "Third draft content" }.to_json,
+ )
+ end
+
+ it "shows bulk select checkboxes for drafts" do
+ drafts_page.visit(user)
+
+ expect(drafts_page).to have_drafts(count: 3)
+ expect(drafts_page).to have_bulk_select_checkboxes
+ end
+
+ it "shows bulk controls only after selecting items" do
+ drafts_page.visit(user)
+
+ # Initially no bulk controls should be visible
+ expect(drafts_page).to have_no_bulk_controls
+
+ # Select a draft
+ drafts_page.select_draft(0)
+
+ # Now bulk controls should be visible
+ expect(drafts_page).to have_bulk_controls
+ expect(drafts_page).to have_selected_count(1)
+ end
+
+ it "updates selection count when selecting multiple drafts" do
+ drafts_page.visit(user)
+
+ # Select first draft
+ drafts_page.select_draft(0)
+ expect(drafts_page).to have_selected_count(1)
+
+ # Select second draft
+ drafts_page.select_draft(1)
+ expect(drafts_page).to have_selected_count(2)
+
+ # Select third draft
+ drafts_page.select_draft(2)
+ expect(drafts_page).to have_selected_count(3)
+ end
+
+ it "selects all drafts with select all button" do
+ drafts_page.visit(user)
+
+ # Select one draft to show controls
+ drafts_page.select_draft(0)
+ expect(drafts_page).to have_bulk_controls
+
+ # Click select all
+ drafts_page.click_bulk_select_all
+ expect(drafts_page).to have_selected_count(3)
+
+ # All checkboxes should be checked
+ expect(drafts_page).to have_checkbox_checked(0)
+ expect(drafts_page).to have_checkbox_checked(1)
+ expect(drafts_page).to have_checkbox_checked(2)
+ end
+
+ it "clears all selections with clear all button" do
+ drafts_page.visit(user)
+
+ # Select all drafts
+ drafts_page.select_draft(0)
+ drafts_page.select_all_drafts
+
+ # Clear all selections
+ drafts_page.clear_all_selections
+
+ # No checkboxes should be checked and controls should be hidden
+ expect(drafts_page).to have_checkbox_unchecked(0)
+ expect(drafts_page).to have_checkbox_unchecked(1)
+ expect(drafts_page).to have_checkbox_unchecked(2)
+ expect(drafts_page).to have_no_bulk_controls
+ end
+
+ it "shows selected styling on selected items" do
+ drafts_page.visit(user)
+
+ # Select first draft
+ drafts_page.select_draft(0)
+
+ # First item should have selected styling, second should not
+ expect(drafts_page).to have_checkbox_checked(0)
+ expect(drafts_page).to have_checkbox_unchecked(1)
+ end
+
+ it "toggles selection when clicking checkbox" do
+ drafts_page.visit(user)
+
+ # Initially unchecked
+ expect(drafts_page).to have_checkbox_unchecked(0)
+
+ # Click to select
+ drafts_page.select_draft(0)
+ expect(drafts_page).to have_checkbox_checked(0)
+ expect(drafts_page).to have_bulk_controls
+
+ # Click to deselect
+ drafts_page.select_draft(0)
+ expect(drafts_page).to have_checkbox_unchecked(0)
+ expect(drafts_page).to have_no_bulk_controls
+ end
+
+ it "bulk deletes selected drafts" do
+ drafts_page.visit(user)
+
+ # Select first two drafts
+ drafts_page.select_draft(0)
+ drafts_page.select_draft(1)
+ expect(drafts_page).to have_selected_count(2)
+
+ # Bulk delete
+ drafts_page.click_bulk_delete
+
+ # Confirm deletion in modal
+ page.find(".dialog-footer .btn-danger").click
+
+ # Should have only one draft left and no bulk controls
+ expect(drafts_page).to have_drafts(count: 1)
+ expect(drafts_page).to have_no_bulk_controls
+ expect(Draft.count).to eq(1)
+ end
+
+ it "clears selection after successful bulk delete" do
+ drafts_page.visit(user)
+
+ # Select all drafts
+ drafts_page.select_draft(0)
+ drafts_page.select_all_drafts
+ expect(drafts_page).to have_selected_count(3)
+
+ # Bulk delete all
+ drafts_page.click_bulk_delete
+
+ # Confirm deletion
+ page.find(".dialog-footer .btn-danger").click
+
+ # Should have no drafts and no controls
+ expect(drafts_page).to have_no_drafts
+ expect(drafts_page).to have_no_bulk_controls
+ expect(Draft.count).to eq(0)
+ end
+ end
+
+ describe "without bulk selection" do
+ it "does not show bulk select controls when no drafts exist" do
+ drafts_page.visit(user)
+
+ expect(drafts_page).to have_no_drafts
+ expect(drafts_page).to have_no_bulk_select_checkboxes
+ expect(drafts_page).to have_no_bulk_controls
+ end
+ end
+end