Skip to content

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

DEV: Convert select-kit base classes to native class syntax (#28467)

David Taylor3e3c051164c4
diff --git a/app/assets/javascripts/select-kit/addon/components/multi-select.js b/app/assets/javascripts/select-kit/addon/components/multi-select.js
index e5606dbadfa..f573dddfaba 100644
--- a/app/assets/javascripts/select-kit/addon/components/multi-select.js
+++ b/app/assets/javascripts/select-kit/addon/components/multi-select.js
@@ -1,41 +1,45 @@
import { computed } from "@ember/object";
import { next } from "@ember/runloop";
import { isPresent } from "@ember/utils";
+import { classNames } from "@ember-decorators/component";
import { makeArray } from "discourse-common/lib/helpers";
-import SelectKitComponent from "select-kit/components/select-kit";
-
-export default SelectKitComponent.extend({
- pluginApiIdentifiers: ["multi-select"],
- classNames: ["multi-select"],
- multiSelect: true,
-
- selectKitOptions: {
- none: "select_kit.default_header_text",
- clearable: true,
- filterable: true,
- filterIcon: null,
- closeOnChange: false,
- autoInsertNoneItem: false,
- headerComponent: "multi-select/multi-select-header",
- filterComponent: "multi-select/multi-select-filter",
- autoFilterable: true,
- caretDownIcon: "caretIcon",
- caretUpIcon: "caretIcon",
- useHeaderFilter: false,
- },
-
- caretIcon: computed("value.[]", function () {
+import SelectKitComponent, {
+ pluginApiIdentifiers,
+ selectKitOptions,
+} from "select-kit/components/select-kit";
+
+@classNames("multi-select")
+@selectKitOptions({
+ none: "select_kit.default_header_text",
+ clearable: true,
+ filterable: true,
+ filterIcon: null,
+ closeOnChange: false,
+ autoInsertNoneItem: false,
+ headerComponent: "multi-select/multi-select-header",
+ filterComponent: "multi-select/multi-select-filter",
+ autoFilterable: true,
+ caretDownIcon: "caretIcon",
+ caretUpIcon: "caretIcon",
+ useHeaderFilter: false,
+})
+@pluginApiIdentifiers(["multi-select"])
+export default class MultiSelect extends SelectKitComponent {
+ multiSelect = true;
+
+ @computed("value.[]")
+ get caretIcon() {
const maximum = this.selectKit.options.maximum;
return maximum && makeArray(this.value).length >= parseInt(maximum, 10)
? null
: "plus";
- }),
+ }
search(filter) {
- return this._super(filter).filter(
- (content) => !makeArray(this.selectedContent).includes(content)
- );
- },
+ return super
+ .search(filter)
+ .filter((content) => !makeArray(this.selectedContent).includes(content));
+ }
append(values) {
const existingItems = values
@@ -60,7 +64,7 @@ export default SelectKitComponent.extend({
);
this.selectKit.change(newValues, newContent);
- },
+ }
deselect(item) {
this.clearErrors();
@@ -73,7 +77,7 @@ export default SelectKitComponent.extend({
this.valueProperty ? newContent.mapBy(this.valueProperty) : newContent,
newContent
);
- },
+ }
select(value, item) {
if (this.selectKit.hasSelection && this.selectKit.options.maximum === 1) {
@@ -122,42 +126,38 @@ export default SelectKitComponent.extend({
: makeArray(this.defaultItem(value, value))
);
}
- },
-
- selectedContent: computed(
- "value.[]",
- "content.[]",
- "selectKit.noneItem",
- function () {
- const value = makeArray(this.value).map((v) =>
- this.selectKit.options.castInteger && this._isNumeric(v) ? Number(v) : v
- );
+ }
- if (value.length) {
- let content = [];
-
- value.forEach((v) => {
- if (this.selectKit.valueProperty) {
- const c = makeArray(this.content).findBy(
- this.selectKit.valueProperty,
- v
- );
- if (c) {
- content.push(c);
- }
- } else {
- if (makeArray(this.content).includes(v)) {
- content.push(v);
- }
- }
- });
+ @computed("value.[]", "content.[]", "selectKit.noneItem")
+ get selectedContent() {
+ const value = makeArray(this.value).map((v) =>
+ this.selectKit.options.castInteger && this._isNumeric(v) ? Number(v) : v
+ );
- return this.selectKit.modifySelection(content);
- }
+ if (value.length) {
+ let content = [];
+
+ value.forEach((v) => {
+ if (this.selectKit.valueProperty) {
+ const c = makeArray(this.content).findBy(
+ this.selectKit.valueProperty,
+ v
+ );
+ if (c) {
+ content.push(c);
+ }
+ } else {
+ if (makeArray(this.content).includes(v)) {
+ content.push(v);
+ }
+ }
+ });
- return null;
+ return this.selectKit.modifySelection(content);
}
- ),
+
+ return null;
+ }
_onKeydown(event) {
if (
@@ -192,5 +192,5 @@ export default SelectKitComponent.extend({
}
return true;
- },
-});
+ }
+}
diff --git a/app/assets/javascripts/select-kit/addon/components/select-kit.js b/app/assets/javascripts/select-kit/addon/components/select-kit.js
index d75b736f813..8ed7e069bd5 100644
--- a/app/assets/javascripts/select-kit/addon/components/select-kit.js
+++ b/app/assets/javascripts/select-kit/addon/components/select-kit.js
@@ -1,10 +1,14 @@
import Component from "@ember/component";
import EmberObject, { computed, get } from "@ember/object";
import { guidFor } from "@ember/object/internals";
-import Mixin from "@ember/object/mixin";
import { bind, cancel, next, schedule, throttle } from "@ember/runloop";
import { service } from "@ember/service";
import { isEmpty, isNone, isPresent } from "@ember/utils";
+import {
+ classNameBindings,
+ classNames,
+ tagName,
+} from "@ember-decorators/component";
import { createPopper } from "@popperjs/core";
import { Promise } from "rsvp";
import { INPUT_DELAY } from "discourse-common/config/environment";
@@ -13,7 +17,7 @@ import deprecated from "discourse-common/lib/deprecated";
import { makeArray } from "discourse-common/lib/helpers";
import { bind as bindDecorator } from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
-import PluginApiMixin, {
+import {
applyContentPluginApiCallbacks,
applyOnChangePluginApiCallbacks,
} from "select-kit/mixins/plugin-api";
@@ -22,1232 +26,1257 @@ import UtilsMixin from "select-kit/mixins/utils";
export const MAIN_COLLECTION = "MAIN_COLLECTION";
export const ERRORS_COLLECTION = "ERRORS_COLLECTION";
-const EMPTY_OBJECT = Object.freeze({});
-const SELECT_KIT_OPTIONS = Mixin.create({
- concatenatedProperties: ["selectKitOptions"],
- selectKitOptions: EMPTY_OBJECT,
-});
-
function isDocumentRTL() {
return document.documentElement.classList.contains("rtl");
}
-export default Component.extend(
- SELECT_KIT_OPTIONS,
- PluginApiMixin,
- UtilsMixin,
- {
- tagName: "details",
- pluginApiIdentifiers: ["select-kit"],
- classNames: ["select-kit"],
- classNameBindings: [
- "selectKit.isLoading:is-loading",
- "selectKit.isExpanded:is-expanded",
- "selectKit.options.disabled:is-disabled",
- "selectKit.isHidden:is-hidden",
- "selectKit.hasSelection:has-selection",
- ],
- tabindex: 0,
- content: null,
- value: null,
- selectKit: null,
- mainCollection: null,
- errorsCollection: null,
- options: null,
- valueProperty: "id",
- nameProperty: "name",
- singleSelect: false,
- multiSelect: false,
- labelProperty: null,
- titleProperty: null,
- langProperty: null,
- appEvents: service(),
-
- init() {
- this._super(...arguments);
-
- this._searchPromise = null;
-
- this.set("errorsCollection", []);
- this._collections = [ERRORS_COLLECTION, MAIN_COLLECTION];
-
- !this.options && this.set("options", EmberObject.create({}));
-
- this.handleDeprecations();
-
- this.set(
- "selectKit",
- EmberObject.create({
- uniqueID: this.id || guidFor(this),
- valueProperty: this.valueProperty,
- nameProperty: this.nameProperty,
- labelProperty: this.labelProperty,
- titleProperty: this.titleProperty,
- langProperty: this.langProperty,
- options: EmberObject.create(),
+/**
+ * Simulates the behavior of Ember's concatenatedProperties under native class syntax
+ */
+function concatProtoProperty(target, key, value) {
+ target.proto();
+ target.prototype[key] = [
+ ...makeArray(target.prototype[key]),
+ ...makeArray(value),
+ ];
+}
- isLoading: false,
- isHidden: false,
- isExpanded: false,
- isFilterExpanded: false,
- enterDisabled: false,
- hasSelection: false,
- hasNoContent: true,
- highlighted: null,
- noneItem: null,
- newItem: null,
- filter: null,
-
- modifyContent: bind(this, this._modifyContentWrapper),
- modifySelection: bind(this, this._modifySelectionWrapper),
- modifyComponentForRow: bind(this, this._modifyComponentForRowWrapper),
- modifyContentForCollection: bind(
- this,
- this._modifyContentForCollectionWrapper
- ),
- modifyComponentForCollection: bind(
- this,
- this._modifyComponentForCollectionWrapper
- ),
-
- toggle: bind(this, this._toggle),
- close: bind(this, this._close),
- open: bind(this, this._open),
- highlightNext: bind(this, this._highlightNext),
- highlightPrevious: bind(this, this._highlightPrevious),
- highlightLast: bind(this, this._highlightLast),
- highlightFirst: bind(this, this._highlightFirst),
- deselectLast: bind(this, this._deselectLast),
- change: bind(this, this._onChangeWrapper),
- select: bind(this, this.select),
- deselect: bind(this, this.deselect),
- deselectByValue: bind(this, this.deselectByValue),
- append: bind(this, this.append),
- cancelSearch: bind(this, this._cancelSearch),
- triggerSearch: bind(this, this.triggerSearch),
- focusFilter: bind(this, this._focusFilter),
-
- onOpen: bind(this, this._onOpenWrapper),
- onClose: bind(this, this._onCloseWrapper),
- onInput: bind(this, this._onInput),
- onClearSelection: bind(this, this._onClearSelection),
- onHover: bind(this, this._onHover),
- onKeydown: bind(this, this._onKeydownWrapper),
-
- mainElement: bind(this, this._mainElement),
- headerElement: bind(this, this._headerElement),
- bodyElement: bind(this, this._bodyElement),
- })
- );
- },
-
- _modifyComponentForRowWrapper(collection, item) {
- let component = this.modifyComponentForRow(collection, item);
- return component || "select-kit/select-kit-row";
- },
-
- modifyComponentForRow() {},
-
- _modifyContentForCollectionWrapper(identifier) {
- let collection = this.modifyContentForCollection(identifier);
-
- if (!collection) {
- switch (identifier) {
- case ERRORS_COLLECTION:
- collection = this.errorsCollection;
- break;
- default:
- collection = this.mainCollection;
- break;
- }
- }
+/**
+ * @decorator
+ *
+ * Apply select-kit options to a component class
+ *
+ */
+export function selectKitOptions(options) {
+ return function (target) {
+ concatProtoProperty(target, "selectKitOptions", options);
+ };
+}
- return collection;
- },
+/**
+ * @decorator
+ *
+ * Register one or more plugin API identifiers for a component class
+ *
+ */
+export function pluginApiIdentifiers(identifiers) {
+ return function (target) {
+ concatProtoProperty(target, "pluginIdIdentifiers", identifiers);
+ };
+}
- modifyContentForCollection() {},
+// Decorator which converts a field into a prototype property.
+// This allows the value to be overridden in subclasses, even if they're still
+// using the legacy Ember `.extend()` syntax.
+function protoProp(prototype, key, descriptor) {
+ return {
+ value: descriptor.initializer?.(),
+ writable: true,
+ enumerable: true,
+ configurable: true,
+ };
+}
- _modifyComponentForCollectionWrapper(identifier) {
- let component = this.modifyComponentForCollection(identifier);
+@tagName("details")
+@classNames("select-kit")
+@classNameBindings(
+ "selectKit.isLoading:is-loading",
+ "selectKit.isExpanded:is-expanded",
+ "selectKit.options.disabled:is-disabled",
+ "selectKit.isHidden:is-hidden",
+ "selectKit.hasSelection:has-selection"
+)
+@selectKitOptions({
+ allowAny: false,
+ showFullTitle: true,
+ none: null,
+ translatedNone: null,
+ filterable: false,
+ autoFilterable: "autoFilterable",
+ filterIcon: "search",
+ filterPlaceholder: null,
+ translatedFilterPlaceholder: null,
+ icon: null,
+ icons: null,
+ maximum: null,
+ maximumLabel: null,
+ minimum: null,
+ autoInsertNoneItem: true,
+ closeOnChange: true,
+ useHeaderFilter: false,
+ limitMatches: null,
+ placement: isDocumentRTL() ? "bottom-end" : "bottom-start",
+ verticalOffset: 3,
+ filterComponent: "select-kit/select-kit-filter",
+ selectedNameComponent: "selected-name",
+ selectedChoiceComponent: "selected-choice",
+ castInteger: false,
+ focusAfterOnChange: true,
+ triggerOnChangeOnTab: true,
+ autofocus: false,
+ placementStrategy: null,
+ mobilePlacementStrategy: null,
+ desktopPlacementStrategy: null,
+ hiddenValues: null,
+ disabled: false,
+ expandedOnInsert: false,
+ formName: null,
+})
+@pluginApiIdentifiers(["select-kit"])
+export default class SelectKit extends Component.extend(UtilsMixin) {
+ @service appEvents;
+
+ singleSelect = false;
+ multiSelect = false;
+
+ @protoProp tabindex = 0;
+ @protoProp content = null;
+ @protoProp value = null;
+ @protoProp selectKit = null;
+ @protoProp mainCollection = null;
+ @protoProp errorsCollection = null;
+ @protoProp options = null;
+ @protoProp valueProperty = "id";
+ @protoProp nameProperty = "name";
+ @protoProp labelProperty = null;
+ @protoProp titleProperty = null;
+ @protoProp langProperty = null;
+
+ init() {
+ super.init(...arguments);
+
+ this._searchPromise = null;
+
+ this.set("errorsCollection", []);
+ this._collections = [ERRORS_COLLECTION, MAIN_COLLECTION];
+
+ !this.options && this.set("options", EmberObject.create({}));
+
+ this.handleDeprecations();
+
+ this.set(
+ "selectKit",
+ EmberObject.create({
+ uniqueID: this.id || guidFor(this),
+ valueProperty: this.valueProperty,
+ nameProperty: this.nameProperty,
+ labelProperty: this.labelProperty,
+ titleProperty: this.titleProperty,
+ langProperty: this.langProperty,
+ options: EmberObject.create(),
+
+ isLoading: false,
+ isHidden: false,
+ isExpanded: false,
+ isFilterExpanded: false,
+ enterDisabled: false,
+ hasSelection: false,
+ hasNoContent: true,
+ highlighted: null,
+ noneItem: null,
+ newItem: null,
+ filter: null,
- if (!component) {
- switch (identifier) {
- case ERRORS_COLLECTION:
- component = "select-kit/errors-collection";
- break;
- default:
- component = "select-kit/select-kit-collection";
- break;
- }
- }
+ modifyContent: bind(this, this._modifyContentWrapper),
+ modifySelection: bind(this, this._modifySelectionWrapper),
+ modifyComponentForRow: bind(this, this._modifyComponentForRowWrapper),
+ modifyContentForCollection: bind(
+ this,
+ this._modifyContentForCollectionWrapper
+ ),
+ modifyComponentForCollection: bind(
+ this,
+ this._modifyComponentForCollectionWrapper
+ ),
+
+ toggle: bind(this, this._toggle),
+ close: bind(this, this._close),
+ open: bind(this, this._open),
+ highlightNext: bind(this, this._highlightNext),
+ highlightPrevious: bind(this, this._highlightPrevious),
+ highlightLast: bind(this, this._highlightLast),
+ highlightFirst: bind(this, this._highlightFirst),
+ deselectLast: bind(this, this._deselectLast),
+ change: bind(this, this._onChangeWrapper),
+ select: bind(this, this.select),
+ deselect: bind(this, this.deselect),
+ deselectByValue: bind(this, this.deselectByValue),
+ append: bind(this, this.append),
+ cancelSearch: bind(this, this._cancelSearch),
+ triggerSearch: bind(this, this.triggerSearch),
+ focusFilter: bind(this, this._focusFilter),
+
+ onOpen: bind(this, this._onOpenWrapper),
+ onClose: bind(this, this._onCloseWrapper),
+ onInput: bind(this, this._onInput),
+ onClearSelection: bind(this, this._onClearSelection),
+ onHover: bind(this, this._onHover),
+ onKeydown: bind(this, this._onKeydownWrapper),
+
+ mainElement: bind(this, this._mainElement),
+ headerElement: bind(this, this._headerElement),
+ bodyElement: bind(this, this._bodyElement),
+ })
+ );
+ }
+
+ _modifyComponentForRowWrapper(collection, item) {
+ let component = this.modifyComponentForRow(collection, item);
+ return component || "select-kit/select-kit-row";
+ }
- return component;
- },
+ modifyComponentForRow() {}
- modifyComponentForCollection() {},
+ _modifyContentForCollectionWrapper(identifier) {
+ let collection = this.modifyContentForCollection(identifier);
- didUpdateAttrs() {
- this._super(...arguments);
+ if (!collection) {
+ switch (identifier) {
+ case ERRORS_COLLECTION:
+ collection = this.errorsCollection;
+ break;
+ default:
+ collection = this.mainCollection;
+ break;
+ }
+ }
- this.handleDeprecations();
- },
+ return collection;
+ }
- didInsertElement() {
- this._super(...arguments);
+ modifyContentForCollection() {}
- this.appEvents.on("keyboard-visibility-change", this, this._updatePopper);
+ _modifyComponentForCollectionWrapper(identifier) {
+ let component = this.modifyComponentForCollection(identifier);
- if (this.selectKit.options.expandedOnInsert) {
- next(() => {
- this._open();
- });
+ if (!component) {
+ switch (identifier) {
+ case ERRORS_COLLECTION:
+ component = "select-kit/errors-collection";
+ break;
+ default:
+ component = "select-kit/select-kit-collection";
+ break;
}
- },
+ }
- click(event) {
- event.preventDefault();
- event.stopPropagation();
- },
+ return component;
+ }
- willDestroyElement() {
- this._super(...arguments);
+ modifyComponentForCollection() {}
- this._cancelSearch();
+ didUpdateAttrs() {
+ super.didUpdateAttrs(...arguments);
- this.appEvents.off(
- "keyboard-visibility-change",
- this,
- this._updatePopper
- );
+ this.handleDeprecations();
+ }
- if (this.popper) {
- this.popper.destroy();
- this.popper = null;
- }
- },
+ didInsertElement() {
+ super.didInsertElement(...arguments);
- didReceiveAttrs() {
- this._super(...arguments);
+ this.appEvents.on("keyboard-visibility-change", this, this._updatePopper);
- const deprecatedOptions = this._resolveDeprecatedOptions();
- const mergedOptions = Object.assign({}, ...this.selectKitOptions);
- Object.keys(mergedOptions).forEach((key) => {
- if (isPresent(this.options[key])) {
- this.selectKit.options.set(key, this.options[key]);
- return;
- }
+ if (this.selectKit.options.expandedOnInsert) {
+ next(() => {
+ this._open();
+ });
+ }
+ }
- if (isPresent(deprecatedOptions[`options.${key}`])) {
- this.selectKit.options.set(key, deprecatedOptions[`options.${key}`]);
- return;
- }
+ click(event) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
- const value = mergedOptions[key];
+ willDestroyElement() {
+ super.willDestroyElement(...arguments);
- if (
- key === "componentForRow" ||
- key === "contentForCollection" ||
- key === "componentForCollection"
- ) {
- if (typeof value === "string") {
- this.selectKit.options.set(key, () => value);
- } else {
- this.selectKit.options.set(key, bind(this, value));
- }
+ this._cancelSearch();
- return;
- }
+ this.appEvents.off("keyboard-visibility-change", this, this._updatePopper);
- if (
- typeof value === "string" &&
- !value.includes(".") &&
- value in this
- ) {
- const computedValue = get(this, value);
- if (typeof computedValue !== "function") {
- this.selectKit.options.set(key, computedValue);
- return;
- }
- }
+ if (this.popper) {
+ this.popper.destroy();
+ this.popper = null;
+ }
+ }
- this.selectKit.options.set(key, value);
- });
+ didReceiveAttrs() {
+ super.didReceiveAttrs(...arguments);
- this.selectKit.setProperties({
- hasSelection: !isEmpty(this.value),
- noneItem: this._modifyNoSelectionWrapper(),
- newItem: null,
- });
+ const deprecatedOptions = this._resolveDeprecatedOptions();
+ const mergedOptions = Object.assign({}, ...this.selectKitOptions);
+ Object.keys(mergedOptions).forEach((key) => {
+ if (isPresent(this.options[key])) {
+ this.selectKit.options.set(key, this.options[key]);
+ return;
+ }
- if (this.selectKit.isExpanded) {
- this.triggerSearch();
+ if (isPresent(deprecatedOptions[`options.${key}`])) {
+ this.selectKit.options.set(key, deprecatedOptions[`options.${key}`]);
+ return;
}
- if (this.computeContent) {
- this._deprecated(
- `The \`computeContent()\` function is deprecated pass a \`content\` attribute or define a \`content\` computed property in your component.`
- );
+ const value = mergedOptions[key];
+
+ if (
+ key === "componentForRow" ||
+ key === "contentForCollection" ||
+ key === "componentForCollection"
+ ) {
+ if (typeof value === "string") {
+ this.selectKit.options.set(key, () => value);
+ } else {
+ this.selectKit.options.set(key, bind(this, value));
+ }
- this.set("content", this.computeContent());
+ return;
}
- },
-
- selectKitOptions: {
- allowAny: false,
- showFullTitle: true,
- none: null,
- translatedNone: null,
- filterable: false,
- autoFilterable: "autoFilterable",
- filterIcon: "search",
- filterPlaceholder: null,
- translatedFilterPlaceholder: null,
- icon: null,
- icons: null,
- maximum: null,
- maximumLabel: null,
- minimum: null,
- autoInsertNoneItem: true,
- closeOnChange: true,
- useHeaderFilter: false,
- limitMatches: null,
- placement: isDocumentRTL() ? "bottom-end" : "bottom-start",
- verticalOffset: 3,
- filterComponent: "select-kit/select-kit-filter",
- selectedNameComponent: "selected-name",
- selectedChoiceComponent: "selected-choice",
- castInteger: false,
- focusAfterOnChange: true,
- triggerOnChangeOnTab: true,
- autofocus: false,
- placementStrategy: null,
- mobilePlacementStrategy: null,
- desktopPlacementStrategy: null,
- hiddenValues: null,
- disabled: false,
- expandedOnInsert: false,
- formName: null,
- },
-
- autoFilterable: computed("content.[]", "selectKit.filter", function () {
- return (
- this.selectKit.filter &&
- this.options.autoFilterable &&
- this.content.length > 15
- );
- }),
-
- collections: computed(
- "selectedContent.[]",
- "mainCollection.[]",
- "errorsCollection.[]",
- function () {
- return this._collections.map((identifier) => {
- return {
- identifier,
- content: this.selectKit.modifyContentForCollection(identifier),
- };
- });
+
+ if (typeof value === "string" && !value.includes(".") && value in this) {
+ const computedValue = get(this, value);
+ if (typeof computedValue !== "function") {
+ this.selectKit.options.set(key, computedValue);
+ return;
+ }
}
- ),
- createContentFromInput(input) {
- return input;
- },
+ this.selectKit.options.set(key, value);
+ });
+
+ this.selectKit.setProperties({
+ hasSelection: !isEmpty(this.value),
+ noneItem: this._modifyNoSelectionWrapper(),
+ newItem: null,
+ });
- validateCreate(filter, content) {
- this.clearErrors();
+ if (this.selectKit.isExpanded) {
+ this.triggerSearch();
+ }
- return (
- filter.length > 0 &&
- content &&
- !content.map((c) => this.getValue(c)).includes(filter) &&
- !makeArray(this.value).includes(filter)
+ if (this.computeContent) {
+ this._deprecated(
+ `The \`computeContent()\` function is deprecated pass a \`content\` attribute or define a \`content\` computed property in your component.`
);
- },
- validateSelect() {
- this.clearErrors();
+ this.set("content", this.computeContent());
+ }
+ }
- const selection = makeArray(this.value);
+ @computed("content.[]", "selectKit.filter")
+ get autoFilterable() {
+ return (
+ this.selectKit.filter &&
+ this.options.autoFilterable &&
+ this.content.length > 15
+ );
+ }
- const maximum = this.selectKit.options.maximum;
- if (maximum && selection.length >= maximum) {
- const key =
- this.selectKit.options.maximumLabel ||
- "select_kit.max_content_reached";
- this.addError(I18n.t(key, { count: maximum }));
- return false;
- }
+ @computed("selectedContent.[]", "mainCollection.[]", "errorsCollection.[]")
+ get collections() {
+ return this._collections.map((identifier) => {
+ return {
+ identifier,
+ content: this.selectKit.modifyContentForCollection(identifier),
+ };
+ });
+ }
- return true;
- },
+ createContentFromInput(input) {
+ return input;
+ }
- addError(error) {
- if (!this.errorsCollection.includes(error)) {
- this.errorsCollection.pushObject(error);
- }
+ validateCreate(filter, content) {
+ this.clearErrors();
- this._safeAfterRender(() => this._updatePopper());
- },
+ return (
+ filter.length > 0 &&
+ content &&
+ !content.map((c) => this.getValue(c)).includes(filter) &&
+ !makeArray(this.value).includes(filter)
+ );
+ }
- clearErrors() {
- if (!this.element || this.isDestroyed || this.isDestroying) {
- return;
- }
+ validateSelect() {
+ this.clearErrors();
- this.set("errorsCollection", []);
- },
+ const selection = makeArray(this.value);
- prependCollection(identifier) {
- this._collections.unshift(identifier);
- },
+ const maximum = this.selectKit.options.maximum;
+ if (maximum && selection.length >= maximum) {
+ const key =
+ this.selectKit.options.maximumLabel || "select_kit.max_content_reached";
+ this.addError(I18n.t(key, { count: maximum }));
+ return false;
+ }
- appendCollection(identifier) {
- this._collections.push(identifier);
- },
+ return true;
+ }
- insertCollectionAtIndex(identifier, index) {
- this._collections.insertAt(index, identifier);
- },
+ addError(error) {
+ if (!this.errorsCollection.includes(error)) {
+ this.errorsCollection.pushObject(error);
+ }
- insertBeforeCollection(identifier, insertedIdentifier) {
- const index = this._collections.indexOf(identifier);
- this.insertCollectionAtIndex(insertedIdentifier, index - 1);
- },
+ this._safeAfterRender(() => this._updatePopper());
+ }
- insertAfterCollection(identifier, insertedIdentifier) {
- const index = this._collections.indexOf(identifier);
- this.insertCollectionAtIndex(insertedIdentifier, index + 1);
- },
+ clearErrors() {
+ if (!this.element || this.isDestroyed || this.isDestroying) {
+ return;
+ }
- _onInput(event) {
- this._updatePopper();
+ this.set("errorsCollection", []);
+ }
- if (this._searchPromise) {
- cancel(this._searchPromise);
- }
+ prependCollection(identifier) {
+ this._collections.unshift(identifier);
+ }
- this.selectKit.set("isLoading", true);
+ appendCollection(identifier) {
+ this._collections.push(identifier);
+ }
- discourseDebounce(
- this,
- this._debouncedInput,
- event.target.value,
- INPUT_DELAY
- );
- },
+ insertCollectionAtIndex(identifier, index) {
+ this._collections.insertAt(index, identifier);
+ }
- _debouncedInput(filter) {
- this.selectKit.set("filter", filter);
- this.triggerSearch(filter);
- },
+ insertBeforeCollection(identifier, insertedIdentifier) {
+ const index = this._collections.indexOf(identifier);
+ this.insertCollectionAtIndex(insertedIdentifier, index - 1);
+ }
- _onChangeWrapper(value, items) {
- this.selectKit.set("filter", null);
+ insertAfterCollection(identifier, insertedIdentifier) {
+ const index = this._collections.indexOf(identifier);
+ this.insertCollectionAtIndex(insertedIdentifier, index + 1);
+ }
- return new Promise((resolve) => {
- if (
- !this.selectKit.valueProperty &&
- this.selectKit.noneItem === value
- ) {
- value = null;
- items = [];
- }
+ _onInput(event) {
+ this._updatePopper();
- value = makeArray(value);
- items = makeArray(items);
+ if (this._searchPromise) {
+ cancel(this._searchPromise);
+ }
- if (this.multiSelect) {
- items = items.filter(
- (i) =>
- i !== this.newItem &&
- i !== this.noneItem &&
- this.getValue(i) !== null
- );
+ this.selectKit.set("isLoading", true);
- if (this.selectKit.options.maximum === 1) {
- value = value.slice(0, 1);
- items = items.slice(0, 1);
- }
- }
+ discourseDebounce(
+ this,
+ this._debouncedInput,
+ event.target.value,
+ INPUT_DELAY
+ );
+ }
- if (this.singleSelect) {
- value = isPresent(value.firstObject) ? value.firstObject : null;
- items = isPresent(items.firstObject) ? items.firstObject : null;
- }
+ _debouncedInput(filter) {
+ this.selectKit.set("filter", filter);
+ this.triggerSearch(filter);
+ }
- this._boundaryActionHandler("onChange", value, items);
+ _onChangeWrapper(value, items) {
+ this.selectKit.set("filter", null);
- applyOnChangePluginApiCallbacks(value, items, this);
+ return new Promise((resolve) => {
+ if (!this.selectKit.valueProperty && this.selectKit.noneItem === value) {
+ value = null;
+ items = [];
+ }
- resolve(items);
- }).finally(() => {
- if (!this.isDestroying && !this.isDestroyed) {
- if (
- this.selectKit.options.closeOnChange ||
- (isPresent(value) && this.selectKit.options.maximum === 1)
- ) {
- this.selectKit.close(event);
- }
+ value = makeArray(value);
+ items = makeArray(items);
- if (this.selectKit.options.focusAfterOnChange) {
- this._safeAfterRender(() => {
- this._focusFilter();
- this._updatePopper();
- });
- }
+ if (this.multiSelect) {
+ items = items.filter(
+ (i) =>
+ i !== this.newItem &&
+ i !== this.noneItem &&
+ this.getValue(i) !== null
+ );
+
+ if (this.selectKit.options.maximum === 1) {
+ value = value.slice(0, 1);
+ items = items.slice(0, 1);
}
- });
- },
+ }
- _modifyContentWrapper(content) {
- content = this.modifyContent(content);
+ if (this.singleSelect) {
+ value = isPresent(value.firstObject) ? value.firstObject : null;
+ items = isPresent(items.firstObject) ? items.firstObject : null;
+ }
- return applyContentPluginApiCallbacks(content, this);
- },
+ this._boundaryActionHandler("onChange", value, items);
- modifyContent(content) {
- return content;
- },
+ applyOnChangePluginApiCallbacks(value, items, this);
- _modifyNoSelectionWrapper() {
- return this.modifyNoSelection();
- },
+ resolve(items);
+ }).finally(() => {
+ if (!this.isDestroying && !this.isDestroyed) {
+ if (
+ this.selectKit.options.closeOnChange ||
+ (isPresent(value) && this.selectKit.options.maximum === 1)
+ ) {
+ this.selectKit.close(event);
+ }
- modifyNoSelection() {
- if (this.selectKit.options.translatedNone) {
- return this.defaultItem(null, this.selectKit.options.translatedNone);
+ if (this.selectKit.options.focusAfterOnChange) {
+ this._safeAfterRender(() => {
+ this._focusFilter();
+ this._updatePopper();
+ });
+ }
}
+ });
+ }
- let none = this.selectKit.options.none;
- if (isNone(none) && !this.selectKit.options.allowAny) {
- return null;
- }
+ _modifyContentWrapper(content) {
+ content = this.modifyContent(content);
- if (
- isNone(none) &&
- this.selectKit.options.allowAny &&
- !this.selectKit.isExpanded
- ) {
- return null;
- }
+ return applyContentPluginApiCallbacks(content, this);
+ }
- let item;
- switch (typeof none) {
- case "string":
- item = this.defaultItem(null, I18n.t(none));
- break;
- default:
- item = none;
- }
+ modifyContent(content) {
+ return content;
+ }
- return item;
- },
+ _modifyNoSelectionWrapper() {
+ return this.modifyNoSelection();
+ }
- _modifySelectionWrapper(item) {
- return this.modifySelection(item);
- },
+ modifyNoSelection() {
+ if (this.selectKit.options.translatedNone) {
+ return this.defaultItem(null, this.selectKit.options.translatedNone);
+ }
+
+ let none = this.selectKit.options.none;
+ if (isNone(none) && !this.selectKit.options.allowAny) {
+ return null;
+ }
+
+ if (
+ isNone(none) &&
+ this.selectKit.options.allowAny &&
+ !this.selectKit.isExpanded
+ ) {
+ return null;
+ }
+
+ let item;
+ switch (typeof none) {
+ case "string":
+ item = this.defaultItem(null, I18n.t(none));
+ break;
+ default:
+ item = none;
+ }
+
+ return item;
+ }
- modifySelection(item) {
- return item;
- },
+ _modifySelectionWrapper(item) {
+ return this.modifySelection(item);
+ }
- _onKeydownWrapper(event) {
- return this._boundaryActionHandler("onKeydown", event);
- },
+ modifySelection(item) {
+ return item;
+ }
- _mainElement() {
- return document.querySelector(`#${this.selectKit.uniqueID}`);
- },
+ _onKeydownWrapper(event) {
+ return this._boundaryActionHandler("onKeydown", event);
+ }
- _headerElement() {
- return this.selectKit.mainElement().querySelector("summary");
- },
+ _mainElement() {
+ return document.querySelector(`#${this.selectKit.uniqueID}`);
+ }
- _bodyElement() {
- return this.selectKit.mainElement().querySelector(".select-kit-body");
- },
+ _headerElement() {
+ return this.selectKit.mainElement().querySelector("summary");
+ }
- _onHover(value, item) {
- throttle(this, this._highlight, item, 25, true);
- },
+ _bodyElement() {
+ return this.selectKit.mainElement().querySelector(".select-kit-body");
+ }
- _highlight(item) {
- this.selectKit.set("highlighted", item);
- },
+ _onHover(value, item) {
+ throttle(this, this._highlight, item, 25, true);
+ }
- _boundaryActionHandler(actionName, ...params) {
- if (!this.element || this.isDestroying || this.isDestroyed) {
- return;
- }
+ _highlight(item) {
+ this.selectKit.set("highlighted", item);
+ }
- let boundaryAction = true;
+ _boundaryActionHandler(actionName, ...params) {
+ if (!this.element || this.isDestroying || this.isDestroyed) {
+ return;
+ }
- const privateActionName = `_${actionName}`;
- const privateAction = get(this, privateActionName);
- if (privateAction) {
- boundaryAction = privateAction.call(this, ...params);
- }
+ let boundaryAction = true;
- if (this.actions) {
- const componentAction = get(this.actions, actionName);
- if (boundaryAction && componentAction) {
- boundaryAction = componentAction.call(this, ...params);
- }
- }
+ const privateActionName = `_${actionName}`;
+ const privateAction = get(this, privateActionName);
+ if (privateAction) {
+ boundaryAction = privateAction.call(this, ...params);
+ }
- const action = get(this, actionName);
- if (boundaryAction && action) {
- boundaryAction = action.call(this, ...params);
+ if (this.actions) {
+ const componentAction = get(this.actions, actionName);
+ if (boundaryAction && componentAction) {
+ boundaryAction = componentAction.call(this, ...params);
}
+ }
- return boundaryAction;
- },
+ const action = get(this, actionName);
+ if (boundaryAction && action) {
+ boundaryAction = action.call(this, ...params);
+ }
- deselect() {
- this.clearErrors();
- this.selectKit.change(null, null);
- },
-
- deselectByValue(value) {
- if (!value) {
- return;
- }
+ return boundaryAction;
+ }
- const item = this.itemForValue(value, this.selectedContent);
- this.deselect(item);
- },
-
- append() {
- // do nothing on general case
- },
-
- search(filter) {
- let content = this.content || [];
- if (filter) {
- filter = this._normalize(filter);
- content = content.filter((c) => {
- const name = this._normalize(this.getName(c));
- return name?.includes(filter);
- });
- }
- return content;
- },
+ deselect() {
+ this.clearErrors();
+ this.selectKit.change(null, null);
+ }
- triggerSearch(filter) {
- this._searchPromise && cancel(this._searchPromise);
+ deselectByValue(value) {
+ if (!value) {
+ return;
+ }
- this._searchPromise = this._searchWrapper(
- filter || this.selectKit.filter
- );
- },
+ const item = this.itemForValue(value, this.selectedContent);
+ this.deselect(item);
+ }
- _searchWrapper(filter) {
- if (this.isDestroyed || this.isDestroying) {
- return Promise.resolve([]);
- }
+ append() {
+ // do nothing on general case
+ }
- this.clearErrors();
- this.setProperties({
- mainCollection: [],
- "selectKit.isLoading": true,
- "selectKit.enterDisabled": true,
+ search(filter) {
+ let content = this.content || [];
+ if (filter) {
+ filter = this._normalize(filter);
+ content = content.filter((c) => {
+ const name = this._normalize(this.getName(c));
+ return name?.includes(filter);
});
- this._safeAfterRender(() => this._updatePopper());
+ }
+ return content;
+ }
- let content = [];
+ triggerSearch(filter) {
+ this._searchPromise && cancel(this._searchPromise);
- return Promise.resolve(this.search(filter))
- .then((result) => {
- if (this.isDestroyed || this.isDestroying) {
- return [];
- }
+ this._searchPromise = this._searchWrapper(filter || this.selectKit.filter);
+ }
- if (this.selectKit.options.maximum === 0) {
- this.set("selectKit.isLoading", false);
- this.set("selectKit.hasNoContent", false);
- return [];
- }
+ _searchWrapper(filter) {
+ if (this.isDestroyed || this.isDestroying) {
+ return Promise.resolve([]);
+ }
+
+ this.clearErrors();
+ this.setProperties({
+ mainCollection: [],
+ "selectKit.isLoading": true,
+ "selectKit.enterDisabled": true,
+ });
+ this._safeAfterRender(() => this._updatePopper());
+
+ let content = [];
+
+ return Promise.resolve(this.search(filter))
+ .then((result) => {
+ if (this.isDestroyed || this.isDestroying) {
+ return [];
+ }
- content = content.concat(makeArray(result));
- content = this.selectKit.modifyContent(content).filter(Boolean);
+ if (this.selectKit.options.maximum === 0) {
+ this.set("selectKit.isLoading", false);
+ this.set("selectKit.hasNoContent", false);
+ return [];
+ }
- if (this.selectKit.valueProperty) {
- content = content.uniqBy(this.selectKit.valueProperty);
- } else {
- content = content.uniq();
- }
+ content = content.concat(makeArray(result));
+ content = this.selectKit.modifyContent(content).filter(Boolean);
- if (this.selectKit.options.limitMatches) {
- content = content.slice(0, this.selectKit.options.limitMatches);
- }
+ if (this.selectKit.valueProperty) {
+ content = content.uniqBy(this.selectKit.valueProperty);
+ } else {
+ content = content.uniq();
+ }
- const noneItem = this.selectKit.noneItem;
- if (
- this.selectKit.options.allowAny &&
- filter &&
- this.getName(noneItem) !== filter
- ) {
- filter = this.createContentFromInput(filter);
- if (this.validateCreate(filter, content)) {
- this.selectKit.set("newItem", this.defaultItem(filter, filter));
- content.unshift(this.selectKit.newItem);
- }
- }
+ if (this.selectKit.options.limitMatches) {
+ content = content.slice(0, this.selectKit.options.limitMatches);
+ }
- const hasNoContent = isEmpty(content);
- if (
- this.selectKit.hasSelection &&
- noneItem &&
- this.selectKit.options.autoInsertNoneItem
- ) {
- content.unshift(noneItem);
+ const noneItem = this.selectKit.noneItem;
+ if (
+ this.selectKit.options.allowAny &&
+ filter &&
+ this.getName(noneItem) !== filter
+ ) {
+ filter = this.createContentFromInput(filter);
+ if (this.validateCreate(filter, content)) {
+ this.selectKit.set("newItem", this.defaultItem(filter, filter));
+ content.unshift(this.selectKit.newItem);
}
+ }
- this.set("mainCollection", content);
-
- this.selectKit.setProperties({
- highlighted:
- this.singleSelect && this.value
- ? this.itemForValue(this.value, this.mainCollection)
- : isEmpty(this.selectKit.filter)
- ? null
- : this.mainCollection.firstObject,
- isLoading: false,
- hasNoContent,
- });
+ const hasNoContent = isEmpty(content);
+ if (
+ this.selectKit.hasSelection &&
+ noneItem &&
+ this.selectKit.options.autoInsertNoneItem
+ ) {
+ content.unshift(noneItem);
+ }
- this._safeAfterRender(() => {
- if (this.selectKit.isExpanded) {
- this._updatePopper();
- this._focusFilter();
- }
- });
- })
- .finally(() => {
- if (this.isDestroyed || this.isDestroying) {
- return;
- }
- this.set("selectKit.enterDisabled", false);
+ this.set("mainCollection", content);
+
+ this.selectKit.setProperties({
+ highlighted:
+ this.singleSelect && this.value
+ ? this.itemForValue(this.value, this.mainCollection)
+ : isEmpty(this.selectKit.filter)
+ ? null
+ : this.mainCollection.firstObject,
+ isLoading: false,
+ hasNoContent,
});
- },
- _safeAfterRender(fn) {
- next(() => {
- schedule("afterRender", () => {
- if (!this.element || this.isDestroyed || this.isDestroying) {
- return;
+ this._safeAfterRender(() => {
+ if (this.selectKit.isExpanded) {
+ this._updatePopper();
+ this._focusFilter();
}
-
- fn();
});
+ })
+ .finally(() => {
+ if (this.isDestroyed || this.isDestroying) {
+ return;
+ }
+ this.set("selectKit.enterDisabled", false);
});
- },
+ }
- _scrollToRow(rowItem, preventScroll = true) {
- const value = this.getValue(rowItem);
+ _safeAfterRender(fn) {
+ next(() => {
+ schedule("afterRender", () => {
+ if (!this.element || this.isDestroyed || this.isDestroying) {
+ return;
+ }
- let rowContainer;
- if (isPresent(value)) {
- rowContainer = this.element.querySelector(
- `.select-kit-row[data-value="${value}"]`
- );
- } else {
- rowContainer = this.element.querySelector(".select-kit-row.is-none");
- }
+ fn();
+ });
+ });
+ }
- rowContainer?.focus({ preventScroll });
- },
+ _scrollToRow(rowItem, preventScroll = true) {
+ const value = this.getValue(rowItem);
- _highlightLast() {
- const highlighted = this.mainCollection.objectAt(
- this.mainCollection.length - 1
+ let rowContainer;
+ if (isPresent(value)) {
+ rowContainer = this.element.querySelector(
+ `.select-kit-row[data-value="${value}"]`
);
- if (highlighted) {
- this._scrollToRow(highlighted, false);
- this.set("selectKit.highlighted", highlighted);
- }
- },
+ } else {
+ rowContainer = this.element.querySelector(".select-kit-row.is-none");
+ }
- _highlightFirst() {
- const highlighted = this.mainCollection.objectAt(0);
- if (highlighted) {
- this._scrollToRow(highlighted, false);
- this.set("selectKit.highlighted", highlighted);
- }
- },
+ rowContainer?.focus({ preventScroll });
+ }
- _highlightNext() {
- let highlightedIndex = this.mainCollection.indexOf(
- this.selectKit.highlighted
- );
- const count = this.mainCollection.length;
+ _highlightLast() {
+ const highlighted = this.mainCollection.objectAt(
+ this.mainCollection.length - 1
+ );
+ if (highlighted) {
+ this._scrollToRow(highlighted, false);
+ this.set("selectKit.highlighted", highlighted);
+ }
+ }
+
+ _highlightFirst() {
+ const highlighted = this.mainCollection.objectAt(0);
+ if (highlighted) {
+ this._scrollToRow(highlighted, false);
+ this.set("selectKit.highlighted", highlighted);
+ }
+ }
- if (highlightedIndex < count - 1) {
- highlightedIndex = highlightedIndex + 1;
+ _highlightNext() {
+ let highlightedIndex = this.mainCollection.indexOf(
+ this.selectKit.highlighted
+ );
+ const count = this.mainCollection.length;
+
+ if (highlightedIndex < count - 1) {
+ highlightedIndex = highlightedIndex + 1;
+ } else {
+ if (this.selectKit.isFilterExpanded) {
+ this._focusFilter();
+ this.set("selectKit.highlighted", null);
+ return;
} else {
- if (this.selectKit.isFilterExpanded) {
- this._focusFilter();
- this.set("selectKit.highlighted", null);
- return;
- } else {
- highlightedIndex = 0;
- }
+ highlightedIndex = 0;
}
+ }
- const highlighted = this.mainCollection.objectAt(highlightedIndex);
- if (highlighted) {
- this._scrollToRow(highlighted, false);
- this.set("selectKit.highlighted", highlighted);
- }
- },
+ const highlighted = this.mainCollection.objectAt(highlightedIndex);
+ if (highlighted) {
+ this._scrollToRow(highlighted, false);
+ this.set("selectKit.highlighted", highlighted);
+ }
+ }
- _highlightPrevious() {
- let highlightedIndex = this.mainCollection.indexOf(
- this.selectKit.highlighted
- );
- const count = this.mainCollection.length;
+ _highlightPrevious() {
+ let highlightedIndex = this.mainCollection.indexOf(
+ this.selectKit.highlighted
+ );
+ const count = this.mainCollection.length;
- if (highlightedIndex > 0) {
- highlightedIndex = highlightedIndex - 1;
+ if (highlightedIndex > 0) {
+ highlightedIndex = highlightedIndex - 1;
+ } else {
+ if (this.selectKit.isFilterExpanded) {
+ this._focusFilter();
+ this.set("selectKit.highlighted", null);
+ return;
} else {
- if (this.selectKit.isFilterExpanded) {
- this._focusFilter();
- this.set("selectKit.highlighted", null);
- return;
- } else {
- highlightedIndex = count - 1;
- }
+ highlightedIndex = count - 1;
}
+ }
- const highlighted = this.mainCollection.objectAt(highlightedIndex);
- if (highlighted) {
- this._scrollToRow(highlighted, false);
- this.set("selectKit.highlighted", highlighted);
- }
- },
+ const highlighted = this.mainCollection.objectAt(highlightedIndex);
+ if (highlighted) {
+ this._scrollToRow(highlighted, false);
+ this.set("selectKit.highlighted", highlighted);
+ }
+ }
- _deselectLast() {
- if (this.selectKit.hasSelection) {
- this.deselectByValue(this.value[this.value.length - 1]);
- }
- },
+ _deselectLast() {
+ if (this.selectKit.hasSelection) {
+ this.deselectByValue(this.value[this.value.length - 1]);
+ }
+ }
- select(value, item) {
- if (!isPresent(value)) {
- this._onClearSelection();
- } else {
- const existingItem = this.findValue(this.mainCollection, item);
- if (existingItem) {
- if (!this.validateSelect(item)) {
- return;
- }
+ select(value, item) {
+ if (!isPresent(value)) {
+ this._onClearSelection();
+ } else {
+ const existingItem = this.findValue(this.mainCollection, item);
+ if (existingItem) {
+ if (!this.validateSelect(item)) {
+ return;
}
-
- this.selectKit.change(value, item || this.defaultItem(value, value));
}
- },
- _onClearSelection() {
- this.selectKit.change(null, null);
- },
+ this.selectKit.change(value, item || this.defaultItem(value, value));
+ }
+ }
- _onOpenWrapper() {
- return this._boundaryActionHandler("onOpen");
- },
+ _onClearSelection() {
+ this.selectKit.change(null, null);
+ }
- _cancelSearch() {
- this._searchPromise && cancel(this._searchPromise);
- },
+ _onOpenWrapper() {
+ return this._boundaryActionHandler("onOpen");
+ }
- _onCloseWrapper() {
- this._cancelSearch();
- this.set("selectKit.highlighted", null);
+ _cancelSearch() {
+ this._searchPromise && cancel(this._searchPromise);
+ }
- return this._boundaryActionHandler("onClose");
- },
+ _onCloseWrapper() {
+ this._cancelSearch();
+ this.set("selectKit.highlighted", null);
- _toggle(event) {
- if (this.selectKit.isExpanded) {
- this._close(event);
- } else {
- this._open(event);
- }
- },
+ return this._boundaryActionHandler("onClose");
+ }
- _close(event) {
- if (!this.selectKit.isExpanded) {
- return;
- }
+ _toggle(event) {
+ if (this.selectKit.isExpanded) {
+ this._close(event);
+ } else {
+ this._open(event);
+ }
+ }
- this.selectKit.mainElement().open = false;
+ _close(event) {
+ if (!this.selectKit.isExpanded) {
+ return;
+ }
- this.clearErrors();
+ this.selectKit.mainElement().open = false;
- const inModal = this.element.closest(".fixed-modal");
- if (inModal && this.site.mobileView) {
- const modalBody = inModal.querySelector(".modal-body");
- modalBody.style = "";
- }
+ this.clearErrors();
- this.selectKit.onClose(event);
+ const inModal = this.element.closest(".fixed-modal");
+ if (inModal && this.site.mobileView) {
+ const modalBody = inModal.querySelector(".modal-body");
+ modalBody.style = "";
+ }
- this.selectKit.setProperties({
- isExpanded: false,
- filter: null,
- });
- },
+ this.selectKit.onClose(event);
- _open(event) {
- if (this.selectKit.isExpanded) {
- return;
- }
+ this.selectKit.setProperties({
+ isExpanded: false,
+ filter: null,
+ });
+ }
- this.selectKit.mainElement().open = true;
- this.clearErrors();
- this.selectKit.onOpen(event);
+ _open(event) {
+ if (this.selectKit.isExpanded) {
+ return;
+ }
- if (!this.popper) {
- const inModal = this.element.closest(".fixed-modal .modal-body");
- const anchor = document.querySelector(
- `#${this.selectKit.uniqueID}-header`
- );
- const popper = document.querySelector(
- `#${this.selectKit.uniqueID}-body`
- );
- const strategy = this._computePlacementStrategy();
-
- let bottomOffset = 0;
- if (this.capabilities.isIOS) {
- bottomOffset +=
- parseInt(
- getComputedStyle(document.documentElement)
- .getPropertyValue("--safe-area-inset-bottom")
- .trim(),
- 10
- ) || 0;
- }
- if (this.site.mobileView) {
- bottomOffset +=
- parseInt(
- getComputedStyle(document.documentElement)
- .getPropertyValue("--footer-nav-height")
- .trim(),
- 10
- ) || 0;
- }
+ this.selectKit.mainElement().open = true;
+ this.clearErrors();
+ this.selectKit.onOpen(event);
- this.popper = createPopper(anchor, popper, {
- eventsEnabled: false,
- strategy,
- placement: this.selectKit.options.placement,
- modifiers: [
- {
- name: "eventListeners",
- options: {
- resize: this.site.desktopView,
- scroll: this.site.desktopView,
- },
+ if (!this.popper) {
+ const inModal = this.element.closest(".fixed-modal .modal-body");
+ const anchor = document.querySelector(
+ `#${this.selectKit.uniqueID}-header`
+ );
+ const popper = document.querySelector(`#${this.selectKit.uniqueID}-body`);
+ const strategy = this._computePlacementStrategy();
+
+ let bottomOffset = 0;
+ if (this.capabilities.isIOS) {
+ bottomOffset +=
+ parseInt(
+ getComputedStyle(document.documentElement)
+ .getPropertyValue("--safe-area-inset-bottom")
+ .trim(),
+ 10
+ ) || 0;
+ }
+ if (this.site.mobileView) {
+ bottomOffset +=
+ parseInt(
+ getComputedStyle(document.documentElement)
+ .getPropertyValue("--footer-nav-height")
+ .trim(),
+ 10
+ ) || 0;
+ }
+
+ this.popper = createPopper(anchor, popper, {
+ eventsEnabled: false,
+ strategy,
+ placement: this.selectKit.options.placement,
+ modifiers: [
+ {
+ name: "eventListeners",
+ options: {
+ resize: this.site.desktopView,
+ scroll: this.site.desktopView,
},
- {
- name: "flip",
- enabled: !inModal,
- options: {
- padding: {
- top:
- parseInt(
- document.documentElement.style.getPropertyValue(
- "--header-offset"
- ),
- 10
- ) || 0,
- bottom: bottomOffset,
- },
+ },
+ {
+ name: "flip",
+ enabled: !inModal,
+ options: {
+ padding: {
+ top:
+ parseInt(
+ document.documentElement.style.getPropertyValue(
+ "--header-offset"
+ ),
+ 10
+ ) || 0,
+ bottom: bottomOffset,
},
},
- {
- name: "offset",
- options: {
- offset: [0, this.selectKit.options.verticalOffset],
- },
+ },
+ {
+ name: "offset",
+ options: {
+ offset: [0, this.selectKit.options.verticalOffset],
},
- {
- name: "applySmallScreenOffset",
- enabled: window.innerWidth <= 450,
- phase: "main",
- fn({ state }) {
- if (!inModal) {
- let { x } = state.elements.reference.getBoundingClientRect();
- if (strategy === "fixed") {
- state.modifiersData.popperOffsets.x = 0 + 10;
- } else {
- state.modifiersData.popperOffsets.x = -x + 10;
- }
+ },
+ {
+ name: "applySmallScreenOffset",
+ enabled: window.innerWidth <= 450,
+ phase: "main",
+ fn({ state }) {
+ if (!inModal) {
+ let { x } = state.elements.reference.getBoundingClientRect();
+ if (strategy === "fixed") {
+ state.modifiersData.popperOffsets.x = 0 + 10;
+ } else {
+ state.modifiersData.popperOffsets.x = -x + 10;
}
- },
+ }
},
- {
- name: "applySmallScreenMaxWidth",
- enabled: window.innerWidth <= 450,
- phase: "beforeWrite",
- fn: ({ state }) => {
- if (inModal) {
- const innerModal = document.querySelector(
- ".fixed-modal div.modal-inner-container"
- );
-
- if (innerModal) {
- if (this.multiSelect) {
- state.styles.popper.width = `${this.element.offsetWidth}px`;
- } else {
- state.styles.popper.width = `${
- innerModal.clientWidth - 20
- }px`;
- }
+ },
+ {
+ name: "applySmallScreenMaxWidth",
+ enabled: window.innerWidth <= 450,
+ phase: "beforeWrite",
+ fn: ({ state }) => {
+ if (inModal) {
+ const innerModal = document.querySelector(
+ ".fixed-modal div.modal-inner-container"
+ );
+
+ if (innerModal) {
+ if (this.multiSelect) {
+ state.styles.popper.width = `${this.element.offsetWidth}px`;
+ } else {
+ state.styles.popper.width = `${
+ innerModal.clientWidth - 20
+ }px`;
}
- } else {
- state.styles.popper.width = `${window.innerWidth - 20}px`;
}
- },
+ } else {
+ state.styles.popper.width = `${window.innerWidth - 20}px`;
+ }
},
- {
- name: "minWidth",
- enabled: window.innerWidth > 450,
- phase: "beforeWrite",
- requires: ["computeStyles"],
- fn: ({ state }) => {
- state.styles.popper.minWidth = `${Math.max(
- state.rects.reference.width,
- 220
- )}px`;
- },
- effect: ({ state }) => {
- state.elements.popper.style.minWidth = `${Math.max(
- state.elements.reference.offsetWidth,
- 220
- )}px`;
- },
+ },
+ {
+ name: "minWidth",
+ enabled: window.innerWidth > 450,
+ phase: "beforeWrite",
+ requires: ["computeStyles"],
+ fn: ({ state }) => {
+ state.styles.popper.minWidth = `${Math.max(
+ state.rects.reference.width,
+ 220
+ )}px`;
},
- {
- name: "modalHeight",
- enabled: !!(inModal && this.site.mobileView),
- phase: "afterWrite",
- fn: ({ state }) => {
- inModal.style = "";
- inModal.style.height =
- inModal.clientHeight + state.rects.popper.height + "px";
- },
+ effect: ({ state }) => {
+ state.elements.popper.style.minWidth = `${Math.max(
+ state.elements.reference.offsetWidth,
+ 220
+ )}px`;
},
- ],
- });
- }
-
- this.selectKit.setProperties({
- isExpanded: true,
- isFilterExpanded:
- this.selectKit.options.filterable || this.selectKit.options.allowAny,
+ },
+ {
+ name: "modalHeight",
+ enabled: !!(inModal && this.site.mobileView),
+ phase: "afterWrite",
+ fn: ({ state }) => {
+ inModal.style = "";
+ inModal.style.height =
+ inModal.clientHeight + state.rects.popper.height + "px";
+ },
+ },
+ ],
});
+ }
- if (this.selectKit.options.useHeaderFilter) {
- this._focusFilterInput();
- }
+ this.selectKit.setProperties({
+ isExpanded: true,
+ isFilterExpanded:
+ this.selectKit.options.filterable || this.selectKit.options.allowAny,
+ });
- this.triggerSearch();
+ if (this.selectKit.options.useHeaderFilter) {
+ this._focusFilterInput();
+ }
- this._safeAfterRender(() => {
- this._focusFilter();
- this._scrollToCurrent();
- this._updatePopper();
- });
- },
-
- _scrollToCurrent() {
- if (this.value && this.mainCollection) {
- let highlighted;
- if (this.valueProperty) {
- highlighted = this.mainCollection.findBy(
- this.valueProperty,
- this.value
- );
- } else {
- const index = this.mainCollection.indexOf(this.value);
- highlighted = this.mainCollection.objectAt(index);
- }
+ this.triggerSearch();
- if (highlighted) {
- this._scrollToRow(highlighted, false);
- this.set("selectKit.highlighted", highlighted);
- }
+ this._safeAfterRender(() => {
+ this._focusFilter();
+ this._scrollToCurrent();
+ this._updatePopper();
+ });
+ }
+
+ _scrollToCurrent() {
+ if (this.value && this.mainCollection) {
+ let highlighted;
+ if (this.valueProperty) {
+ highlighted = this.mainCollection.findBy(
+ this.valueProperty,
+ this.value
+ );
+ } else {
+ const index = this.mainCollection.indexOf(this.value);
+ highlighted = this.mainCollection.objectAt(index);
}
- },
- _focusFilter(forceHeader = false) {
- if (!this.selectKit.mainElement()) {
- return;
+ if (highlighted) {
+ this._scrollToRow(highlighted, false);
+ this.set("selectKit.highlighted", highlighted);
}
+ }
+ }
+
+ _focusFilter(forceHeader = false) {
+ if (!this.selectKit.mainElement()) {
+ return;
+ }
+
+ if (!this.selectKit.mainElement().open) {
+ const headerContainer = this.getHeader();
+ headerContainer && headerContainer.focus({ preventScroll: true });
+ return;
+ }
- if (!this.selectKit.mainElement().open) {
+ // setting focus as early as possible is best for iOS
+ // because render/promise delays may cause keyboard not to show
+ if (!forceHeader) {
+ this._focusFilterInput();
+ }
+
+ this._safeAfterRender(() => {
+ const input = this.getFilterInput();
+ if (!forceHeader && input) {
+ this._focusFilterInput();
+ } else if (!this.selectKit.options.preventHeaderFocus) {
const headerContainer = this.getHeader();
headerContainer && headerContainer.focus({ preventScroll: true });
- return;
}
+ });
+ }
- // setting focus as early as possible is best for iOS
- // because render/promise delays may cause keyboard not to show
- if (!forceHeader) {
- this._focusFilterInput();
- }
+ _focusFilterInput() {
+ const input = this.getFilterInput();
- this._safeAfterRender(() => {
- const input = this.getFilterInput();
- if (!forceHeader && input) {
- this._focusFilterInput();
- } else if (!this.selectKit.options.preventHeaderFocus) {
- const headerContainer = this.getHeader();
- headerContainer && headerContainer.focus({ preventScroll: true });
- }
- });
- },
+ if (input && document.activeElement !== input) {
+ input.focus({ preventScroll: true });
- _focusFilterInput() {
- const input = this.getFilterInput();
+ if (typeof input.selectionStart === "number") {
+ input.selectionStart = input.selectionEnd = input.value.length;
+ }
+ }
+ }
- if (input && document.activeElement !== input) {
- input.focus({ preventScroll: true });
+ getFilterInput() {
+ return document.querySelector(`#${this.selectKit.uniqueID}-filter input`);
+ }
- if (typeof input.selectionStart === "number") {
- input.selectionStart = input.selectionEnd = input.value.length;
- }
- }
- },
+ getHeader() {
+ return document.querySelector(`#${this.selectKit.uniqueID}-header`);
+ }
- getFilterInput() {
- return document.querySelector(`#${this.selectKit.uniqueID}-filter input`);
- },
+ handleDeprecations() {
+ this._deprecateValueAttribute();
+ this._deprecateMutations();
+ this._handleDeprecatedArgs();
+ }
- getHeader() {
- return document.querySelector(`#${this.selectKit.uniqueID}-header`);
- },
+ @bindDecorator
+ _updatePopper() {
+ this.popper?.update?.();
+ }
- handleDeprecations() {
- this._deprecateValueAttribute();
- this._deprecateMutations();
- this._handleDeprecatedArgs();
- },
+ _computePlacementStrategy() {
+ let placementStrategy = this.selectKit.options.placementStrategy;
- @bindDecorator
- _updatePopper() {
- this.popper?.update?.();
- },
+ if (placementStrategy) {
+ return placementStrategy;
+ }
- _computePlacementStrategy() {
- let placementStrategy = this.selectKit.options.placementStrategy;
+ if (this.capabilities.isIpadOS || this.site.mobileView) {
+ placementStrategy =
+ this.selectKit.options.mobilePlacementStrategy || "absolute";
+ } else {
+ placementStrategy =
+ this.selectKit.options.desktopPlacementStrategy || "fixed";
+ }
- if (placementStrategy) {
- return placementStrategy;
- }
+ return placementStrategy;
+ }
- if (this.capabilities.isIpadOS || this.site.mobileView) {
- placementStrategy =
- this.selectKit.options.mobilePlacementStrategy || "absolute";
- } else {
- placementStrategy =
- this.selectKit.options.desktopPlacementStrategy || "fixed";
- }
+ _deprecated(text) {
+ deprecated(text, {
+ since: "v2.4.0",
+ dropFrom: "2.9.0.beta1",
+ id: "discourse.select-kit",
+ });
+ }
- return placementStrategy;
- },
+ _deprecateValueAttribute() {
+ if (this.valueAttribute || this.valueAttribute === null) {
+ this._deprecated(
+ "The `valueAttribute` is deprecated. Use `valueProperty` instead"
+ );
- _deprecated(text) {
- deprecated(text, {
- since: "v2.4.0",
- dropFrom: "2.9.0.beta1",
- id: "discourse.select-kit",
- });
- },
+ this.set("valueProperty", this.valueAttribute);
+ }
+ }
- _deprecateValueAttribute() {
- if (this.valueAttribute || this.valueAttribute === null) {
- this._deprecated(
- "The `valueAttribute` is deprecated. Use `valueProperty` instead"
- );
+ _deprecateMutations() {
+ this.actions ??= {};
- this.set("valueProperty", this.valueAttribute);
- }
- },
+ if (!this.onChange && !this.actions.onChange) {
+ this._deprecated(
+ "Implicit mutation has been deprecated, please use `onChange` handler"
+ );
- _deprecateMutations() {
- this.actions ??= {};
+ this.actions.onChange =
+ this.onSelect ||
+ this.actions.onSelect ||
+ ((value) => this.set("value", value));
+ }
+ }
- if (!this.onChange && !this.actions.onChange) {
+ _resolveDeprecatedOptions() {
+ const migrations = {
+ allowAny: "options.allowAny",
+ allowCreate: "options.allowAny",
+ filterable: "options.filterable",
+ excludeCategoryId: "options.excludeCategoryId",
+ scopedCategoryId: "options.scopedCategoryId",
+ allowUncategorized: "options.allowUncategorized",
+ none: "options.none",
+ rootNone: "options.none",
+ disabled: "options.disabled",
+ isDisabled: "options.disabled",
+ rootNoneLabel: "options.none",
+ showFullTitle: "options.showFullTitle",
+ title: "options.translatedNone",
+ maximum: "options.maximum",
+ minimum: "options.minimum",
+ i18nPostfix: "options.i18nPostfix",
+ i18nPrefix: "options.i18nPrefix",
+ btnCustomClasses: "options.btnCustomClasses",
+ castInteger: "options.castInteger",
+ };
+
+ const resolvedDeprecations = {};
+
+ Object.keys(migrations).forEach((from) => {
+ const to = migrations[from];
+ if (this.get(from) && !this.get(to)) {
this._deprecated(
- "Implicit mutation has been deprecated, please use `onChange` handler"
+ `The \`${from}\` attribute is deprecated. Use \`${to}\` instead`
);
- this.actions.onChange =
- this.onSelect ||
- this.actions.onSelect ||
- ((value) => this.set("value", value));
+ resolvedDeprecations[(to, this.get(from))];
}
- },
-
- _resolveDeprecatedOptions() {
- const migrations = {
- allowAny: "options.allowAny",
- allowCreate: "options.allowAny",
- filterable: "options.filterable",
- excludeCategoryId: "options.excludeCategoryId",
- scopedCategoryId: "options.scopedCategoryId",
- allowUncategorized: "options.allowUncategorized",
- none: "options.none",
- rootNone: "options.none",
- disabled: "options.disabled",
- isDisabled: "options.disabled",
- rootNoneLabel: "options.none",
- showFullTitle: "options.showFullTitle",
- title: "options.translatedNone",
- maximum: "options.maximum",
- minimum: "options.minimum",
- i18nPostfix: "options.i18nPostfix",
- i18nPrefix: "options.i18nPrefix",
- btnCustomClasses: "options.btnCustomClasses",
- castInteger: "options.castInteger",
- };
-
- const resolvedDeprecations = {};
-
- Object.keys(migrations).forEach((from) => {
- const to = migrations[from];
- if (this.get(from) && !this.get(to)) {
- this._deprecated(
- `The \`${from}\` attribute is deprecated. Use \`${to}\` instead`
- );
-
- resolvedDeprecations[(to, this.get(from))];
- }
- });
+ });
- return resolvedDeprecations;
- },
+ return resolvedDeprecations;
+ }
- _handleDeprecatedArgs() {
- const migrations = {
- headerIcon: "icon",
- onExpand: "onOpen",
- onCollapse: "onClose",
- };
+ _handleDeprecatedArgs() {
+ const migrations = {
+ headerIcon: "icon",
+ onExpand: "onOpen",
+ onCollapse: "onClose",
+ };
- Object.keys(migrations).forEach((from) => {
- const to = migrations[from];
- if (this.get(from) && !this.get(to)) {
- this._deprecated(
- `The \`${from}\` attribute is deprecated. Use \`${to}\` instead`
- );
+ Object.keys(migrations).forEach((from) => {
+ const to = migrations[from];
+ if (this.get(from) && !this.get(to)) {
+ this._deprecated(
+ `The \`${from}\` attribute is deprecated. Use \`${to}\` instead`
+ );
- this.set(to, this.get(from));
- }
- });
- },
+ this.set(to, this.get(from));
+ }
+ });
}
-);
+}
+
+// Keep the concatenatedProperties behavior for legacy `.extend()` subclasses
+SelectKit.prototype.concatenatedProperties = [
+ ...SelectKit.prototype.concatenatedProperties,
+ "selectKitOptions",
+ "pluginApiIdentifiers",
+];
diff --git a/app/assets/javascripts/select-kit/addon/components/single-select.js b/app/assets/javascripts/select-kit/addon/components/single-select.js
index 733f66c0e71..a3f6916ee7d 100644
--- a/app/assets/javascripts/select-kit/addon/components/single-select.js
+++ b/app/assets/javascripts/select-kit/addon/components/single-select.js
@@ -1,46 +1,45 @@
import { computed } from "@ember/object";
import { isEmpty } from "@ember/utils";
-import SelectKitComponent from "select-kit/components/select-kit";
+import { classNames } from "@ember-decorators/component";
+import SelectKitComponent, {
+ pluginApiIdentifiers,
+ selectKitOptions,
+} from "select-kit/components/select-kit";
-export default SelectKitComponent.extend({
- pluginApiIdentifiers: ["single-select"],
- classNames: ["single-select"],
- singleSelect: true,
+@classNames("single-select")
+@selectKitOptions({
+ headerComponent: "select-kit/single-select-header",
+})
+@pluginApiIdentifiers(["single-select"])
+export default class SingleSelect extends SelectKitComponent {
+ singleSelect = true;
- selectKitOptions: {
- headerComponent: "select-kit/single-select-header",
- },
+ @computed("value", "content.[]", "selectKit.noneItem")
+ get selectedContent() {
+ if (!isEmpty(this.value)) {
+ let content;
- selectedContent: computed(
- "value",
- "content.[]",
- "selectKit.noneItem",
- function () {
- if (!isEmpty(this.value)) {
- let content;
+ const value =
+ this.selectKit.options.castInteger && this._isNumeric(this.value)
+ ? Number(this.value)
+ : this.value;
- const value =
- this.selectKit.options.castInteger && this._isNumeric(this.value)
- ? Number(this.value)
- : this.value;
+ if (this.selectKit.valueProperty) {
+ content = (this.content || []).findBy(
+ this.selectKit.valueProperty,
+ value
+ );
- if (this.selectKit.valueProperty) {
- content = (this.content || []).findBy(
- this.selectKit.valueProperty,
- value
- );
-
- return this.selectKit.modifySelection(
- content || this.defaultItem(value, value)
- );
- } else {
- return this.selectKit.modifySelection(
- (this.content || []).filter((c) => c === value)
- );
- }
+ return this.selectKit.modifySelection(
+ content || this.defaultItem(value, value)
+ );
} else {
- return this.selectKit.noneItem;
+ return this.selectKit.modifySelection(
+ (this.content || []).filter((c) => c === value)
+ );
}
+ } else {
+ return this.selectKit.noneItem;
}
- ),
-});
+ }
+}
diff --git a/app/assets/javascripts/select-kit/addon/mixins/plugin-api.js b/app/assets/javascripts/select-kit/addon/mixins/plugin-api.js
index f206221bdf0..34e797ac9bf 100644
--- a/app/assets/javascripts/select-kit/addon/mixins/plugin-api.js
+++ b/app/assets/javascripts/select-kit/addon/mixins/plugin-api.js
@@ -1,4 +1,3 @@
-import Mixin from "@ember/object/mixin";
import { isNone } from "@ember/utils";
import { makeArray } from "discourse-common/lib/helpers";
@@ -97,9 +96,3 @@ export function clearCallbacks() {
_onChangeCallbacks = {};
_replaceContentCallbacks = {};
}
-
-const EMPTY_ARRAY = Object.freeze([]);
-export default Mixin.create({
- concatenatedProperties: ["pluginApiIdentifiers"],
- pluginApiIdentifiers: EMPTY_ARRAY,
-});