angular2-query-builder
Version:
A modernized Angular 2+ query builder based on jquery QueryBuilder
1,117 lines (1,081 loc) • 68.6 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/forms'), require('@angular/core'), require('@angular/common')) :
typeof define === 'function' && define.amd ? define('angular2-query-builder', ['exports', '@angular/forms', '@angular/core', '@angular/common'], factory) :
(global = global || self, factory(global['angular2-query-builder'] = {}, global.ng.forms, global.ng.core, global.ng.common));
}(this, (function (exports, forms, core, common) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
var QueryOperatorDirective = /** @class */ (function () {
function QueryOperatorDirective(template) {
this.template = template;
}
QueryOperatorDirective.ctorParameters = function () { return [
{ type: core.TemplateRef }
]; };
QueryOperatorDirective = __decorate([
core.Directive({ selector: '[queryOperator]' }),
__metadata("design:paramtypes", [core.TemplateRef])
], QueryOperatorDirective);
return QueryOperatorDirective;
}());
var QueryFieldDirective = /** @class */ (function () {
function QueryFieldDirective(template) {
this.template = template;
}
QueryFieldDirective.ctorParameters = function () { return [
{ type: core.TemplateRef }
]; };
QueryFieldDirective = __decorate([
core.Directive({ selector: '[queryField]' }),
__metadata("design:paramtypes", [core.TemplateRef])
], QueryFieldDirective);
return QueryFieldDirective;
}());
var QueryEntityDirective = /** @class */ (function () {
function QueryEntityDirective(template) {
this.template = template;
}
QueryEntityDirective.ctorParameters = function () { return [
{ type: core.TemplateRef }
]; };
QueryEntityDirective = __decorate([
core.Directive({ selector: '[queryEntity]' }),
__metadata("design:paramtypes", [core.TemplateRef])
], QueryEntityDirective);
return QueryEntityDirective;
}());
var QuerySwitchGroupDirective = /** @class */ (function () {
function QuerySwitchGroupDirective(template) {
this.template = template;
}
QuerySwitchGroupDirective.ctorParameters = function () { return [
{ type: core.TemplateRef }
]; };
QuerySwitchGroupDirective = __decorate([
core.Directive({ selector: '[querySwitchGroup]' }),
__metadata("design:paramtypes", [core.TemplateRef])
], QuerySwitchGroupDirective);
return QuerySwitchGroupDirective;
}());
var QueryButtonGroupDirective = /** @class */ (function () {
function QueryButtonGroupDirective(template) {
this.template = template;
}
QueryButtonGroupDirective.ctorParameters = function () { return [
{ type: core.TemplateRef }
]; };
QueryButtonGroupDirective = __decorate([
core.Directive({ selector: '[queryButtonGroup]' }),
__metadata("design:paramtypes", [core.TemplateRef])
], QueryButtonGroupDirective);
return QueryButtonGroupDirective;
}());
var QueryInputDirective = /** @class */ (function () {
function QueryInputDirective(template) {
this.template = template;
}
Object.defineProperty(QueryInputDirective.prototype, "queryInputType", {
/** Unique name for query input type. */
get: function () { return this._type; },
set: function (value) {
// If the directive is set without a type (updated programatically), then this setter will
// trigger with an empty string and should not overwrite the programatically set value.
if (!value) {
return;
}
this._type = value;
},
enumerable: true,
configurable: true
});
QueryInputDirective.ctorParameters = function () { return [
{ type: core.TemplateRef }
]; };
__decorate([
core.Input(),
__metadata("design:type", String),
__metadata("design:paramtypes", [String])
], QueryInputDirective.prototype, "queryInputType", null);
QueryInputDirective = __decorate([
core.Directive({ selector: '[queryInput]' }),
__metadata("design:paramtypes", [core.TemplateRef])
], QueryInputDirective);
return QueryInputDirective;
}());
var QueryRemoveButtonDirective = /** @class */ (function () {
function QueryRemoveButtonDirective(template) {
this.template = template;
}
QueryRemoveButtonDirective.ctorParameters = function () { return [
{ type: core.TemplateRef }
]; };
QueryRemoveButtonDirective = __decorate([
core.Directive({ selector: '[queryRemoveButton]' }),
__metadata("design:paramtypes", [core.TemplateRef])
], QueryRemoveButtonDirective);
return QueryRemoveButtonDirective;
}());
var QueryEmptyWarningDirective = /** @class */ (function () {
function QueryEmptyWarningDirective(template) {
this.template = template;
}
QueryEmptyWarningDirective.ctorParameters = function () { return [
{ type: core.TemplateRef }
]; };
QueryEmptyWarningDirective = __decorate([
core.Directive({ selector: '[queryEmptyWarning]' }),
__metadata("design:paramtypes", [core.TemplateRef])
], QueryEmptyWarningDirective);
return QueryEmptyWarningDirective;
}());
var QueryArrowIconDirective = /** @class */ (function () {
function QueryArrowIconDirective(template) {
this.template = template;
}
QueryArrowIconDirective.ctorParameters = function () { return [
{ type: core.TemplateRef }
]; };
QueryArrowIconDirective = __decorate([
core.Directive({ selector: '[queryArrowIcon]' }),
__metadata("design:paramtypes", [core.TemplateRef])
], QueryArrowIconDirective);
return QueryArrowIconDirective;
}());
var CONTROL_VALUE_ACCESSOR = {
provide: forms.NG_VALUE_ACCESSOR,
useExisting: core.forwardRef(function () { return QueryBuilderComponent; }),
multi: true
};
var VALIDATOR = {
provide: forms.NG_VALIDATORS,
useExisting: core.forwardRef(function () { return QueryBuilderComponent; }),
multi: true
};
var QueryBuilderComponent = /** @class */ (function () {
function QueryBuilderComponent(changeDetectorRef) {
var _this = this;
this.changeDetectorRef = changeDetectorRef;
this.defaultClassNames = {
arrowIconButton: 'q-arrow-icon-button',
arrowIcon: 'q-icon q-arrow-icon',
removeIcon: 'q-icon q-remove-icon',
addIcon: 'q-icon q-add-icon',
button: 'q-button',
buttonGroup: 'q-button-group',
removeButton: 'q-remove-button',
switchGroup: 'q-switch-group',
switchLabel: 'q-switch-label',
switchRadio: 'q-switch-radio',
rightAlign: 'q-right-align',
transition: 'q-transition',
collapsed: 'q-collapsed',
treeContainer: 'q-tree-container',
tree: 'q-tree',
row: 'q-row',
connector: 'q-connector',
rule: 'q-rule',
ruleSet: 'q-ruleset',
invalidRuleSet: 'q-invalid-ruleset',
emptyWarning: 'q-empty-warning',
fieldControl: 'q-field-control',
fieldControlSize: 'q-control-size',
entityControl: 'q-entity-control',
entityControlSize: 'q-control-size',
operatorControl: 'q-operator-control',
operatorControlSize: 'q-control-size',
inputControl: 'q-input-control',
inputControlSize: 'q-control-size'
};
this.defaultOperatorMap = {
string: ['=', '!=', 'contains', 'like'],
number: ['=', '!=', '>', '>=', '<', '<='],
time: ['=', '!=', '>', '>=', '<', '<='],
date: ['=', '!=', '>', '>=', '<', '<='],
category: ['=', '!=', 'in', 'not in'],
boolean: ['=']
};
this.data = { condition: 'and', rules: [] };
this.allowRuleset = true;
this.allowCollapse = false;
this.emptyMessage = 'A ruleset cannot be empty. Please add a rule or remove it all together.';
this.config = { fields: {} };
this.persistValueOnFieldChange = false;
this.defaultTemplateTypes = [
'string', 'number', 'time', 'date', 'category', 'boolean', 'multiselect'
];
this.defaultPersistValueTypes = [
'string', 'number', 'time', 'date', 'boolean'
];
this.defaultEmptyList = [];
this.inputContextCache = new Map();
this.operatorContextCache = new Map();
this.fieldContextCache = new Map();
this.entityContextCache = new Map();
this.removeButtonContextCache = new Map();
// ----------END----------
this.getDisabledState = function () {
return _this.disabled;
};
}
// ----------OnInit Implementation----------
QueryBuilderComponent.prototype.ngOnInit = function () { };
// ----------OnChanges Implementation----------
QueryBuilderComponent.prototype.ngOnChanges = function (changes) {
var config = this.config;
var type = typeof config;
if (type === 'object') {
this.fields = Object.keys(config.fields).map(function (value) {
var field = config.fields[value];
field.value = field.value || value;
return field;
});
if (config.entities) {
this.entities = Object.keys(config.entities).map(function (value) {
var entity = config.entities[value];
entity.value = entity.value || value;
return entity;
});
}
else {
this.entities = null;
}
this.operatorsCache = {};
}
else {
throw new Error("Expected 'config' must be a valid object, got " + type + " instead.");
}
};
// ----------Validator Implementation----------
QueryBuilderComponent.prototype.validate = function (control) {
var errors = {};
var ruleErrorStore = [];
var hasErrors = false;
if (!this.config.allowEmptyRulesets && this.checkEmptyRuleInRuleset(this.data)) {
errors.empty = 'Empty rulesets are not allowed.';
hasErrors = true;
}
this.validateRulesInRuleset(this.data, ruleErrorStore);
if (ruleErrorStore.length) {
errors.rules = ruleErrorStore;
hasErrors = true;
}
return hasErrors ? errors : null;
};
Object.defineProperty(QueryBuilderComponent.prototype, "value", {
// ----------ControlValueAccessor Implementation----------
get: function () {
return this.data;
},
set: function (value) {
// When component is initialized without a formControl, null is passed to value
this.data = value || { condition: 'and', rules: [] };
this.handleDataChange();
},
enumerable: true,
configurable: true
});
QueryBuilderComponent.prototype.writeValue = function (obj) {
this.value = obj;
};
QueryBuilderComponent.prototype.registerOnChange = function (fn) {
var _this = this;
this.onChangeCallback = function () { return fn(_this.data); };
};
QueryBuilderComponent.prototype.registerOnTouched = function (fn) {
var _this = this;
this.onTouchedCallback = function () { return fn(_this.data); };
};
QueryBuilderComponent.prototype.setDisabledState = function (isDisabled) {
this.disabled = isDisabled;
this.changeDetectorRef.detectChanges();
};
QueryBuilderComponent.prototype.findTemplateForRule = function (rule) {
var type = this.getInputType(rule.field, rule.operator);
if (type) {
var queryInput = this.findQueryInput(type);
if (queryInput) {
return queryInput.template;
}
else {
if (this.defaultTemplateTypes.indexOf(type) === -1) {
console.warn("Could not find template for field with type: " + type);
}
return null;
}
}
};
QueryBuilderComponent.prototype.findQueryInput = function (type) {
var templates = this.parentInputTemplates || this.inputTemplates;
return templates.find(function (item) { return item.queryInputType === type; });
};
QueryBuilderComponent.prototype.getOperators = function (field) {
if (this.operatorsCache[field]) {
return this.operatorsCache[field];
}
var operators = this.defaultEmptyList;
var fieldObject = this.config.fields[field];
if (this.config.getOperators) {
return this.config.getOperators(field, fieldObject);
}
var type = fieldObject.type;
if (fieldObject && fieldObject.operators) {
operators = fieldObject.operators;
}
else if (type) {
operators = (this.operatorMap && this.operatorMap[type]) || this.defaultOperatorMap[type] || this.defaultEmptyList;
if (operators.length === 0) {
console.warn("No operators found for field '" + field + "' with type " + fieldObject.type + ". " +
"Please define an 'operators' property on the field or use the 'operatorMap' binding to fix this.");
}
if (fieldObject.nullable) {
operators = operators.concat(['is null', 'is not null']);
}
}
else {
console.warn("No 'type' property found on field: '" + field + "'");
}
// Cache reference to array object, so it won't be computed next time and trigger a rerender.
this.operatorsCache[field] = operators;
return operators;
};
QueryBuilderComponent.prototype.getFields = function (entity) {
if (this.entities && entity) {
return this.fields.filter(function (field) {
return field && field.entity === entity;
});
}
else {
return this.fields;
}
};
QueryBuilderComponent.prototype.getInputType = function (field, operator) {
if (this.config.getInputType) {
return this.config.getInputType(field, operator);
}
if (!this.config.fields[field]) {
throw new Error("No configuration for field '" + field + "' could be found! Please add it to config.fields.");
}
var type = this.config.fields[field].type;
switch (operator) {
case 'is null':
case 'is not null':
return null; // No displayed component
case 'in':
case 'not in':
return type === 'category' || type === 'boolean' ? 'multiselect' : type;
default:
return type;
}
};
QueryBuilderComponent.prototype.getOptions = function (field) {
if (this.config.getOptions) {
return this.config.getOptions(field);
}
return this.config.fields[field].options || this.defaultEmptyList;
};
QueryBuilderComponent.prototype.getClassNames = function () {
var _this = this;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var clsLookup = this.classNames ? this.classNames : this.defaultClassNames;
var classNames = args.map(function (id) { return clsLookup[id] || _this.defaultClassNames[id]; }).filter(function (c) { return !!c; });
return classNames.length ? classNames.join(' ') : null;
};
QueryBuilderComponent.prototype.getDefaultField = function (entity) {
if (!entity) {
return null;
}
else if (entity.defaultField !== undefined) {
return this.getDefaultValue(entity.defaultField);
}
else {
var entityFields = this.fields.filter(function (field) {
return field && field.entity === entity.value;
});
if (entityFields && entityFields.length) {
return entityFields[0];
}
else {
console.warn("No fields found for entity '" + entity.name + "'. " +
"A 'defaultOperator' is also not specified on the field config. Operator value will default to null.");
return null;
}
}
};
QueryBuilderComponent.prototype.getDefaultOperator = function (field) {
if (field && field.defaultOperator !== undefined) {
return this.getDefaultValue(field.defaultOperator);
}
else {
var operators = this.getOperators(field.value);
if (operators && operators.length) {
return operators[0];
}
else {
console.warn("No operators found for field '" + field.value + "'. " +
"A 'defaultOperator' is also not specified on the field config. Operator value will default to null.");
return null;
}
}
};
QueryBuilderComponent.prototype.addRule = function (parent) {
if (this.disabled) {
return;
}
parent = parent || this.data;
if (this.config.addRule) {
this.config.addRule(parent);
}
else {
var field = this.fields[0];
parent.rules = parent.rules.concat([{
field: field.value,
operator: this.getDefaultOperator(field),
value: this.getDefaultValue(field.defaultValue),
entity: field.entity
}]);
}
this.handleTouched();
this.handleDataChange();
};
QueryBuilderComponent.prototype.removeRule = function (rule, parent) {
if (this.disabled) {
return;
}
parent = parent || this.data;
if (this.config.removeRule) {
this.config.removeRule(rule, parent);
}
else {
parent.rules = parent.rules.filter(function (r) { return r !== rule; });
}
this.inputContextCache.delete(rule);
this.operatorContextCache.delete(rule);
this.fieldContextCache.delete(rule);
this.entityContextCache.delete(rule);
this.removeButtonContextCache.delete(rule);
this.handleTouched();
this.handleDataChange();
};
QueryBuilderComponent.prototype.addRuleSet = function (parent) {
if (this.disabled) {
return;
}
parent = parent || this.data;
if (this.config.addRuleSet) {
this.config.addRuleSet(parent);
}
else {
parent.rules = parent.rules.concat([{ condition: 'and', rules: [] }]);
}
this.handleTouched();
this.handleDataChange();
};
QueryBuilderComponent.prototype.removeRuleSet = function (ruleset, parent) {
if (this.disabled) {
return;
}
ruleset = ruleset || this.data;
parent = parent || this.parentValue;
if (this.config.removeRuleSet) {
this.config.removeRuleSet(ruleset, parent);
}
else {
parent.rules = parent.rules.filter(function (r) { return r !== ruleset; });
}
this.handleTouched();
this.handleDataChange();
};
QueryBuilderComponent.prototype.transitionEnd = function (e) {
this.treeContainer.nativeElement.style.maxHeight = null;
};
QueryBuilderComponent.prototype.toggleCollapse = function () {
var _this = this;
this.computedTreeContainerHeight();
setTimeout(function () {
_this.data.collapsed = !_this.data.collapsed;
}, 100);
};
QueryBuilderComponent.prototype.computedTreeContainerHeight = function () {
var nativeElement = this.treeContainer.nativeElement;
if (nativeElement && nativeElement.firstElementChild) {
nativeElement.style.maxHeight = (nativeElement.firstElementChild.clientHeight + 8) + 'px';
}
};
QueryBuilderComponent.prototype.changeCondition = function (value) {
if (this.disabled) {
return;
}
this.data.condition = value;
this.handleTouched();
this.handleDataChange();
};
QueryBuilderComponent.prototype.changeOperator = function (rule) {
if (this.disabled) {
return;
}
if (this.config.coerceValueForOperator) {
rule.value = this.config.coerceValueForOperator(rule.operator, rule.value, rule);
}
else {
rule.value = this.coerceValueForOperator(rule.operator, rule.value, rule);
}
this.handleTouched();
this.handleDataChange();
};
QueryBuilderComponent.prototype.coerceValueForOperator = function (operator, value, rule) {
var inputType = this.getInputType(rule.field, operator);
if (inputType === 'multiselect' && !Array.isArray(value)) {
return [value];
}
return value;
};
QueryBuilderComponent.prototype.changeInput = function () {
if (this.disabled) {
return;
}
this.handleTouched();
this.handleDataChange();
};
QueryBuilderComponent.prototype.changeField = function (fieldValue, rule) {
if (this.disabled) {
return;
}
var inputContext = this.inputContextCache.get(rule);
var currentField = inputContext && inputContext.field;
var nextField = this.config.fields[fieldValue];
var nextValue = this.calculateFieldChangeValue(currentField, nextField, rule.value);
if (nextValue !== undefined) {
rule.value = nextValue;
}
else {
delete rule.value;
}
rule.operator = this.getDefaultOperator(nextField);
// Create new context objects so templates will automatically update
this.inputContextCache.delete(rule);
this.operatorContextCache.delete(rule);
this.fieldContextCache.delete(rule);
this.entityContextCache.delete(rule);
this.getInputContext(rule);
this.getFieldContext(rule);
this.getOperatorContext(rule);
this.getEntityContext(rule);
this.handleTouched();
this.handleDataChange();
};
QueryBuilderComponent.prototype.changeEntity = function (entityValue, rule, index, data) {
if (this.disabled) {
return;
}
var i = index;
var rs = data;
var entity = this.entities.find(function (e) { return e.value === entityValue; });
var defaultField = this.getDefaultField(entity);
if (!rs) {
rs = this.data;
i = rs.rules.findIndex(function (x) { return x === rule; });
}
rule.field = defaultField.value;
rs.rules[i] = rule;
if (defaultField) {
this.changeField(defaultField.value, rule);
}
else {
this.handleTouched();
this.handleDataChange();
}
};
QueryBuilderComponent.prototype.getDefaultValue = function (defaultValue) {
switch (typeof defaultValue) {
case 'function':
return defaultValue();
default:
return defaultValue;
}
};
QueryBuilderComponent.prototype.getOperatorTemplate = function () {
var t = this.parentOperatorTemplate || this.operatorTemplate;
return t ? t.template : null;
};
QueryBuilderComponent.prototype.getFieldTemplate = function () {
var t = this.parentFieldTemplate || this.fieldTemplate;
return t ? t.template : null;
};
QueryBuilderComponent.prototype.getEntityTemplate = function () {
var t = this.parentEntityTemplate || this.entityTemplate;
return t ? t.template : null;
};
QueryBuilderComponent.prototype.getArrowIconTemplate = function () {
var t = this.parentArrowIconTemplate || this.arrowIconTemplate;
return t ? t.template : null;
};
QueryBuilderComponent.prototype.getButtonGroupTemplate = function () {
var t = this.parentButtonGroupTemplate || this.buttonGroupTemplate;
return t ? t.template : null;
};
QueryBuilderComponent.prototype.getSwitchGroupTemplate = function () {
var t = this.parentSwitchGroupTemplate || this.switchGroupTemplate;
return t ? t.template : null;
};
QueryBuilderComponent.prototype.getRemoveButtonTemplate = function () {
var t = this.parentRemoveButtonTemplate || this.removeButtonTemplate;
return t ? t.template : null;
};
QueryBuilderComponent.prototype.getEmptyWarningTemplate = function () {
var t = this.parentEmptyWarningTemplate || this.emptyWarningTemplate;
return t ? t.template : null;
};
QueryBuilderComponent.prototype.getQueryItemClassName = function (local) {
var cls = this.getClassNames('row', 'connector', 'transition');
cls += ' ' + this.getClassNames(local.ruleset ? 'ruleSet' : 'rule');
if (local.invalid) {
cls += ' ' + this.getClassNames('invalidRuleSet');
}
return cls;
};
QueryBuilderComponent.prototype.getButtonGroupContext = function () {
if (!this.buttonGroupContext) {
this.buttonGroupContext = {
addRule: this.addRule.bind(this),
addRuleSet: this.allowRuleset && this.addRuleSet.bind(this),
removeRuleSet: this.allowRuleset && this.parentValue && this.removeRuleSet.bind(this),
getDisabledState: this.getDisabledState,
$implicit: this.data
};
}
return this.buttonGroupContext;
};
QueryBuilderComponent.prototype.getRemoveButtonContext = function (rule) {
if (!this.removeButtonContextCache.has(rule)) {
this.removeButtonContextCache.set(rule, {
removeRule: this.removeRule.bind(this),
getDisabledState: this.getDisabledState,
$implicit: rule
});
}
return this.removeButtonContextCache.get(rule);
};
QueryBuilderComponent.prototype.getFieldContext = function (rule) {
if (!this.fieldContextCache.has(rule)) {
this.fieldContextCache.set(rule, {
onChange: this.changeField.bind(this),
getFields: this.getFields.bind(this),
getDisabledState: this.getDisabledState,
fields: this.fields,
$implicit: rule
});
}
return this.fieldContextCache.get(rule);
};
QueryBuilderComponent.prototype.getEntityContext = function (rule) {
if (!this.entityContextCache.has(rule)) {
this.entityContextCache.set(rule, {
onChange: this.changeEntity.bind(this),
getDisabledState: this.getDisabledState,
entities: this.entities,
$implicit: rule
});
}
return this.entityContextCache.get(rule);
};
QueryBuilderComponent.prototype.getSwitchGroupContext = function () {
return {
onChange: this.changeCondition.bind(this),
getDisabledState: this.getDisabledState,
$implicit: this.data
};
};
QueryBuilderComponent.prototype.getArrowIconContext = function () {
return {
getDisabledState: this.getDisabledState,
$implicit: this.data
};
};
QueryBuilderComponent.prototype.getEmptyWarningContext = function () {
return {
getDisabledState: this.getDisabledState,
message: this.emptyMessage,
$implicit: this.data
};
};
QueryBuilderComponent.prototype.getOperatorContext = function (rule) {
if (!this.operatorContextCache.has(rule)) {
this.operatorContextCache.set(rule, {
onChange: this.changeOperator.bind(this),
getDisabledState: this.getDisabledState,
operators: this.getOperators(rule.field),
$implicit: rule
});
}
return this.operatorContextCache.get(rule);
};
QueryBuilderComponent.prototype.getInputContext = function (rule) {
if (!this.inputContextCache.has(rule)) {
this.inputContextCache.set(rule, {
onChange: this.changeInput.bind(this),
getDisabledState: this.getDisabledState,
options: this.getOptions(rule.field),
field: this.config.fields[rule.field],
$implicit: rule
});
}
return this.inputContextCache.get(rule);
};
QueryBuilderComponent.prototype.calculateFieldChangeValue = function (currentField, nextField, currentValue) {
var _this = this;
if (this.config.calculateFieldChangeValue != null) {
return this.config.calculateFieldChangeValue(currentField, nextField, currentValue);
}
var canKeepValue = function () {
if (currentField == null || nextField == null) {
return false;
}
return currentField.type === nextField.type
&& _this.defaultPersistValueTypes.indexOf(currentField.type) !== -1;
};
if (this.persistValueOnFieldChange && canKeepValue()) {
return currentValue;
}
if (nextField && nextField.defaultValue !== undefined) {
return this.getDefaultValue(nextField.defaultValue);
}
return undefined;
};
QueryBuilderComponent.prototype.checkEmptyRuleInRuleset = function (ruleset) {
var _this = this;
if (!ruleset || !ruleset.rules || ruleset.rules.length === 0) {
return true;
}
else {
return ruleset.rules.some(function (item) {
if (item.rules) {
return _this.checkEmptyRuleInRuleset(item);
}
else {
return false;
}
});
}
};
QueryBuilderComponent.prototype.validateRulesInRuleset = function (ruleset, errorStore) {
var _this = this;
if (ruleset && ruleset.rules && ruleset.rules.length > 0) {
ruleset.rules.forEach(function (item) {
if (item.rules) {
return _this.validateRulesInRuleset(item, errorStore);
}
else if (item.field) {
var field = _this.config.fields[item.field];
if (field && field.validator && field.validator.apply) {
var error = field.validator(item, ruleset);
if (error != null) {
errorStore.push(error);
}
}
}
});
}
};
QueryBuilderComponent.prototype.handleDataChange = function () {
this.changeDetectorRef.markForCheck();
if (this.onChangeCallback) {
this.onChangeCallback();
}
if (this.parentChangeCallback) {
this.parentChangeCallback();
}
};
QueryBuilderComponent.prototype.handleTouched = function () {
if (this.onTouchedCallback) {
this.onTouchedCallback();
}
if (this.parentTouchedCallback) {
this.parentTouchedCallback();
}
};
QueryBuilderComponent.ctorParameters = function () { return [
{ type: core.ChangeDetectorRef }
]; };
__decorate([
core.Input(),
__metadata("design:type", Boolean)
], QueryBuilderComponent.prototype, "disabled", void 0);
__decorate([
core.Input(),
__metadata("design:type", Object)
], QueryBuilderComponent.prototype, "data", void 0);
__decorate([
core.Input(),
__metadata("design:type", Boolean)
], QueryBuilderComponent.prototype, "allowRuleset", void 0);
__decorate([
core.Input(),
__metadata("design:type", Boolean)
], QueryBuilderComponent.prototype, "allowCollapse", void 0);
__decorate([
core.Input(),
__metadata("design:type", String)
], QueryBuilderComponent.prototype, "emptyMessage", void 0);
__decorate([
core.Input(),
__metadata("design:type", Object)
], QueryBuilderComponent.prototype, "classNames", void 0);
__decorate([
core.Input(),
__metadata("design:type", Object)
], QueryBuilderComponent.prototype, "operatorMap", void 0);
__decorate([
core.Input(),
__metadata("design:type", Object)
], QueryBuilderComponent.prototype, "parentValue", void 0);
__decorate([
core.Input(),
__metadata("design:type", Object)
], QueryBuilderComponent.prototype, "config", void 0);
__decorate([
core.Input(),
__metadata("design:type", QueryArrowIconDirective)
], QueryBuilderComponent.prototype, "parentArrowIconTemplate", void 0);
__decorate([
core.Input(),
__metadata("design:type", core.QueryList)
], QueryBuilderComponent.prototype, "parentInputTemplates", void 0);
__decorate([
core.Input(),
__metadata("design:type", QueryOperatorDirective)
], QueryBuilderComponent.prototype, "parentOperatorTemplate", void 0);
__decorate([
core.Input(),
__metadata("design:type", QueryFieldDirective)
], QueryBuilderComponent.prototype, "parentFieldTemplate", void 0);
__decorate([
core.Input(),
__metadata("design:type", QueryEntityDirective)
], QueryBuilderComponent.prototype, "parentEntityTemplate", void 0);
__decorate([
core.Input(),
__metadata("design:type", QuerySwitchGroupDirective)
], QueryBuilderComponent.prototype, "parentSwitchGroupTemplate", void 0);
__decorate([
core.Input(),
__metadata("design:type", QueryButtonGroupDirective)
], QueryBuilderComponent.prototype, "parentButtonGroupTemplate", void 0);
__decorate([
core.Input(),
__metadata("design:type", QueryRemoveButtonDirective)
], QueryBuilderComponent.prototype, "parentRemoveButtonTemplate", void 0);
__decorate([
core.Input(),
__metadata("design:type", QueryEmptyWarningDirective)
], QueryBuilderComponent.prototype, "parentEmptyWarningTemplate", void 0);
__decorate([
core.Input(),
__metadata("design:type", Function)
], QueryBuilderComponent.prototype, "parentChangeCallback", void 0);
__decorate([
core.Input(),
__metadata("design:type", Function)
], QueryBuilderComponent.prototype, "parentTouchedCallback", void 0);
__decorate([
core.Input(),
__metadata("design:type", Boolean)
], QueryBuilderComponent.prototype, "persistValueOnFieldChange", void 0);
__decorate([
core.ViewChild('treeContainer', { static: true }),
__metadata("design:type", core.ElementRef)
], QueryBuilderComponent.prototype, "treeContainer", void 0);
__decorate([
core.ContentChild(QueryButtonGroupDirective),
__metadata("design:type", QueryButtonGroupDirective)
], QueryBuilderComponent.prototype, "buttonGroupTemplate", void 0);
__decorate([
core.ContentChild(QuerySwitch