discourse/app/assets/javascripts/admin/addon/controllers/admin-badges/show.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

261 lines
6.2 KiB
JavaScript
Raw Normal View History

import Controller, { inject as controller } from "@ember/controller";
import { observes } from "@ember-decorators/object";
import I18n from "I18n";
import { bufferedProperty } from "discourse/mixins/buffered-content";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { next } from "@ember/runloop";
import { action } from "@ember/object";
import { inject as service } from "@ember/service";
import getURL from "discourse-common/lib/get-url";
import { tracked } from "@glimmer/tracking";
const IMAGE = "image";
const ICON = "icon";
// TODO: Stop using Mixin here
export default class AdminBadgesShowController extends Controller.extend(
bufferedProperty("model")
) {
@service router;
@service dialog;
@controller adminBadges;
@tracked saving = false;
@tracked savingStatus = "";
@tracked selectedGraphicType = null;
get badgeEnabledLabel() {
if (this.buffered.get("enabled")) {
return "admin.badges.enabled";
} else {
return "admin.badges.disabled";
}
}
get badgeTypes() {
return this.adminBadges.badgeTypes;
}
get badgeGroupings() {
return this.adminBadges.badgeGroupings;
}
get badgeTriggers() {
return this.adminBadges.badgeTriggers;
}
get protectedSystemFields() {
return this.adminBadges.protectedSystemFields;
}
get readOnly() {
return this.buffered.get("system");
}
get showDisplayName() {
return this.name !== this.displayName;
}
get iconSelectorSelected() {
return this.selectedGraphicType === ICON;
}
get imageUploaderSelected() {
return this.selectedGraphicType === IMAGE;
}
init() {
super.init(...arguments);
// this is needed because the model doesnt have default values
// and as we are using a bufferedProperty it's not accessible
// in any other way
next(() => {
// Using `set` here isn't ideal, but we don't know that tracking is set up on the model yet.
if (this.model) {
if (!this.model.badge_type_id) {
this.model.set("badge_type_id", this.badgeTypes?.[0]?.id);
}
if (!this.model.badge_grouping_id) {
this.model.set("badge_grouping_id", this.badgeGroupings?.[0]?.id);
}
if (!this.model.trigger) {
this.model.set("trigger", this.badgeTriggers?.[0]?.id);
}
}
});
}
get hasQuery() {
let modelQuery = this.model.get("query");
let bufferedQuery = this.buffered.get("query");
if (bufferedQuery) {
return bufferedQuery.trim().length > 0;
}
return modelQuery && modelQuery.trim().length > 0;
}
get textCustomizationPrefix() {
return `badges.${this.model.i18n_name}.`;
}
// FIXME: Remove observer
@observes("model.id")
_resetSaving() {
this.saving = false;
this.savingStatus = "";
}
showIconSelector() {
this.selectedGraphicType = ICON;
}
showImageUploader() {
this.selectedGraphicType = IMAGE;
}
@action
changeGraphicType(newType) {
if (newType === IMAGE) {
this.showImageUploader();
} else if (newType === ICON) {
this.showIconSelector();
} else {
throw new Error(`Unknown badge graphic type "${newType}"`);
}
}
@action
setImage(upload) {
this.buffered.set("image_upload_id", upload.id);
this.buffered.set("image_url", getURL(upload.url));
}
@action
removeImage() {
this.buffered.set("image_upload_id", null);
this.buffered.set("image_url", null);
}
DEV: Remove usage of {{action}} modifiers - Take 2 (#18476) This PR enables the [`no-action-modifiers`](https://github.com/ember-template-lint/ember-template-lint/blob/master/docs/rule/no-action-modifiers.md) template lint rule and removes all usages of the `{{action}}` modifier in core. In general, instances of `{{action "x"}}` have been replaced with `{{on "click" (action "x")}}`. In many cases, such as for `a` elements, we also need to prevent default event handling to avoid unwanted side effects. While the `{{action}}` modifier internally calls `event.preventDefault()`, we need to handle these cases more explicitly. For this purpose, this PR also adds the [ember-event-helpers](https://github.com/buschtoens/ember-event-helpers) dependency so we can use the `prevent-default` handler. For instance: ``` <a href {{on "click" (prevent-default (action "x"))}}>Do X</a> ``` Note that `action` has not in general been refactored away as a helper yet. In general, all event handlers should be methods on the corresponding component and referenced directly (e.g. `{{on "click" this.doSomething}}`). However, the `action` helper is used extensively throughout the codebase and often references methods in the `actions` hash on controllers or routes. Thus this refactor will also be extensive and probably deserves a separate PR. Note: This work was done to complement #17767 by minimizing the potential impact of the `action` modifier override, which uses private API and arguably should be replaced with an AST transform. This is a followup to #18333, which had to be reverted because it did not account for the default treatment of modifier keys by the {{action}} modifier. Commits: * Enable `no-action-modifiers` template lint rule * Replace {{action "x"}} with {{on "click" (action "x")}} * Remove unnecessary action helper usage * Remove ctl+click tests for user-menu These tests now break in Chrome when used with addEventListener. As per the comment, they can probably be safely removed. * Prevent default event handlers to avoid unwanted side effects Uses `event.preventDefault()` in event handlers to prevent default event handling. This had been done automatically by the `action` modifier, but is not always desirable or necessary. * Restore UserCardContents#showUser action to avoid regression By keeping the `showUser` action, we can avoid a breaking change for plugins that rely upon it, while not interfering with the `showUser` argument that's been passed. * Revert EditCategoryTab#selectTab -> EditCategoryTab#select Avoid potential breaking change in themes / plugins * Restore GroupCardContents#showGroup action to avoid regression By keeping the `showGroup` action, we can avoid a breaking change for plugins that rely upon it, while not interfering with the `showGroup` argument that's been passed. * Restore SecondFactorAddTotp#showSecondFactorKey action to avoid regression By keeping the `showSecondFactorKey` action, we can avoid a breaking change for plugins that rely upon it, while not interfering with the `showSecondFactorKey` property that's maintained on the controller. * Refactor away from `actions` hash in ChooseMessage component * Modernize EmojiPicker#onCategorySelection usage * Modernize SearchResultEntry#logClick usage * Modernize Discovery::Categories#showInserted usage * Modernize Preferences::Account#resendConfirmationEmail usage * Modernize MultiSelect::SelectedCategory#onSelectedNameClick usage * Favor fn over action in SelectedChoice component * Modernize WizardStep event handlers * Favor fn over action usage in buttons * Restore Login#forgotPassword action to avoid possible regression * Introduce modKeysPressed utility Returns an array of modifier keys that are pressed during a given `MouseEvent` or `KeyboardEvent`. * Don't interfere with click events on links with `href` values when modifier keys are pressed
2022-10-05 20:08:54 +08:00
@action
showPreview(badge, explain, event) {
event?.preventDefault();
this.send("preview", badge, explain);
}
@action
save() {
if (!this.saving) {
let fields = [
"allow_title",
"multiple_grant",
"listable",
"auto_revoke",
"enabled",
"show_posts",
"target_posts",
"name",
"description",
"long_description",
"icon",
"image_upload_id",
"query",
"badge_grouping_id",
"trigger",
"badge_type_id",
];
if (this.buffered.get("system")) {
let protectedFields = this.protectedSystemFields || [];
fields = fields.filter((f) => !protectedFields.includes(f));
}
this.saving = true;
this.savingStatus = I18n.t("saving");
const boolFields = [
"allow_title",
"multiple_grant",
"listable",
"auto_revoke",
"enabled",
"show_posts",
"target_posts",
];
const data = {};
const buffered = this.buffered;
fields.forEach(function (field) {
let d = buffered.get(field);
if (boolFields.includes(field)) {
d = !!d;
}
data[field] = d;
});
const newBadge = !this.id;
const model = this.model;
this.model
.save(data)
.then(() => {
if (newBadge) {
const adminBadges = this.get("adminBadges.model");
if (!adminBadges.includes(model)) {
adminBadges.pushObject(model);
}
this.router.transitionTo("adminBadges.show", model.get("id"));
} else {
this.commitBuffer();
this.savingStatus = I18n.t("saved");
}
})
.catch(popupAjaxError)
.finally(() => {
this.saving = false;
this.savingStatus = "";
});
}
}
@action
destroyBadge() {
const adminBadges = this.adminBadges.model;
const model = this.model;
if (!model?.get("id")) {
this.router.transitionTo("adminBadges.index");
return;
}
return this.dialog.yesNoConfirm({
message: I18n.t("admin.badges.delete_confirm"),
didConfirm: () => {
model
.destroy()
.then(() => {
adminBadges.removeObject(model);
this.router.transitionTo("adminBadges.index");
})
.catch(() => {
this.dialog.alert(I18n.t("generic_error"));
});
},
});
}
@action
toggleBadge() {
const originalState = this.buffered.get("enabled");
const newState = !this.buffered.get("enabled");
this.buffered.set("enabled", newState);
this.model.save({ enabled: newState }).catch((error) => {
this.buffered.set("enabled", originalState);
return popupAjaxError(error);
});
}
}