@nent/core
Version:
90 lines (86 loc) • 3.13 kB
JavaScript
/*!
* NENT 2022
*/
;
const index = require('./index-637e8c28.js');
const logging = require('./logging-37c154cf.js');
const state = require('./state-f97ff0e6.js');
/***
It provides a method to get an action object from an action element, and a method to send that
action object to the action bus
***/
class ActionService {
constructor(element, elementName) {
this.element = element;
this.elementName = elementName;
}
/**
* It takes the data from the form, resolves any tokens, and returns an event action
* @returns An object with a topic, command, and data property.
*/
async getAction() {
if (!this.element.topic) {
logging.warn(`${this.elementName}: unable to fire action, missing topic`);
return null;
}
if (!this.element.command) {
logging.warn(`${this.elementName}: unable to fire action, missing command`);
return null;
}
let data = Object.assign({}, this.element.el.dataset);
if (this.element.childScript) {
Object.assign(data, JSON.parse(this.element.childScript.textContent || '{}'));
}
this.element.valid = true;
this.element.childInputs.forEach((el, index) => {
var _a, _b;
if (((_a = el.checkValidity) === null || _a === void 0 ? void 0 : _a.call(el)) === false) {
(_b = el.reportValidity) === null || _b === void 0 ? void 0 : _b.call(el);
this.element.valid = false;
}
else {
data[el.id || el.name || index] =
el.value || (el.type == 'checkbox' ? el.checked : null);
}
});
if (!this.element.valid)
return null;
if (state.state.dataEnabled) {
if (this.element.when) {
const { evaluatePredicate } = await Promise.resolve().then(function () { return require('./expressions-531d82f5.js'); }).then(function (n) { return n.expressions; });
let predicateResult = await evaluatePredicate(this.element.when);
if (predicateResult == false) {
logging.debugIf(state.state.debug, `${this.elementName}: not fired, predicate '${this.element.when}' evaluated to false`);
return null;
}
}
const { hasToken, resolveTokens } = await Promise.resolve().then(function () { return require('./tokens-4f8bcd42.js'); });
// resolve token values
await Promise.all(Object.keys(data).map(async (key) => {
const value = data[key];
if (typeof value == 'string' && hasToken(value)) {
data[key] = await resolveTokens(value);
}
}));
}
return {
topic: this.element.topic,
command: this.element.command,
data,
};
}
/**
* It gets the action from the element, if it exists, and if the element is valid, it emits the
* action on the action bus
* @param [data] - An object containing data to be sent with the action.
*/
async sendAction(data) {
const action = await this.element.getAction();
if (action && this.element.valid) {
if (data)
Object.assign(action.data, data);
index.actionBus.emit(action.topic, action);
}
}
}
exports.ActionService = ActionService;