Skip to content

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

UX: Better admin emoji page sorting & filtering and service refactors (#41892)

Martin Brennan9e9de80295f7
diff --git a/app/controllers/admin/emoji_controller.rb b/app/controllers/admin/emoji_controller.rb
index ddda72faf03..13013efe870 100644
--- a/app/controllers/admin/emoji_controller.rb
+++ b/app/controllers/admin/emoji_controller.rb
@@ -4,7 +4,13 @@ class Admin::EmojiController < Admin::AdminController
skip_before_action :check_xhr, only: [:export]
def index
- render_serialized(Emoji.custom, EmojiSerializer, root: false)
+ render_serialized(
+ Emoji.custom.sort_by do |emoji|
+ [emoji.group == "default" ? 0 : 1, emoji.group.downcase, emoji.name.downcase]
+ end,
+ EmojiSerializer,
+ root: false,
+ )
end
# NOTE: This kind of custom logic also needs to be implemented to
@@ -13,41 +19,28 @@ class Admin::EmojiController < Admin::AdminController
#
# Until then, preventDirectS3Uploads is set to true in the UppyUploadMixin.
def create
- file = params[:file] || params[:files].first
- name = params[:name] || File.basename(file.original_filename, ".*")
- group = params[:group] ? params[:group].downcase : nil
-
hijack do
- # fix the name
- name = File.basename(name, ".*")
- name = Emoji.sanitize_emoji_name(name)
- upload =
- UploadCreator.new(file.tempfile, file.original_filename, type: "custom_emoji").create_for(
- current_user.id,
- )
-
- good = true
-
- data =
- if upload.persisted?
- custom_emoji =
- CustomEmoji.new(name: name, upload: upload, group: group, user: current_user)
-
- if custom_emoji.save
- StaffActionLogger.new(current_user).log_custom_emoji_create(name, group: group)
-
- Emoji.clear_cache
- { name: custom_emoji.name, url: custom_emoji.upload.url, group: group }
- else
- good = false
- failed_json.merge(errors: custom_emoji.errors.full_messages)
- end
- else
- good = false
- failed_json.merge(errors: upload.errors.full_messages)
+ CustomEmoji::Create.call(service_params) do |result|
+ on_success do |custom_emoji:|
+ render json: {
+ name: custom_emoji.name,
+ url: custom_emoji.upload.url,
+ group: custom_emoji.group,
+ }
end
-
- render json: data.as_json, status: good ? 200 : 422
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :unprocessable_entity
+ end
+ on_model_errors(:upload) do |_, upload:|
+ render json: failed_json.merge(errors: upload.errors.full_messages),
+ status: :unprocessable_entity
+ end
+ on_model_errors(:custom_emoji) do |custom_emoji|
+ render json: failed_json.merge(errors: custom_emoji.errors.full_messages),
+ status: :unprocessable_entity
+ end
+ end
end
end
@@ -130,20 +123,11 @@ class Admin::EmojiController < Admin::AdminController
end
def destroy
- name = params.require(:id)
-
- # NOTE: the upload will automatically be removed by the 'clean_up_uploads' job
- emoji = CustomEmoji.find_by(name: name)
-
- if emoji.present?
- StaffActionLogger.new(current_user).log_custom_emoji_destroy(name)
- emoji.destroy!
+ CustomEmoji::Destroy.call(
+ service_params.deep_merge(params: { name: params.require(:id) }),
+ ) do |result|
+ on_success { render json: success_json }
+ on_failed_contract { raise Discourse::InvalidParameters.new(:name) }
end
-
- Emoji.clear_cache
-
- Jobs.enqueue(:rebake_custom_emoji_posts, name: name)
-
- render json: success_json
end
end
diff --git a/app/services/custom_emoji/create.rb b/app/services/custom_emoji/create.rb
new file mode 100644
index 00000000000..1851c16ea60
--- /dev/null
+++ b/app/services/custom_emoji/create.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+class CustomEmoji::Create
+ include Service::Base
+
+ params do
+ attribute :file
+ attribute :files
+ attribute :name, :string
+ attribute :group, :string
+
+ before_validation :prepare_attributes
+
+ validates :file, presence: true
+
+ private
+
+ def prepare_attributes
+ self.file ||= files&.first
+ self.name = File.basename(name.nil? ? file&.original_filename.to_s : name, ".*")
+ self.name = Emoji.sanitize_emoji_name(name)
+ self.group = group&.downcase
+ end
+ end
+
+ model :upload, :create_upload
+
+ transaction do
+ model :custom_emoji, :create_custom_emoji
+ step :log_creation
+ end
+
+ step :clear_cache
+
+ private
+
+ def create_upload(params:, guardian:)
+ UploadCreator.new(
+ params.file.tempfile,
+ params.file.original_filename,
+ type: "custom_emoji",
+ ).create_for(guardian.user.id)
+ end
+
+ def create_custom_emoji(params:, upload:, guardian:)
+ CustomEmoji.create(name: params.name, upload:, group: params.group, user: guardian.user)
+ end
+
+ def log_creation(params:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom_emoji_create(params.name, group: params.group)
+ end
+
+ def clear_cache
+ Emoji.clear_cache
+ end
+end
diff --git a/app/services/custom_emoji/destroy.rb b/app/services/custom_emoji/destroy.rb
new file mode 100644
index 00000000000..7ef85992d42
--- /dev/null
+++ b/app/services/custom_emoji/destroy.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+class CustomEmoji::Destroy
+ include Service::Base
+
+ params do
+ attribute :name, :string
+
+ validates :name, presence: true
+ end
+
+ model :custom_emoji, optional: true
+
+ only_if :custom_emoji_exists do
+ transaction do
+ step :log_destruction
+ step :remove_custom_emoji
+ end
+ end
+
+ step :clear_cache
+ step :rebake_affected_posts
+
+ private
+
+ def fetch_custom_emoji(params:)
+ CustomEmoji.find_by(name: params.name)
+ end
+
+ def custom_emoji_exists(custom_emoji:)
+ custom_emoji.present?
+ end
+
+ def log_destruction(params:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom_emoji_destroy(params.name)
+ end
+
+ def remove_custom_emoji(custom_emoji:)
+ # The clean_up_uploads job removes the upload after it becomes unused.
+ custom_emoji.destroy!
+ end
+
+ def clear_cache
+ Emoji.clear_cache
+ end
+
+ def rebake_affected_posts(params:)
+ Jobs.enqueue(:rebake_custom_emoji_posts, name: params.name)
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index b5e1a73aafc..ed35873b527 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -9900,6 +9900,9 @@ en:
uploading: "Uploading…"
name: "Name"
group: "Group"
+ all_groups: "All groups"
+ filter_placeholder: "Search emojis by name"
+ no_results: "No emojis found."
created_by: "Created By"
image: "Image"
alt: "custom emoji preview"
diff --git a/frontend/discourse/admin/components/admin-config-areas/emojis-list.gjs b/frontend/discourse/admin/components/admin-config-areas/emojis-list.gjs
index a276116233f..6fce67550dc 100644
--- a/frontend/discourse/admin/components/admin-config-areas/emojis-list.gjs
+++ b/frontend/discourse/admin/components/admin-config-areas/emojis-list.gjs
@@ -3,10 +3,12 @@ import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
import { service } from "@ember/service";
import AdminConfigAreaEmptyList from "discourse/admin/components/admin-config-area-empty-list";
-import ComboBox from "discourse/select-kit/components/combo-box";
import DButton from "discourse/ui-kit/d-button";
+import DFilterControls from "discourse/ui-kit/d-filter-controls";
import { i18n } from "discourse-i18n";
+const ALL_GROUPS = "all";
+
export default class AdminConfigAreasEmojisList extends Component {
@service adminEmojis;
@@ -14,135 +16,171 @@ export default class AdminConfigAreasEmojisList extends Component {
return this.adminEmojis.selectedEmojis.has(name);
};
+ allVisibleSelected = (emojis) => {
+ return (
+ emojis.length > 0 &&
+ emojis.every((emoji) =>
+ this.adminEmojis.selectedEmojis.has(emoji.get("name"))
+ )
+ );
+ };
+
+ someVisibleSelected = (emojis) => {
+ return (
+ !this.allVisibleSelected(emojis) &&
+ emojis.some((emoji) =>
+ this.adminEmojis.selectedEmojis.has(emoji.get("name"))
+ )
+ );
+ };
+
get emojis() {
return this.adminEmojis.emojis;
}
- get sortedEmojis() {
- return this.adminEmojis.sortedEmojis;
+ get searchableProps() {
+ return ["name"];
}
- get filteringGroups() {
- return this.adminEmojis.filteringGroups;
+ get groupFilterOptions() {
+ return [
+ {
+ value: ALL_GROUPS,
+ label: i18n("admin.emoji.all_groups"),
+ },
+ ...this.adminEmojis.emojiGroups.map((group) => ({
+ value: group,
+ label: group,
+ filterFn: (emoji) => emoji.group === group,
+ })),
+ ];
}
<template>
- <div class="admin-emoji-list__controls">
- <div class="inline-form">
- <ComboBox
- @value={{this.adminEmojis.filter}}
- @content={{this.filteringGroups}}
- @nameProperty={{null}}
- @valueProperty={{null}}
- />
-
- {{#if this.adminEmojis.isSelecting}}
- <DButton
- @action={{this.adminEmojis.exportSelected}}
- @translatedLabel={{this.adminEmojis.exportLabel}}
- @icon="download"
- @disabled={{this.adminEmojis.exportDisabled}}
- @isLoading={{this.adminEmojis.isExporting}}
- class="btn-primary admin-emoji-list__export-btn"
- />
- <DButton
- @action={{this.adminEmojis.cancelSelecting}}
- @label="cancel"
- class="btn-default admin-emoji-list__cancel-btn"
- />
- {{else}}
- <DButton
- @action={{this.adminEmojis.startSelecting}}
- @label="admin.emoji.select_to_export"
- @icon="download"
- class="btn-default admin-emoji-list__select-to-export"
- />
- {{/if}}
- </div>
- </div>
-
{{#if this.emojis}}
- <table id="custom_emoji" class="d-table admin-emoji-list">
- <thead class="d-table__header">
- <tr class="d-table__row">
- {{#if this.adminEmojis.isSelecting}}
- <th class="d-table__header-cell admin-emoji-list__select-col">
- <input
- type="checkbox"
- class="admin-emoji-list__select-all"
- aria-label={{i18n "admin.emoji.select_all"}}
- checked={{this.adminEmojis.allVisibleSelected}}
- indeterminate={{this.adminEmojis.someVisibleSelected}}
- {{on "change" this.adminEmojis.toggleAllVisible}}
- />
- </th>
- {{/if}}
- <th class="d-table__header-cell">{{i18n "admin.emoji.image"}}</th>
- <th class="d-table__header-cell">{{i18n "admin.emoji.name"}}</th>
- <th class="d-table__header-cell">{{i18n "admin.emoji.group"}}</th>
- <th class="d-table__header-cell" colspan="3">{{i18n
- "admin.emoji.created_by"
- }}</th>
- </tr>
- </thead>
- {{#if this.sortedEmojis}}
- <tbody class="d-table__body">
- {{#each this.sortedEmojis as |emoji|}}
+ <DFilterControls
+ @array={{this.emojis}}
+ @searchableProps={{this.searchableProps}}
+ @dropdownOptions={{this.groupFilterOptions}}
+ @inputPlaceholder={{i18n "admin.emoji.filter_placeholder"}}
+ @noResultsMessage={{i18n "admin.emoji.no_results"}}
+ >
+ <:actions>
+ {{#if this.adminEmojis.isSelecting}}
+ <DButton
+ @action={{this.adminEmojis.exportSelected}}
+ @translatedLabel={{this.adminEmojis.exportLabel}}
+ @icon="download"
+ @disabled={{this.adminEmojis.exportDisabled}}
+ @isLoading={{this.adminEmojis.isExporting}}
+ class="btn-primary admin-emoji-list__export-btn"
+ />
+ <DButton
+ @action={{this.adminEmojis.cancelSelecting}}
+ @label="cancel"
+ class="btn-default admin-emoji-list__cancel-btn"
+ />
+ {{else}}
+ <DButton
+ @action={{this.adminEmojis.startSelecting}}
+ @label="admin.emoji.select_to_export"
+ @icon="download"
+ class="btn-default admin-emoji-list__select-to-export"
+ />
+ {{/if}}
+ </:actions>
+
+ <:content as |filteredEmojis|>
+ <table id="custom_emoji" class="d-table admin-emoji-list">
+ <thead class="d-table__header">
<tr class="d-table__row">
{{#if this.adminEmojis.isSelecting}}
- <td class="d-table__cell admin-emoji-list__select-col">
+ <th class="d-table__header-cell admin-emoji-list__select-col">
<input
type="checkbox"
- class="admin-emoji-list__select"
- aria-label={{i18n "admin.emoji.select" name=emoji.name}}
- checked={{this.isEmojiSelected emoji.name}}
+ class="admin-emoji-list__select-all"
+ aria-label={{i18n "admin.emoji.select_all"}}
+ checked={{this.allVisibleSelected filteredEmojis}}
+ indeterminate={{this.someVisibleSelected filteredEmojis}}
{{on
"change"
- (fn this.adminEmojis.toggleEmojiSelected emoji)
+ (fn this.adminEmojis.toggleAllVisible filteredEmojis)
}}
/>
- </td>
+ </th>
{{/if}}
- <td class="d-table__cell --overview">
- <img
- class="emoji emoji-custom"
- src={{emoji.url}}
- title={{emoji.name}}
- alt={{i18n "admin.emoji.alt"}}
- />
- </td>
- <td class="d-table__cell --detail">
- <div class="d-table__mobile-label">
- {{i18n "admin.emoji.name"}}
- </div>
- :{{emoji.name}}:
- </td>
- <td class="d-table__cell --detail">
- <div class="d-table__mobile-label">
- {{i18n "admin.emoji.group"}}
- </div>
- {{emoji.group}}
- </td>
- <td class="d-table__cell --detail">
- <div class="d-table__mobile-label">
- {{i18n "admin.emoji.created_by"}}
- </div>
- {{emoji.created_by}}
- </td>
- {{#unless this.adminEmojis.isSelecting}}
- <td class="d-table__cell --controls action">
- <DButton
- @action={{fn this.adminEmojis.destroyEmoji emoji}}
- @label="admin.emoji.delete"
- class="btn-default btn-small d-table__cell-action-delete"
+ <th class="d-table__header-cell">{{i18n
+ "admin.emoji.image"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "admin.emoji.name"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "admin.emoji.group"
+ }}</th>
+ <th class="d-table__header-cell" colspan="3">{{i18n
+ "admin.emoji.created_by"
+ }}</th>
+ </tr>
+ </thead>
+ <tbody class="d-table__body">
+ {{#each filteredEmojis as |emoji|}}
+ <tr class="d-table__row">
+ {{#if this.adminEmojis.isSelecting}}
+ <td class="d-table__cell admin-emoji-list__select-col">
+ <input
+ type="checkbox"
+ class="admin-emoji-list__select"
+ aria-label={{i18n "admin.emoji.select" name=emoji.name}}
+ checked={{this.isEmojiSelected emoji.name}}
+ {{on
+ "change"
+ (fn this.adminEmojis.toggleEmojiSelected emoji)
+ }}
+ />
+ </td>
+ {{/if}}
+ <td class="d-table__cell --overview">
+ <img
+ class="emoji emoji-custom"
+ src={{emoji.url}}
+ title={{emoji.name}}
+ alt={{i18n "admin.emoji.alt"}}
/>
</td>
- {{/unless}}
- </tr>
- {{/each}}
- </tbody>
- {{/if}}
- </table>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "admin.emoji.name"}}
+ </div>
+ :{{emoji.name}}:
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "admin.emoji.group"}}
+ </div>
+ {{emoji.group}}
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "admin.emoji.created_by"}}
+ </div>
+ {{emoji.created_by}}
+ </td>
+ {{#unless this.adminEmojis.isSelecting}}
+ <td class="d-table__cell --controls action">
+ <DButton
+ @action={{fn this.adminEmojis.destroyEmoji emoji}}
+ @label="admin.emoji.delete"
+ class="btn-default btn-small d-table__cell-action-delete"
+ />
+ </td>
+ {{/unless}}
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ </:content>
+ </DFilterControls>
{{else}}
<AdminConfigAreaEmptyList
@ctaLabel="admin.emoji.add"
diff --git a/frontend/discourse/admin/services/admin-emojis.js b/frontend/discourse/admin/services/admin-emojis.js
index 3784d45b9ef..a23878f8e11 100644
--- a/frontend/discourse/admin/services/admin-emojis.js
+++ b/frontend/discourse/admin/services/admin-emojis.js
@@ -12,13 +12,11 @@ import { autoTrackedArray } from "discourse/lib/tracked-tools";
import Session from "discourse/models/session";
import { i18n } from "discourse-i18n";
-const ALL_FILTER = "all";
const DEFAULT_GROUP = "default";
export default class AdminEmojis extends Service {
@service dialog;
- @tracked filter = ALL_FILTER;
@tracked sorting = ["group", "name"];
@tracked selectedEmojis = new Set();
@tracked isSelecting = false;
@@ -30,43 +28,12 @@ export default class AdminEmojis extends Service {
this.#fetchEmojis();
}
- get filteredEmojis() {
- if (!this.filter || this.filter === ALL_FILTER) {
- return this.emojis;
- } else {
- return this.emojis.filter((e) => e.group === this.filter);
- }
- }
-
- get sortedEmojis() {
- return this.filteredEmojis.toSorted((a, b) => a.name.localeCompare(b.name));
- }
-
get emojiGroups() {
return uniqueItemsFromArray(
[DEFAULT_GROUP].concat(this.emojis.map((e) => e.group))
);
}
- get filteringGroups() {
- return [ALL_FILTER].concat(this.emojiGroups);
- }
-
- get allVisibleSelected() {
- const visible = this.sortedEmojis;
- return (
- visible.length > 0 &&
- visible.every((e) => this.selectedEmojis.has(e.get("name")))
- );
- }
-
- get someVisibleSelected() {
- return (
- !this.allVisibleSelected &&
- this.sortedEmojis.some((e) => this.selectedEmojis.has(e.get("name")))
- );
- }
-
get exportDisabled() {
return this.selectedEmojis.size === 0;
}
@@ -146,10 +113,13 @@ export default class AdminEmojis extends Service {
}
@action
- toggleAllVisible() {
- const emojis = this.sortedEmojis;
+ toggleAllVisible(emojis) {
const next = new Set(this.selectedEmojis);
- if (this.allVisibleSelected) {
+ const allVisibleSelected = emojis.every((emoji) =>
+ this.selectedEmojis.has(emoji.get("name"))
+ );
+
+ if (allVisibleSelected) {
emojis.forEach((e) => next.delete(e.get("name")));
} else {
emojis.forEach((e) => next.add(e.get("name")));
diff --git a/frontend/discourse/tests/acceptance/admin-emoji-test.gjs b/frontend/discourse/tests/acceptance/admin-emoji-test.gjs
index 34ffe2adb4e..2657a2f5cd7 100644
--- a/frontend/discourse/tests/acceptance/admin-emoji-test.gjs
+++ b/frontend/discourse/tests/acceptance/admin-emoji-test.gjs
@@ -1,4 +1,11 @@
-import { click, currentURL, triggerEvent, visit } from "@ember/test-helpers";
+import {
+ click,
+ currentURL,
+ fillIn,
+ select,
+ triggerEvent,
+ visit,
+} from "@ember/test-helpers";
import { test } from "qunit";
import pretender, { response } from "discourse/tests/helpers/create-pretender";
import { acceptance, createFile } from "discourse/tests/helpers/qunit-helpers";
@@ -96,6 +103,32 @@ acceptance("Admin - Emoji", function (needs) {
.doesNotExist("checkboxes not shown before selecting mode");
});
+ test("filters custom emojis by name", async function (assert) {
+ await visit("/admin/config/emoji");
+
+ await fillIn(".filter-input", "party");
+
+ assert
+ .dom(".admin-emoji-list tbody .d-table__row")
+ .exists({ count: 1 }, "only the emoji matching by name is shown");
+ assert
+ .dom(".admin-emoji-list tbody")
+ .containsText(":partyblob:", "shows the matching emoji");
+ });
+
+ test("filters custom emojis by group", async function (assert) {
+ await visit("/admin/config/emoji");
+
+ await select(".d-filter-controls__dropdown", "fun");
+
+ assert
+ .dom(".admin-emoji-list tbody .d-table__row")
+ .exists({ count: 1 }, "only emojis in the selected group are shown");
+ assert
+ .dom(".admin-emoji-list tbody")
+ .containsText(":partyblob:", "shows the emoji in the selected group");
+ });
+
// ─── Select to export flow ─────────────────────────────────────────────────
test("clicking select-to-export enters selecting mode and shows checkboxes", async function (assert) {
@@ -175,6 +208,19 @@ acceptance("Admin - Emoji", function (needs) {
.doesNotExist("all rows deselected after clicking select-all again");
});
+ test("select-all only selects emojis visible through the filters", async function (assert) {
+ await visit("/admin/config/emoji");
+
+ await fillIn(".filter-input", "party");
+ await click(".admin-emoji-list__select-to-export");
+ await click(".admin-emoji-list__select-all");
+ await fillIn(".filter-input", "");
+
+ assert
+ .dom(".admin-emoji-list__select:checked")
+ .exists({ count: 1 }, "only the filtered emoji is selected");
+ });
+
test("selecting a row makes header select-all indeterminate", async function (assert) {
await visit("/admin/config/emoji");
diff --git a/spec/requests/admin/emojis_controller_spec.rb b/spec/requests/admin/emojis_controller_spec.rb
index f50ad4abf27..6f503e5f566 100644
--- a/spec/requests/admin/emojis_controller_spec.rb
+++ b/spec/requests/admin/emojis_controller_spec.rb
@@ -67,6 +67,13 @@ RSpec.describe Admin::EmojiController do
end
end
+ it "returns a controlled validation error without an upload" do
+ post "/admin/config/emoji.json", params: { name: "test" }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to eq(["File can't be blank"])
+ end
+
context "when emoji name already exists" do
it "should publish the right error" do
CustomEmoji.create!(name: "test", upload: upload)
@@ -615,6 +622,9 @@ RSpec.describe Admin::EmojiController do
expect do
delete "/admin/config/emoji/#{custom_emoji.name}.json", params: { name: "test" }
end.to change { CustomEmoji.count }.by(-1)
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["success"]).to eq("OK")
end
it "should log the action" do
diff --git a/spec/services/custom_emoji/create_spec.rb b/spec/services/custom_emoji/create_spec.rb
new file mode 100644
index 00000000000..b18cdc471dc
--- /dev/null
+++ b/spec/services/custom_emoji/create_spec.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+RSpec.describe CustomEmoji::Create do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:file) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:actor, :admin)
+
+ let(:params) { { file:, name: "PaRTY.png", group: "Foo" } }
+ let(:dependencies) { { guardian: actor.guardian } }
+ let(:file) do
+ Rack::Test::UploadedFile.new(Rails.root.join("spec/fixtures/images/logo.png"), "image/png")
+ end
+
+ context "without an uploaded file" do
+ let(:file) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "with files instead of a file" do
+ let(:params) { { files: [file], name: "party" } }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when the upload is invalid" do
+ let(:file) do
+ Rack::Test::UploadedFile.new(Rails.root.join("spec/fixtures/images/fake.jpg"), "image/jpeg")
+ end
+
+ it { is_expected.to fail_with_an_invalid_model(:upload) }
+ end
+
+ context "when the emoji is invalid" do
+ fab!(:existing_emoji) { Fabricate(:custom_emoji, name: "party") }
+
+ it { is_expected.to fail_with_an_invalid_model(:custom_emoji) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "creates a normalized custom emoji owned by the actor" do
+ expect(result.custom_emoji).to have_attributes(name: "party", group: "foo", user: actor)
+ expect(result.custom_emoji.upload.original_filename).to eq("logo.png")
+ end
+
+ it "logs the creation" do
+ expect { result }.to change {
+ UserHistory.where(action: UserHistory.actions[:custom_emoji_create]).count
+ }.by(1)
+
+ expect(UserHistory.last).to have_attributes(acting_user_id: actor.id, new_value: "party")
+ end
+
+ it "invalidates the custom emoji cache" do
+ expect(Emoji.custom.map(&:name)).not_to include("party")
+
+ result
+
+ expect(Emoji.custom.map(&:name)).to include("party")
+ end
+ end
+ end
+end
diff --git a/spec/services/custom_emoji/destroy_spec.rb b/spec/services/custom_emoji/destroy_spec.rb
new file mode 100644
index 00000000000..5c921377db4
--- /dev/null
+++ b/spec/services/custom_emoji/destroy_spec.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+RSpec.describe CustomEmoji::Destroy do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:name) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:actor, :admin)
+ fab!(:custom_emoji) { Fabricate(:custom_emoji, name: "party") }
+
+ let(:params) { { name: } }
+ let(:dependencies) { { guardian: actor.guardian } }
+ let(:name) { "party" }
+
+ context "without a name" do
+ let(:name) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the custom emoji does not exist" do
+ let(:name) { "missing" }
+
+ it { is_expected.to run_successfully }
+
+ it "enqueues a rebake for the requested name" do
+ expect_enqueued_with(job: :rebake_custom_emoji_posts, args: { name: }) { result }
+ end
+ end
+
+ context "when the custom emoji exists" do
+ it { is_expected.to run_successfully }
+
+ it "deletes the custom emoji" do
+ expect { result }.to change { CustomEmoji.exists?(custom_emoji.id) }.from(true).to(false)
+ end
+
+ it "logs the destruction" do
+ expect { result }.to change {
+ UserHistory.where(action: UserHistory.actions[:custom_emoji_destroy]).count
+ }.by(1)
+
+ expect(UserHistory.last).to have_attributes(acting_user_id: actor.id, previous_value: name)
+ end
+
+ it "invalidates the custom emoji cache" do
+ expect(Emoji.custom.map(&:name)).to include(name)
+
+ result
+
+ expect(Emoji.custom.map(&:name)).not_to include(name)
+ end
+
+ it "enqueues a rebake for the deleted emoji" do
+ expect_enqueued_with(job: :rebake_custom_emoji_posts, args: { name: }) { result }
+ end
+ end
+ end
+end