discourse/app/assets/javascripts/select-kit/mixins/plugin-api.js
Joffrey JAFFEUX c99ecba68f
DEV: improves sk api (#9653)
- reduces the API to 3 actions for now: appendContent/prependContent/onChange
- well tested
- removes all previous APIS which were only half supported or too dangerous as they could collide with other plugins or core behaviors
- this plugins also puts every sk test helpers in one file
2020-05-06 17:16:20 +02:00

79 lines
2.4 KiB
JavaScript

import Mixin from "@ember/object/mixin";
import { isNone } from "@ember/utils";
import { makeArray } from "discourse-common/lib/helpers";
let _appendContentCallbacks = {};
function appendContent(pluginApiIdentifiers, contentFunction) {
if (isNone(_appendContentCallbacks[pluginApiIdentifiers])) {
_appendContentCallbacks[pluginApiIdentifiers] = [];
}
_appendContentCallbacks[pluginApiIdentifiers].push(contentFunction);
}
let _prependContentCallbacks = {};
function prependContent(targetedIdentifier, contentFunction) {
if (isNone(_prependContentCallbacks[targetedIdentifier])) {
_prependContentCallbacks[targetedIdentifier] = [];
}
_prependContentCallbacks[targetedIdentifier].push(contentFunction);
}
let _onChangeCallbacks = {};
function onChange(pluginApiIdentifiers, mutationFunction) {
if (isNone(_onChangeCallbacks[pluginApiIdentifiers])) {
_onChangeCallbacks[pluginApiIdentifiers] = [];
}
_onChangeCallbacks[pluginApiIdentifiers].push(mutationFunction);
}
export function applyContentPluginApiCallbacks(content, component) {
makeArray(component.pluginApiIdentifiers).forEach(key => {
(_prependContentCallbacks[key] || []).forEach(c => {
content = makeArray(c(component, content)).concat(content);
});
(_appendContentCallbacks[key] || []).forEach(c => {
content = content.concat(makeArray(c(component, content)));
});
});
return content;
}
export function applyOnChangePluginApiCallbacks(value, items, component) {
makeArray(component.pluginApiIdentifiers).forEach(key => {
(_onChangeCallbacks[key] || []).forEach(c => c(component, value, items));
});
}
export function modifySelectKit(targetedIdentifier) {
return {
appendContent: callback => {
appendContent(targetedIdentifier, callback);
return modifySelectKit(targetedIdentifier);
},
prependContent: callback => {
prependContent(targetedIdentifier, callback);
return modifySelectKit(targetedIdentifier);
},
onChange: callback => {
onChange(targetedIdentifier, callback);
return modifySelectKit(targetedIdentifier);
}
};
}
export function clearCallbacks() {
_appendContentCallbacks = {};
_prependContentCallbacks = {};
_onChangeCallbacks = {};
}
const EMPTY_ARRAY = Object.freeze([]);
export default Mixin.create({
concatenatedProperties: ["pluginApiIdentifiers"],
pluginApiIdentifiers: EMPTY_ARRAY
});