/**
* @ag-grid-community/all-modules - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v22.1.1
* @link http://www.ag-grid.com/
' * @license MIT
*/
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var Color = /** @class */ (function () {
/**
* Every color component should be in the [0, 1] range.
* Some easing functions (such as elastic easing) can overshoot the target value by some amount.
* So, when animating colors, if the source or target color components are already near
* or at the edge of the allowed [0, 1] range, it is possible for the intermediate color
* component value to end up outside of that range mid-animation. For this reason the constructor
* performs range checking/constraining.
* @param r Red component.
* @param g Green component.
* @param b Blue component.
* @param a Alpha (opacity) component.
*/
function Color(r, g, b, a) {
if (a === void 0) { a = 1; }
// NaN is treated as 0.
this.r = Math.min(1, Math.max(0, r || 0));
this.g = Math.min(1, Math.max(0, g || 0));
this.b = Math.min(1, Math.max(0, b || 0));
this.a = Math.min(1, Math.max(0, a || 0));
}
/**
* The given string can be in one of the following formats:
* - #rgb
* - #rrggbb
* - rgb(r, g, b)
* - rgba(r, g, b, a)
* - CSS color name such as 'white', 'orange', 'cyan', etc.
* @param str
*/
Color.fromString = function (str) {
// hexadecimal notation
if (str.indexOf('#') >= 0) { // there can be some leading whitespace
return Color.fromHexString(str);
}
// color name
var hex = Color.nameToHex[str];
if (hex) {
return Color.fromHexString(hex);
}
// rgb(a) notation
if (str.indexOf('rgb') >= 0) {
return Color.fromRgbaString(str);
}
throw new Error("Invalid color string: '" + str + "'");
};
// Using separate RegExp for the short hex notation because strings like `#abcd`
// are matched as ['#abcd', 'ab', 'c', 'd', undefined] when the `{1,2}` quantifier is used.
Color.fromHexString = function (str) {
var values = str.match(Color.hexRe);
if (values) {
var r = parseInt(values[1], 16);
var g = parseInt(values[2], 16);
var b = parseInt(values[3], 16);
var a = values[4] !== undefined ? parseInt(values[4], 16) : 255;
return new Color(r / 255, g / 255, b / 255, a / 255);
}
values = str.match(Color.shortHexRe);
if (values) {
var r = parseInt(values[1], 16);
var g = parseInt(values[2], 16);
var b = parseInt(values[3], 16);
var a = values[4] !== undefined ? parseInt(values[4], 16) : 15;
r += r * 16;
g += g * 16;
b += b * 16;
a += a * 16;
return new Color(r / 255, g / 255, b / 255, a / 255);
}
throw new Error("Malformed hexadecimal color string: '" + str + "'");
};
Color.fromRgbaString = function (str) {
var values = str.match(Color.rgbRe);
if (values) {
return new Color(+values[1] / 255, +values[2] / 255, +values[3] / 255);
}
values = str.match(Color.rgbaRe);
if (values) {
return new Color(+values[1] / 255, +values[2] / 255, +values[3] / 255, +values[4]);
}
throw new Error("Malformed rgb/rgba color string: '" + str + "'");
};
Color.fromArray = function (arr) {
if (arr.length === 4) {
return new Color(arr[0], arr[1], arr[2], arr[3]);
}
if (arr.length === 3) {
return new Color(arr[0], arr[1], arr[2]);
}
throw new Error('The given array should contain 3 or 4 color components (numbers).');
};
/**
* Creates an instance of the Color class from the given HSB(A) components.
* @param h Hue in the [0, 360) range.
* @param s Saturation in the [0, 1] range.
* @param b Brightness in the [0, 1] range.
* @param alpha Opacity in the [0, 1] range. Defaults to 1 (completely opaque).
*/
Color.fromHSB = function (h, s, b, alpha) {
if (alpha === void 0) { alpha = 1; }
var rgb = Color.HSBtoRGB(h, s, b);
return new Color(rgb[0], rgb[1], rgb[2], alpha);
};
Color.padHex = function (str) {
// Can't use `padStart(2, '0')` here because of IE.
return str.length === 1 ? '0' + str : str;
};
Color.prototype.toHexString = function () {
var hex = '#'
+ Color.padHex(Math.round(this.r * 255).toString(16))
+ Color.padHex(Math.round(this.g * 255).toString(16))
+ Color.padHex(Math.round(this.b * 255).toString(16));
if (this.a < 1) {
hex += Color.padHex(Math.round(this.a * 255).toString(16));
}
return hex;
};
Color.prototype.toRgbaString = function (fractionDigits) {
if (fractionDigits === void 0) { fractionDigits = 3; }
var components = [
Math.round(this.r * 255),
Math.round(this.g * 255),
Math.round(this.b * 255)
];
var k = Math.pow(10, fractionDigits);
if (this.a !== 1) {
components.push(Math.round(this.a * k) / k);
return "rgba(" + components.join(', ') + ")";
}
return "rgb(" + components.join(', ') + ")";
};
Color.prototype.toString = function () {
if (this.a === 1) {
return this.toHexString();
}
return this.toRgbaString();
};
Color.prototype.toHSB = function () {
return Color.RGBtoHSB(this.r, this.g, this.b);
};
/**
* Converts the given RGB triple to an array of HSB (HSV) components.
* The hue component will be `NaN` for achromatic colors.
*/
Color.RGBtoHSB = function (r, g, b) {
var min = Math.min(r, g, b);
var max = Math.max(r, g, b);
var S = max !== 0 ? (max - min) / max : 0;
var H = NaN;
// min == max, means all components are the same
// and the color is a shade of gray with no hue (H is NaN)
if (min !== max) {
var delta = max - min;
var rc = (max - r) / delta;
var gc = (max - g) / delta;
var bc = (max - b) / delta;
if (r === max) {
H = bc - gc;
}
else if (g === max) {
H = 2.0 + rc - bc;
}
else {
H = 4.0 + gc - rc;
}
H /= 6.0;
if (H < 0) {
H = H + 1.0;
}
}
return [H * 360, S, max];
};
/**
* Converts the given HSB (HSV) triple to an array of RGB components.
*/
Color.HSBtoRGB = function (H, S, B) {
if (isNaN(H)) {
H = 0;
}
H = (((H % 360) + 360) % 360) / 360; // normalize hue to [0, 360] interval, then scale to [0, 1]
var r = 0;
var g = 0;
var b = 0;
if (S === 0) {
r = g = b = B;
}
else {
var h = (H - Math.floor(H)) * 6;
var f = h - Math.floor(h);
var p = B * (1 - S);
var q = B * (1 - S * f);
var t = B * (1 - (S * (1 - f)));
switch (h >> 0) { // discard the floating point part of the number
case 0:
r = B;
g = t;
b = p;
break;
case 1:
r = q;
g = B;
b = p;
break;
case 2:
r = p;
g = B;
b = t;
break;
case 3:
r = p;
g = q;
b = B;
break;
case 4:
r = t;
g = p;
b = B;
break;
case 5:
r = B;
g = p;
b = q;
break;
}
}
return [r, g, b];
};
Color.prototype.derive = function (hueShift, saturationFactor, brightnessFactor, opacityFactor) {
var hsb = Color.RGBtoHSB(this.r, this.g, this.b);
var b = hsb[2];
if (b == 0 && brightnessFactor > 1.0) {
b = 0.05;
}
var h = (((hsb[0] + hueShift) % 360) + 360) % 360;
var s = Math.max(Math.min(hsb[1] * saturationFactor, 1.0), 0.0);
b = Math.max(Math.min(b * brightnessFactor, 1.0), 0.0);
var a = Math.max(Math.min(this.a * opacityFactor, 1.0), 0.0);
var rgba = Color.HSBtoRGB(h, s, b);
rgba.push(a);
return Color.fromArray(rgba);
};
Color.prototype.brighter = function () {
return this.derive(0, 1.0, 1.0 / 0.7, 1.0);
};
Color.prototype.darker = function () {
return this.derive(0, 1.0, 0.7, 1.0);
};
// See https://drafts.csswg.org/css-color/#hex-notation
Color.hexRe = /\s*#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})?\s*$/;
Color.shortHexRe = /\s*#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])?\s*$/;
Color.rgbRe = /\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)\s*/;
Color.rgbaRe = /\s*rgba\((\d+),\s*(\d+),\s*(\d+),\s*([.\d]+)\)\s*/;
/**
* CSS Color Module Level 4:
* https://drafts.csswg.org/css-color/#named-colors
*/
Color.nameToHex = Object.freeze({
aliceblue: '#F0F8FF',
antiquewhite: '#FAEBD7',
aqua: '#00FFFF',
aquamarine: '#7FFFD4',
azure: '#F0FFFF',
beige: '#F5F5DC',
bisque: '#FFE4C4',
black: '#000000',
blanchedalmond: '#FFEBCD',
blue: '#0000FF',
blueviolet: '#8A2BE2',
brown: '#A52A2A',
burlywood: '#DEB887',
cadetblue: '#5F9EA0',
chartreuse: '#7FFF00',
chocolate: '#D2691E',
coral: '#FF7F50',
cornflowerblue: '#6495ED',
cornsilk: '#FFF8DC',
crimson: '#DC143C',
cyan: '#00FFFF',
darkblue: '#00008B',
darkcyan: '#008B8B',
darkgoldenrod: '#B8860B',
darkgray: '#A9A9A9',
darkgreen: '#006400',
darkgrey: '#A9A9A9',
darkkhaki: '#BDB76B',
darkmagenta: '#8B008B',
darkolivegreen: '#556B2F',
darkorange: '#FF8C00',
darkorchid: '#9932CC',
darkred: '#8B0000',
darksalmon: '#E9967A',
darkseagreen: '#8FBC8F',
darkslateblue: '#483D8B',
darkslategray: '#2F4F4F',
darkslategrey: '#2F4F4F',
darkturquoise: '#00CED1',
darkviolet: '#9400D3',
deeppink: '#FF1493',
deepskyblue: '#00BFFF',
dimgray: '#696969',
dimgrey: '#696969',
dodgerblue: '#1E90FF',
firebrick: '#B22222',
floralwhite: '#FFFAF0',
forestgreen: '#228B22',
fuchsia: '#FF00FF',
gainsboro: '#DCDCDC',
ghostwhite: '#F8F8FF',
gold: '#FFD700',
goldenrod: '#DAA520',
gray: '#808080',
green: '#008000',
greenyellow: '#ADFF2F',
grey: '#808080',
honeydew: '#F0FFF0',
hotpink: '#FF69B4',
indianred: '#CD5C5C',
indigo: '#4B0082',
ivory: '#FFFFF0',
khaki: '#F0E68C',
lavender: '#E6E6FA',
lavenderblush: '#FFF0F5',
lawngreen: '#7CFC00',
lemonchiffon: '#FFFACD',
lightblue: '#ADD8E6',
lightcoral: '#F08080',
lightcyan: '#E0FFFF',
lightgoldenrodyellow: '#FAFAD2',
lightgray: '#D3D3D3',
lightgreen: '#90EE90',
lightgrey: '#D3D3D3',
lightpink: '#FFB6C1',
lightsalmon: '#FFA07A',
lightseagreen: '#20B2AA',
lightskyblue: '#87CEFA',
lightslategray: '#778899',
lightslategrey: '#778899',
lightsteelblue: '#B0C4DE',
lightyellow: '#FFFFE0',
lime: '#00FF00',
limegreen: '#32CD32',
linen: '#FAF0E6',
magenta: '#FF00FF',
maroon: '#800000',
mediumaquamarine: '#66CDAA',
mediumblue: '#0000CD',
mediumorchid: '#BA55D3',
mediumpurple: '#9370DB',
mediumseagreen: '#3CB371',
mediumslateblue: '#7B68EE',
mediumspringgreen: '#00FA9A',
mediumturquoise: '#48D1CC',
mediumvioletred: '#C71585',
midnightblue: '#191970',
mintcream: '#F5FFFA',
mistyrose: '#FFE4E1',
moccasin: '#FFE4B5',
navajowhite: '#FFDEAD',
navy: '#000080',
oldlace: '#FDF5E6',
olive: '#808000',
olivedrab: '#6B8E23',
orange: '#FFA500',
orangered: '#FF4500',
orchid: '#DA70D6',
palegoldenrod: '#EEE8AA',
palegreen: '#98FB98',
paleturquoise: '#AFEEEE',
palevioletred: '#DB7093',
papayawhip: '#FFEFD5',
peachpuff: '#FFDAB9',
peru: '#CD853F',
pink: '#FFC0CB',
plum: '#DDA0DD',
powderblue: '#B0E0E6',
purple: '#800080',
rebeccapurple: '#663399',
red: '#FF0000',
rosybrown: '#BC8F8F',
royalblue: '#4169E1',
saddlebrown: '#8B4513',
salmon: '#FA8072',
sandybrown: '#F4A460',
seagreen: '#2E8B57',
seashell: '#FFF5EE',
sienna: '#A0522D',
silver: '#C0C0C0',
skyblue: '#87CEEB',
slateblue: '#6A5ACD',
slategray: '#708090',
slategrey: '#708090',
snow: '#FFFAFA',
springgreen: '#00FF7F',
steelblue: '#4682B4',
tan: '#D2B48C',
teal: '#008080',
thistle: '#D8BFD8',
tomato: '#FF6347',
turquoise: '#40E0D0',
violet: '#EE82EE',
wheat: '#F5DEB3',
white: '#FFFFFF',
whitesmoke: '#F5F5F5',
yellow: '#FFFF00',
yellowgreen: '#9ACD32'
});
return Color;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var Constants = /** @class */ (function () {
function Constants() {
}
Constants.STEP_EVERYTHING = 0;
Constants.STEP_FILTER = 1;
Constants.STEP_SORT = 2;
Constants.STEP_MAP = 3;
Constants.STEP_AGGREGATE = 4;
Constants.STEP_PIVOT = 5;
Constants.ROW_BUFFER_SIZE = 10;
Constants.LAYOUT_INTERVAL = 500;
Constants.BATCH_WAIT_MILLIS = 50;
Constants.EXPORT_TYPE_DRAG_COPY = 'dragCopy';
Constants.EXPORT_TYPE_CLIPBOARD = 'clipboard';
Constants.EXPORT_TYPE_EXCEL = 'excel';
Constants.EXPORT_TYPE_CSV = 'csv';
Constants.KEY_BACKSPACE = 8;
Constants.KEY_TAB = 9;
Constants.KEY_NEW_LINE = 10;
Constants.KEY_ENTER = 13;
Constants.KEY_SHIFT = 16;
Constants.KEY_ESCAPE = 27;
Constants.KEY_SPACE = 32;
Constants.KEY_LEFT = 37;
Constants.KEY_UP = 38;
Constants.KEY_RIGHT = 39;
Constants.KEY_DOWN = 40;
Constants.KEY_DELETE = 46;
Constants.KEY_A = 65;
Constants.KEY_C = 67;
Constants.KEY_V = 86;
Constants.KEY_D = 68;
Constants.KEY_Z = 90;
Constants.KEY_Y = 89;
Constants.KEY_F2 = 113;
Constants.KEY_PAGE_UP = 33;
Constants.KEY_PAGE_DOWN = 34;
Constants.KEY_PAGE_HOME = 36;
Constants.KEY_PAGE_END = 35;
Constants.ROW_MODEL_TYPE_INFINITE = 'infinite';
Constants.ROW_MODEL_TYPE_VIEWPORT = 'viewport';
Constants.ROW_MODEL_TYPE_CLIENT_SIDE = 'clientSide';
Constants.ROW_MODEL_TYPE_SERVER_SIDE = 'serverSide';
Constants.DEPRECATED_ROW_MODEL_TYPE_NORMAL = 'normal';
Constants.ALWAYS = 'always';
Constants.ONLY_WHEN_GROUPING = 'onlyWhenGrouping';
Constants.PINNED_TOP = 'top';
Constants.PINNED_BOTTOM = 'bottom';
Constants.DOM_LAYOUT_NORMAL = 'normal';
Constants.DOM_LAYOUT_PRINT = 'print';
Constants.DOM_LAYOUT_AUTO_HEIGHT = 'autoHeight';
Constants.GROUP_AUTO_COLUMN_ID = 'ag-Grid-AutoColumn';
Constants.SOURCE_PASTE = 'paste';
Constants.PINNED_RIGHT = 'right';
Constants.PINNED_LEFT = 'left';
Constants.SORT_ASC = 'asc';
Constants.SORT_DESC = 'desc';
return Constants;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var FUNCTION_STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var FUNCTION_ARGUMENT_NAMES = /([^\s,]+)/g;
var AG_GRID_STOP_PROPAGATION = '__ag_Grid_Stop_Propagation';
/**
* HTML Escapes.
*/
var HTML_ESCAPES = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
var reUnescapedHtml = /[&<>"']/g;
var Utils = /** @class */ (function () {
function Utils() {
}
/**
* If the key was passed before, then doesn't execute the func
* @param {Function} func
* @param {string} key
*/
Utils.doOnce = function (func, key) {
if (this.doOnceFlags[key]) {
return;
}
func();
this.doOnceFlags[key] = true;
};
Utils.getMaxSafeInteger = function () {
// eslint-disable-next-line
if (!Number.MAX_SAFE_INTEGER) {
return 9007199254740991;
}
// eslint-disable-next-line
return Number.MAX_SAFE_INTEGER;
};
/**
* Checks if event was issued by a left click
* from https://stackoverflow.com/questions/3944122/detect-left-mouse-button-press
* @param {MouseEvent} mouseEvent
* @returns {boolean}
*/
Utils.isLeftClick = function (mouseEvent) {
if ("buttons" in mouseEvent) {
return mouseEvent.buttons == 1;
}
var button = mouseEvent.which || mouseEvent.button;
return button == 1;
};
/**
* `True` if the event is close to the original event by X pixels either vertically or horizontally.
* we only start dragging after X pixels so this allows us to know if we should start dragging yet.
* @param {MouseEvent | TouchEvent} e1
* @param {MouseEvent | TouchEvent} e2
* @param {number} pixelCount
* @returns {boolean}
*/
Utils.areEventsNear = function (e1, e2, pixelCount) {
// by default, we wait 4 pixels before starting the drag
if (pixelCount === 0) {
return false;
}
var diffX = Math.abs(e1.clientX - e2.clientX);
var diffY = Math.abs(e1.clientY - e2.clientY);
return Math.max(diffX, diffY) <= pixelCount;
};
Utils.jsonEquals = function (val1, val2) {
var val1Json = val1 ? JSON.stringify(val1) : null;
var val2Json = val2 ? JSON.stringify(val2) : null;
return val1Json === val2Json;
};
Utils.shallowCompare = function (arr1, arr2) {
// if both are missing, then they are the same
if (this.missing(arr1) && this.missing(arr2)) {
return true;
}
// if one is present, but other is missing, then they are different
if (this.missing(arr1) || this.missing(arr2)) {
return false;
}
if (arr1.length !== arr2.length) {
return false;
}
for (var i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
};
Utils.getNameOfClass = function (theClass) {
var funcNameRegex = /function (.{1,})\(/;
var funcAsString = theClass.toString();
var results = funcNameRegex.exec(funcAsString);
return results && results.length > 1 ? results[1] : "";
};
Utils.getValueUsingField = function (data, field, fieldContainsDots) {
if (!field || !data) {
return;
}
// if no '.', then it's not a deep value
if (!fieldContainsDots) {
return data[field];
}
else {
// otherwise it is a deep value, so need to dig for it
var fields = field.split('.');
var currentObject = data;
for (var i = 0; i < fields.length; i++) {
currentObject = currentObject[fields[i]];
if (this.missing(currentObject)) {
return null;
}
}
return currentObject;
}
};
Utils.getElementSize = function (el) {
var _a = window.getComputedStyle(el), height = _a.height, width = _a.width, paddingTop = _a.paddingTop, paddingRight = _a.paddingRight, paddingBottom = _a.paddingBottom, paddingLeft = _a.paddingLeft, marginTop = _a.marginTop, marginRight = _a.marginRight, marginBottom = _a.marginBottom, marginLeft = _a.marginLeft, boxSizing = _a.boxSizing;
return {
height: parseFloat(height),
width: parseFloat(width),
paddingTop: parseFloat(paddingTop),
paddingRight: parseFloat(paddingRight),
paddingBottom: parseFloat(paddingBottom),
paddingLeft: parseFloat(paddingLeft),
marginTop: parseFloat(marginTop),
marginRight: parseFloat(marginRight),
marginBottom: parseFloat(marginBottom),
marginLeft: parseFloat(marginLeft),
boxSizing: boxSizing
};
};
Utils.getInnerHeight = function (el) {
var size = this.getElementSize(el);
if (size.boxSizing === 'border-box') {
return size.height - size.paddingTop - size.paddingBottom;
}
return size.height;
};
Utils.getInnerWidth = function (el) {
var size = this.getElementSize(el);
if (size.boxSizing === 'border-box') {
return size.width - size.paddingLeft - size.paddingRight;
}
return size.width;
};
Utils.getAbsoluteHeight = function (el) {
var size = this.getElementSize(el);
var marginRight = size.marginBottom + size.marginTop;
return Math.ceil(el.offsetHeight + marginRight);
};
Utils.getAbsoluteWidth = function (el) {
var size = this.getElementSize(el);
var marginWidth = size.marginLeft + size.marginRight;
return Math.ceil(el.offsetWidth + marginWidth);
};
Utils.getScrollLeft = function (element, rtl) {
var scrollLeft = element.scrollLeft;
if (rtl) {
// Absolute value - for FF that reports RTL scrolls in negative numbers
scrollLeft = Math.abs(scrollLeft);
// Get Chrome to return the same value as well
if (this.isBrowserChrome()) {
scrollLeft = element.scrollWidth - element.clientWidth - scrollLeft;
}
}
return scrollLeft;
};
Utils.cleanNumber = function (value) {
if (typeof value === 'string') {
value = parseInt(value, 10);
}
if (typeof value === 'number') {
value = Math.floor(value);
}
else {
value = null;
}
return value;
};
Utils.setScrollLeft = function (element, value, rtl) {
if (rtl) {
// Chrome and Safari when doing RTL have the END position of the scroll as zero, not the start
if (this.isBrowserSafari() || this.isBrowserChrome()) {
value = element.scrollWidth - element.clientWidth - value;
}
// Firefox uses negative numbers when doing RTL scrolling
if (this.isBrowserFirefox()) {
value *= -1;
}
}
element.scrollLeft = value;
};
Utils.iterateNamedNodeMap = function (map, callback) {
if (!map) {
return;
}
for (var i = 0; i < map.length; i++) {
var attr = map[i];
callback(attr.name, attr.value);
}
};
Utils.iterateObject = function (object, callback) {
if (!object || this.missing(object)) {
return;
}
if (Array.isArray(object)) {
object.forEach(function (value, index) { return callback("" + index, value); });
}
else {
Object.keys(object).forEach(function (key) { return callback(key, object[key]); });
}
};
Utils.cloneObject = function (object) {
var copy = {};
var keys = Object.keys(object);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = object[key];
copy[key] = value;
}
return copy;
};
/**
* Will copy the specified properties from `source` into the equivalent properties on `target`, ignoring properties with
* a value of `undefined`.
*/
Utils.copyPropertiesIfPresent = function (source, target) {
var _this = this;
var properties = [];
for (var _i = 2; _i < arguments.length; _i++) {
properties[_i - 2] = arguments[_i];
}
properties.forEach(function (p) { return _this.copyPropertyIfPresent(source, target, p); });
};
/**
* Will copy the specified property from `source` into the equivalent property on `target`, unless the property has a
* value of `undefined`. If a transformation is provided, it will be applied to the value before being set on `target`.
*/
Utils.copyPropertyIfPresent = function (source, target, property, transform) {
var value = this.getProperty(source, property);
if (value !== undefined) {
this.setProperty(target, property, transform ? transform(value) : value);
}
};
Utils.getAllKeysInObjects = function (objects) {
var allValues = {};
objects.forEach(function (obj) {
if (obj) {
Object.keys(obj).forEach(function (key) { return allValues[key] = null; });
}
});
return Object.keys(allValues);
};
Utils.mergeDeep = function (dest, source, copyUndefined) {
if (copyUndefined === void 0) { copyUndefined = true; }
if (!this.exists(source)) {
return;
}
this.iterateObject(source, function (key, newValue) {
var oldValue = dest[key];
if (oldValue === newValue) {
return;
}
if (typeof oldValue === 'object' && typeof newValue === 'object' && !Array.isArray(oldValue)) {
Utils.mergeDeep(oldValue, newValue);
}
else if (copyUndefined || newValue !== undefined) {
dest[key] = newValue;
}
});
};
Utils.assign = function (object) {
var _this = this;
var sources = [];
for (var _i = 1; _i < arguments.length; _i++) {
sources[_i - 1] = arguments[_i];
}
sources.forEach(function (source) {
if (_this.exists(source)) {
_this.iterateObject(source, function (key, value) {
object[key] = value;
});
}
});
return object;
};
Utils.flatten = function (arrayOfArrays) {
return [].concat.apply([], arrayOfArrays);
};
Utils.parseYyyyMmDdToDate = function (yyyyMmDd, separator) {
try {
if (!yyyyMmDd) {
return null;
}
if (yyyyMmDd.indexOf(separator) === -1) {
return null;
}
var fields = yyyyMmDd.split(separator);
if (fields.length != 3) {
return null;
}
return new Date(Number(fields[0]), Number(fields[1]) - 1, Number(fields[2]));
}
catch (e) {
return null;
}
};
Utils.serializeDateToYyyyMmDd = function (date, separator) {
if (!date) {
return null;
}
return date.getFullYear() + separator + this.padStart(date.getMonth() + 1, 2) + separator + this.padStart(date.getDate(), 2);
};
Utils.padStart = function (num, totalStringSize) {
var asString = num + "";
while (asString.length < totalStringSize) {
asString = "0" + asString;
}
return asString;
};
Utils.pushAll = function (target, source) {
if (this.missing(source) || this.missing(target)) {
return;
}
source.forEach(function (func) { return target.push(func); });
};
Utils.createArrayOfNumbers = function (first, last) {
var result = [];
for (var i = first; i <= last; i++) {
result.push(i);
}
return result;
};
Utils.getFunctionParameters = function (func) {
var fnStr = func.toString().replace(FUNCTION_STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(FUNCTION_ARGUMENT_NAMES);
if (result === null) {
return [];
}
else {
return result;
}
};
Utils.find = function (collection, predicate, value) {
if (collection === null || collection === undefined) {
return null;
}
if (!Array.isArray(collection)) {
var objToArray = this.values(collection);
return this.find(objToArray, predicate, value);
}
var collectionAsArray = collection;
var firstMatchingItem = null;
for (var i = 0; i < collectionAsArray.length; i++) {
var item = collectionAsArray[i];
if (typeof predicate === 'string') {
if (item[predicate] === value) {
firstMatchingItem = item;
break;
}
}
else {
var callback = predicate;
if (callback(item)) {
firstMatchingItem = item;
break;
}
}
}
return firstMatchingItem;
};
Utils.toStrings = function (array) {
return array.map(function (item) {
if (item === undefined || item === null || !item.toString) {
return null;
}
else {
return item.toString();
}
});
};
Utils.findIndex = function (collection, predicate) {
for (var i = 0; i < collection.length; i++) {
if (predicate(collection[i], i, collection)) {
return i;
}
}
return -1;
};
/**
* Returns true if it is a DOM node
* taken from: http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
* @param {any} o
* @return {boolean}
*/
Utils.isNode = function (o) {
return (typeof Node === "function" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string");
};
//
/**
* Returns true if it is a DOM element
* taken from: http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
* @param {any} o
* @returns {boolean}
*/
Utils.isElement = function (o) {
return (typeof HTMLElement === "function" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string");
};
Utils.isNodeOrElement = function (o) {
return this.isNode(o) || this.isElement(o);
};
/**
* Makes a copy of a node list into a list
* @param {NodeList} nodeList
* @returns {Node[]}
*/
Utils.copyNodeList = function (nodeList) {
var childCount = nodeList ? nodeList.length : 0;
var res = [];
for (var i = 0; i < childCount; i++) {
res.push(nodeList[i]);
}
return res;
};
Utils.isEventFromPrintableCharacter = function (event) {
var pressedChar = String.fromCharCode(event.charCode);
// newline is an exception, as it counts as a printable character, but we don't
// want to start editing when it is pressed. without this check, if user is in chrome
// and editing a cell, and they press ctrl+enter, the cell stops editing, and then
// starts editing again with a blank value (two 'key down' events are fired). to
// test this, remove the line below, edit a cell in chrome and hit ctrl+enter while editing.
// https://ag-grid.atlassian.net/browse/AG-605
if (this.isKeyPressed(event, Constants.KEY_NEW_LINE)) {
return false;
}
// no allowed printable chars have alt or ctrl key combinations
if (event.altKey || event.ctrlKey) {
return false;
}
if (_.exists(event.key)) {
// modern browser will implement key, so we return if key is length 1, eg if it is 'a' for the
// a key, or '2' for the '2' key. non-printable characters have names, eg 'Enter' or 'Backspace'.
var printableCharacter = event.key.length === 1;
// IE11 & Edge treat the numpad del key differently - with numlock on we get "Del" for key,
// so this addition checks if its IE11/Edge and handles that specific case the same was as all other browsers
var numpadDelWithNumlockOnForEdgeOrIe = Utils.isNumpadDelWithNumlockOnForEdgeOrIe(event);
return printableCharacter || numpadDelWithNumlockOnForEdgeOrIe;
}
else {
// otherwise, for older browsers, we test against a list of characters, which doesn't include
// accents for non-English, but don't care much, as most users are on modern browsers
return Utils.PRINTABLE_CHARACTERS.indexOf(pressedChar) >= 0;
}
};
/**
* Allows user to tell the grid to skip specific keyboard events
* @param {GridOptionsWrapper} gridOptionsWrapper
* @param {KeyboardEvent} keyboardEvent
* @param {RowNode} rowNode
* @param {Column} column
* @param {boolean} editing
* @returns {boolean}
*/
Utils.isUserSuppressingKeyboardEvent = function (gridOptionsWrapper, keyboardEvent, rowNode, column, editing) {
var gridOptionsFunc = gridOptionsWrapper.getSuppressKeyboardEventFunc();
var colDefFunc = column.getColDef().suppressKeyboardEvent;
// if no callbacks provided by user, then do nothing
if (!gridOptionsFunc && !colDefFunc) {
return false;
}
var params = {
event: keyboardEvent,
editing: editing,
column: column,
api: gridOptionsWrapper.getApi(),
node: rowNode,
data: rowNode.data,
colDef: column.getColDef(),
context: gridOptionsWrapper.getContext(),
columnApi: gridOptionsWrapper.getColumnApi()
};
// colDef get first preference on suppressing events
if (colDefFunc) {
var colDefFuncResult = colDefFunc(params);
// if colDef func suppressed, then return now, no need to call gridOption func
if (colDefFuncResult) {
return true;
}
}
if (gridOptionsFunc) {
// if gridOption func, return the result
return gridOptionsFunc(params);
}
else {
// otherwise return false, don't suppress, as colDef didn't suppress and no func on gridOptions
return false;
}
};
Utils.getCellCompForEvent = function (gridOptionsWrapper, event) {
var sourceElement = this.getTarget(event);
while (sourceElement) {
var renderedCell = gridOptionsWrapper.getDomData(sourceElement, 'cellComp');
if (renderedCell) {
return renderedCell;
}
sourceElement = sourceElement.parentElement;
}
return null;
};
/**
* Adds all type of change listeners to an element, intended to be a text field
* @param {HTMLElement} element
* @param {EventListener} listener
*/
Utils.addChangeListener = function (element, listener) {
element.addEventListener("changed", listener);
element.addEventListener("paste", listener);
element.addEventListener("input", listener);
// IE doesn't fire changed for special keys (eg delete, backspace), so need to
// listen for this further ones
element.addEventListener("keydown", listener);
element.addEventListener("keyup", listener);
};
/**
* If value is undefined, null or blank, returns null, otherwise returns the value
* @param {T} value
* @returns {T | null}
*/
Utils.makeNull = function (value) {
var valueNoType = value;
if (value === null || value === undefined || valueNoType === "") {
return null;
}
return value;
};
Utils.missing = function (value) {
return !this.exists(value);
};
Utils.missingOrEmpty = function (value) {
return !value || this.missing(value) || value.length === 0;
};
Utils.missingOrEmptyObject = function (value) {
return this.missing(value) || Object.keys(value).length === 0;
};
Utils.exists = function (value, allowEmptyString) {
if (allowEmptyString === void 0) { allowEmptyString = false; }
return value != null && (value !== '' || allowEmptyString);
};
Utils.firstExistingValue = function () {
var values = [];
for (var _i = 0; _i < arguments.length; _i++) {
values[_i] = arguments[_i];
}
for (var i = 0; i < values.length; i++) {
var value = values[i];
if (_.exists(value)) {
return value;
}
}
return null;
};
Utils.anyExists = function (values) {
if (values) {
for (var i = 0; i < values.length; i++) {
if (this.exists(values[i])) {
return true;
}
}
}
return false;
};
Utils.existsAndNotEmpty = function (value) {
return value != null && this.exists(value) && value.length > 0;
};
Utils.clearElement = function (el) {
while (el && el.firstChild) {
el.removeChild(el.firstChild);
}
};
Utils.removeElement = function (parent, cssSelector) {
this.removeFromParent(parent.querySelector(cssSelector));
};
Utils.removeFromParent = function (node) {
if (node && node.parentNode) {
node.parentNode.removeChild(node);
}
};
Utils.isVisible = function (element) {
return (element.offsetParent !== null);
};
Utils.callIfPresent = function (func) {
if (func) {
func();
}
};
/**
* Loads the template and returns it as an element. makes up for no simple way in
* the dom api to load html directly, eg we cannot do this: document.createElement(template)
* @param {string} template
* @returns {HTMLElement}
*/
Utils.loadTemplate = function (template) {
var tempDiv = document.createElement("div");
tempDiv.innerHTML = template;
return tempDiv.firstChild;
};
Utils.appendHtml = function (eContainer, htmlTemplate) {
if (eContainer.lastChild) {
// https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
// we put the items at the start, so new items appear underneath old items,
// so when expanding/collapsing groups, the new rows don't go on top of the
// rows below that are moving our of the way
eContainer.insertAdjacentHTML('afterbegin', htmlTemplate);
}
else {
eContainer.innerHTML = htmlTemplate;
}
};
Utils.addOrRemoveCssClass = function (element, className, addOrRemove) {
if (addOrRemove) {
this.addCssClass(element, className);
}
else {
this.removeCssClass(element, className);
}
};
/**
* This method adds a class to an element and remove that class from all siblings.
* Useful for toggling state.
* @param {HTMLElement} element The element to receive the class
* @param {string} className The class to be assigned to the element
* @param {boolean} [inverted] This inverts the effect, adding the class to all siblings and
* removing from the relevant element (useful when adding a class to hide non-selected elements).
*/
Utils.radioCssClass = function (element, className, inverted) {
var parent = element.parentElement;
var sibling = parent.firstChild;
while (sibling) {
_.addOrRemoveCssClass(sibling, className, inverted ? (sibling !== element) : (sibling === element));
sibling = sibling.nextSibling;
}
};
Utils.addCssClass = function (element, className) {
var _this = this;
if (!className || className.length === 0) {
return;
}
if (className.indexOf(' ') >= 0) {
className.split(' ').forEach(function (value) { return _this.addCssClass(element, value); });
return;
}
if (element.classList) {
element.classList.add(className);
}
else if (element.className && element.className.length > 0) {
var cssClasses = element.className.split(' ');
if (cssClasses.indexOf(className) < 0) {
cssClasses.push(className);
element.setAttribute('class', cssClasses.join(' '));
}
}
else {
// do not use element.classList = className here, it will cause
// a read-only assignment error on some browsers (IE/Edge).
element.setAttribute('class', className);
}
};
Utils.removeCssClass = function (element, className) {
if (element.classList) {
element.classList.remove(className);
}
else if (element.className && element.className.length > 0) {
var newClassName = element.className.split(' ').filter(function (c) { return c !== className; }).join(' ');
element.setAttribute('class', newClassName);
}
};
Utils.containsClass = function (element, className) {
if (element.classList) {
// for modern browsers
return element.classList.contains(className);
}
else if (element.className) {
// for older browsers, check against the string of class names
// if only one class, can check for exact match
var onlyClass = element.className === className;
// if many classes, check for class name, we have to pad with ' ' to stop other
// class names that are a substring of this class
var contains = element.className.indexOf(' ' + className + ' ') >= 0;
// the padding above then breaks when it's the first or last class names
var startsWithClass = element.className.indexOf(className + ' ') === 0;
var endsWithClass = element.className.lastIndexOf(' ' + className) === (element.className.length - className.length - 1);
return onlyClass || contains || startsWithClass || endsWithClass;
}
else {
// if item is not a node
return false;
}
};
Utils.getElementAttribute = function (element, attributeName) {
if (element.attributes && element.attributes[attributeName]) {
var attribute = element.attributes[attributeName];
return attribute.value;
}
else {
return null;
}
};
Utils.offsetHeight = function (element) {
return element && element.clientHeight ? element.clientHeight : 0;
};
Utils.offsetWidth = function (element) {
return element && element.clientWidth ? element.clientWidth : 0;
};
Utils.sortNumerically = function (array) {
return array.sort(function (a, b) { return a - b; });
};
Utils.removeRepeatsFromArray = function (array, object) {
if (!array) {
return;
}
for (var index = array.length - 2; index >= 0; index--) {
var thisOneMatches = array[index] === object;
var nextOneMatches = array[index + 1] === object;
if (thisOneMatches && nextOneMatches) {
array.splice(index + 1, 1);
}
}
};
Utils.removeFromArray = function (array, object) {
var index = array.indexOf(object);
if (index >= 0) {
array.splice(index, 1);
}
};
Utils.removeAllFromArray = function (array, toRemove) {
var _this = this;
toRemove.forEach(function (item) { return _this.removeFromArray(array, item); });
};
Utils.insertIntoArray = function (array, object, toIndex) {
array.splice(toIndex, 0, object);
};
Utils.insertArrayIntoArray = function (dest, src, toIndex) {
if (this.missing(dest) || this.missing(src)) {
return;
}
// put items in backwards, otherwise inserted items end up in reverse order
for (var i = src.length - 1; i >= 0; i--) {
var item = src[i];
this.insertIntoArray(dest, item, toIndex);
}
};
Utils.moveInArray = function (array, objectsToMove, toIndex) {
var _this = this;
// first take out it items from the array
objectsToMove.forEach(function (obj) {
_this.removeFromArray(array, obj);
});
// now add the objects, in same order as provided to us, that means we start at the end
// as the objects will be pushed to the right as they are inserted
objectsToMove.slice().reverse().forEach(function (obj) {
_this.insertIntoArray(array, obj, toIndex);
});
};
Utils.defaultComparator = function (valueA, valueB, accentedCompare) {
if (accentedCompare === void 0) { accentedCompare = false; }
var valueAMissing = valueA === null || valueA === undefined;
var valueBMissing = valueB === null || valueB === undefined;
// this is for aggregations sum and avg, where the result can be a number that is wrapped.
// if we didn't do this, then the toString() value would be used, which would result in
// the strings getting used instead of the numbers.
if (valueA && valueA.toNumber) {
valueA = valueA.toNumber();
}
if (valueB && valueB.toNumber) {
valueB = valueB.toNumber();
}
if (valueAMissing && valueBMissing) {
return 0;
}
if (valueAMissing) {
return -1;
}
if (valueBMissing) {
return 1;
}
if (typeof valueA === "string") {
if (!accentedCompare) {
return doQuickCompare(valueA, valueB);
}
else {
try {
// using local compare also allows chinese comparisons
return valueA.localeCompare(valueB);
}
catch (e) {
// if something wrong with localeCompare, eg not supported
// by browser, then just continue with the quick one
return doQuickCompare(valueA, valueB);
}
}
}
if (valueA < valueB) {
return -1;
}
else if (valueA > valueB) {
return 1;
}
else {
return 0;
}
function doQuickCompare(a, b) {
return (a > b ? 1 : (a < b ? -1 : 0));
}
};
Utils.last = function (arr) {
if (!arr || !arr.length) {
return undefined;
}
return arr[arr.length - 1];
};
Utils.compareArrays = function (array1, array2) {
if (this.missing(array1) && this.missing(array2)) {
return true;
}
if ((this.missing(array1) || this.missing(array2)) ||
(!array1 || !array2)) {
return false;
}
if (array1.length !== array2.length) {
return false;
}
for (var i = 0; i < array1.length; i++) {
if (array1[i] !== array2[i]) {
return false;
}
}
return true;
};
Utils.ensureDomOrder = function (eContainer, eChild, eChildBefore) {
// if already in right order, do nothing
if (eChildBefore && eChildBefore.nextSibling === eChild) {
return;
}
if (eChildBefore) {
if (eChildBefore.nextSibling) {
// insert between the eRowBefore and the row after it
eContainer.insertBefore(eChild, eChildBefore.nextSibling);
}
else {
// if nextSibling is missing, means other row is at end, so just append new row at the end
eContainer.appendChild(eChild);
}
}
else {
// otherwise put at start
if (eContainer.firstChild && eContainer.firstChild !== eChild) {
// insert it at the first location
eContainer.insertAdjacentElement('afterbegin', eChild);
}
}
};
Utils.setDomChildOrder = function (eContainer, orderedChildren) {
for (var i = 0; i < orderedChildren.length; i++) {
var correctCellAtIndex = orderedChildren[i];
var actualCellAtIndex = eContainer.children[i];
if (actualCellAtIndex !== correctCellAtIndex) {
eContainer.insertBefore(correctCellAtIndex, actualCellAtIndex);
}
}
};
Utils.insertTemplateWithDomOrder = function (eContainer, htmlTemplate, eChildBefore) {
var res;
if (eChildBefore) {
// if previous element exists, just slot in after the previous element
eChildBefore.insertAdjacentHTML('afterend', htmlTemplate);
res = eChildBefore.nextSibling;
}
else {
if (eContainer.firstChild) {
// insert it at the first location
eContainer.insertAdjacentHTML('afterbegin', htmlTemplate);
}
else {
// otherwise eContainer is empty, so just append it
eContainer.innerHTML = htmlTemplate;
}
res = eContainer.firstChild;
}
return res;
};
Utils.every = function (items, callback) {
if (!items || items.length === 0) {
return true;
}
for (var i = 0; i < items.length; i++) {
if (!callback(items[i])) {
return false;
}
}
return true;
};
Utils.toStringOrNull = function (value) {
if (this.exists(value) && value.toString) {
return value.toString();
}
else {
return null;
}
};
Utils.formatSize = function (size) {
if (typeof size === "number") {
return size + "px";
}
else {
return size;
}
};
Utils.formatNumberTwoDecimalPlacesAndCommas = function (value) {
if (typeof value !== 'number') {
return '';
}
// took this from: http://blog.tompawlak.org/number-currency-formatting-javascript
return (Math.round(value * 100) / 100).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
};
Utils.findLineByLeastSquares = function (values) {
var len = values.length;
if (len <= 1) {
return values;
}
var sum_x = 0;
var sum_y = 0;
var sum_xy = 0;
var sum_xx = 0;
var y = 0;
for (var x = 0; x < len; x++) {
y = values[x];
sum_x += x;
sum_y += y;
sum_xx += x * x;
sum_xy += x * y;
}
var m = (len * sum_xy - sum_x * sum_y) / (len * sum_xx - sum_x * sum_x);
var b = (sum_y / len) - (m * sum_x) / len;
var result = [];
for (var x = 0; x <= len; x++) {
result.push(x * m + b);
}
return result;
};
/**
* the native method number.toLocaleString(undefined, {minimumFractionDigits: 0})
* puts in decimal places in IE, so we use this method instead
* from: http://blog.tompawlak.org/number-currency-formatting-javascript
* @param {number} value
* @returns {string}
*/
Utils.formatNumberCommas = function (value) {
if (typeof value !== 'number') {
return '';
}
return value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
};
Utils.prependDC = function (parent, documentFragment) {
if (this.exists(parent.firstChild)) {
parent.insertBefore(documentFragment, parent.firstChild);
}
else {
parent.appendChild(documentFragment);
}
};
/**
* If icon provided, use this (either a string, or a function callback).
* if not, then use the default icon from the theme
* @param {string} iconName
* @param {GridOptionsWrapper} gridOptionsWrapper
* @param {Column | null} [column]
* @returns {HTMLElement}
*/
Utils.createIcon = function (iconName, gridOptionsWrapper, column) {
var iconContents = this.createIconNoSpan(iconName, gridOptionsWrapper, column);
if (iconContents.className.indexOf('ag-icon') > -1) {
return iconContents;
}
else {
var eResult = document.createElement('span');
eResult.appendChild(iconContents);
return eResult;
}
};
Utils.createIconNoSpan = function (iconName, gridOptionsWrapper, column, forceCreate) {
var userProvidedIcon = null;
// check col for icon first
var icons = column && column.getColDef().icons;
if (icons) {
userProvidedIcon = icons[iconName];
}
// if not in col, try grid options
if (gridOptionsWrapper && !userProvidedIcon) {
var optionsIcons = gridOptionsWrapper.getIcons();
if (optionsIcons) {
userProvidedIcon = optionsIcons[iconName];
}
}
// now if user provided, use it
if (userProvidedIcon) {
var rendererResult = void 0;
if (typeof userProvidedIcon === 'function') {
rendererResult = userProvidedIcon();
}
else if (typeof userProvidedIcon === 'string') {
rendererResult = userProvidedIcon;
}
else {
throw new Error('icon from grid options needs to be a string or a function');
}
if (typeof rendererResult === 'string') {
return this.loadTemplate(rendererResult);
}
else if (this.isNodeOrElement(rendererResult)) {
return rendererResult;
}
else {
console.warn('ag-Grid: iconRenderer should return back a string or a dom object');
}
}
else {
var span = document.createElement('span');
var cssClass = this.iconNameClassMap[iconName];
if (!cssClass) {
if (!forceCreate) {
console.warn("ag-Grid: Did not find icon " + iconName);
cssClass = '';
}
else {
cssClass = iconName;
}
}
span.setAttribute("class", "ag-icon ag-icon-" + cssClass);
span.setAttribute("unselectable", "on");
return span;
}
};
Utils.addStylesToElement = function (eElement, styles) {
var _this = this;
if (!styles) {
return;
}
Object.keys(styles).forEach(function (key) {
var keyCamelCase = _this.hyphenToCamelCase(key);
if (keyCamelCase) {
eElement.style[keyCamelCase] = styles[key];
}
});
};
Utils.isHorizontalScrollShowing = function (element) {
return element.clientWidth < element.scrollWidth;
};
Utils.isVerticalScrollShowing = function (element) {
return element.clientHeight < element.scrollHeight;
};
Utils.getMaxDivHeight = function () {
if (!document.body) {
return -1;
}
var res = 1000000;
// FF reports the height back but still renders blank after ~6M px
var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000;
var div = this.loadTemplate("
");
document.body.appendChild(div);
while (true) {
var test = res * 2;
div.style.height = test + 'px';
if (test > testUpTo || div.clientHeight !== test) {
break;
}
else {
res = test;
}
}
document.body.removeChild(div);
return res;
};
Utils.getScrollbarWidth = function () {
var body = document.body;
var div = document.createElement("div");
div.style.width = div.style.height = "100px";
div.style.opacity = "0";
div.style.overflow = "scroll";
div.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
div.style.position = "absolute";
body.appendChild(div);
var width = div.offsetWidth - div.clientWidth;
// remove divs
if (div.parentNode) {
div.parentNode.removeChild(div);
}
return width;
};
Utils.hasOverflowScrolling = function () {
var prefixes = ['webkit', 'moz', 'o', 'ms'];
var div = document.createElement('div');
var body = document.getElementsByTagName('body')[0];
var found = false;
var p;
body.appendChild(div);
div.setAttribute('style', prefixes.map(function (prefix) { return "-" + prefix + "-overflow-scrolling: touch"; }).concat('overflow-scrolling: touch').join(';'));
var computedStyle = window.getComputedStyle(div);
if (computedStyle.overflowScrolling === 'touch') {
found = true;
}
if (!found) {
for (var _i = 0, prefixes_1 = prefixes; _i < prefixes_1.length; _i++) {
p = prefixes_1[_i];
if (computedStyle[p + "OverflowScrolling"] === 'touch') {
found = true;
break;
}
}
}
if (div.parentNode) {
div.parentNode.removeChild(div);
}
return found;
};
Utils.isKeyPressed = function (event, keyToCheck) {
var pressedKey = event.which || event.keyCode;
return pressedKey === keyToCheck;
};
Utils.isCharacterKey = function (event) {
// from: https://stackoverflow.com/questions/4179708/how-to-detect-if-the-pressed-key-will-produce-a-character-inside-an-input-text
var which = event.which;
if (typeof which === 'number' && which) {
return !event.ctrlKey && !event.metaKey && !event.altKey && event.which !== 8 && event.which !== 16;
}
return which === undefined;
};
Utils.setDisplayed = function (element, displayed) {
this.addOrRemoveCssClass(element, 'ag-hidden', !displayed);
};
Utils.setVisible = function (element, visible) {
this.addOrRemoveCssClass(element, 'ag-invisible', !visible);
};
Utils.setElementWidth = function (element, width) {
if (width === 'flex') {
element.style.width = null;
element.style.minWidth = null;
element.style.maxWidth = null;
element.style.flex = '1 1 auto';
}
else {
this.setFixedWidth(element, width);
}
};
Utils.setFixedWidth = function (element, width) {
width = this.formatSize(width);
element.style.width = width;
element.style.maxWidth = width;
element.style.minWidth = width;
};
Utils.setElementHeight = function (element, height) {
if (height === 'flex') {
element.style.height = null;
element.style.minHeight = null;
element.style.maxHeight = null;
element.style.flex = '1 1 auto';
}
else {
this.setFixedHeight(element, height);
}
};
Utils.setFixedHeight = function (element, height) {
height = this.formatSize(height);
element.style.height = height;
element.style.maxHeight = height;
element.style.minHeight = height;
};
Utils.isBrowserIE = function () {
if (this.isIE === undefined) {
this.isIE = /*@cc_on!@*/ !!document.documentMode; // At least IE6
}
return this.isIE;
};
Utils.isBrowserEdge = function () {
if (this.isEdge === undefined) {
this.isEdge = !this.isBrowserIE() && !!window.StyleMedia;
}
return this.isEdge;
};
Utils.isBrowserSafari = function () {
if (this.isSafari === undefined) {
var anyWindow = window;
// taken from https://github.com/ag-grid/ag-grid/issues/550
this.isSafari = Object.prototype.toString.call(anyWindow.HTMLElement).indexOf('Constructor') > 0
|| (function (p) {
return p ? p.toString() === "[object SafariRemoteNotification]" : false;
})(!anyWindow.safari || anyWindow.safari.pushNotification);
}
return this.isSafari;
};
Utils.isBrowserChrome = function () {
if (this.isChrome === undefined) {
var win = window;
this.isChrome = (!!win.chrome && (!!win.chrome.webstore || !!win.chrome.runtime)) ||
(/Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor));
}
return this.isChrome;
};
Utils.isBrowserFirefox = function () {
if (this.isFirefox === undefined) {
var win = window;
this.isFirefox = typeof win.InstallTrigger !== 'undefined';
}
return this.isFirefox;
};
Utils.isIOSUserAgent = function () {
if (this.isIOS === undefined) {
// taken from https://stackoverflow.com/a/58064481/1388233
this.isIOS = (/iPad|iPhone|iPod/.test(navigator.platform) ||
// eslint-disable-next-line
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream;
}
return this.isIOS;
};
/**
* srcElement is only available in IE. In all other browsers it is target
* http://stackoverflow.com/questions/5301643/how-can-i-make-event-srcelement-work-in-firefox-and-what-does-it-mean
* @param {Event} event
* @returns {Element}
*/
Utils.getTarget = function (event) {
var eventNoType = event;
return eventNoType.target || eventNoType.srcElement;
};
Utils.isElementChildOfClass = function (element, cls, maxNest) {
var counter = 0;
while (element) {
if (this.containsClass(element, cls)) {
return true;
}
element = element.parentElement;
if (maxNest && ++counter > maxNest) {
break;
}
}
return false;
};
Utils.isElementInEventPath = function (element, event) {
if (!event || !element) {
return false;
}
var path = _.getEventPath(event);
return path.indexOf(element) >= 0;
};
Utils.isFunction = function (val) {
return !!(val && val.constructor && val.call && val.apply);
};
Utils.createEventPath = function (event) {
var res = [];
var pointer = _.getTarget(event);
while (pointer) {
res.push(pointer);
pointer = pointer.parentElement;
}
return res;
};
/**
* firefox doesn't have event.path set, or any alternative to it, so we hack
* it in. this is needed as it's to late to work out the path when the item is
* removed from the dom. used by MouseEventService, where it works out if a click
* was from the current grid, or a detail grid (master / detail).
* @param {Event} event
*/
Utils.addAgGridEventPath = function (event) {
event.__agGridEventPath = this.getEventPath(event);
};
/**
* Gets the path for an Event.
* https://stackoverflow.com/questions/39245488/event-path-undefined-with-firefox-and-vue-js
* https://developer.mozilla.org/en-US/docs/Web/API/Event
* @param {Event} event
* @returns {EventTarget[]}
*/
Utils.getEventPath = function (event) {
var eventNoType = event;
if (eventNoType.deepPath) {
// IE supports deep path
return eventNoType.deepPath();
}
else if (eventNoType.path) {
// Chrome supports path
return eventNoType.path;
}
else if (eventNoType.composedPath) {
// Firefox supports composePath
return eventNoType.composedPath();
}
else if (eventNoType.__agGridEventPath) {
// Firefox supports composePath
return eventNoType.__agGridEventPath;
}
else {
// and finally, if none of the above worked,
// we create the path ourselves
return this.createEventPath(event);
}
};
Utils.forEachSnapshotFirst = function (list, callback) {
if (list) {
var arrayCopy = list.slice(0);
arrayCopy.forEach(callback);
}
};
/**
* Gets the document body width
* from: http://stackoverflow.com/questions/1038727/how-to-get-browser-width-using-javascript-code
* @returns {number}
*/
Utils.getBodyWidth = function () {
if (document.body) {
return document.body.clientWidth;
}
if (window.innerHeight) {
return window.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
return -1;
};
/**
* Gets the body height
* from: http://stackoverflow.com/questions/1038727/how-to-get-browser-width-using-javascript-code
* @returns {number}
*/
Utils.getBodyHeight = function () {
if (document.body) {
return document.body.clientHeight;
}
if (window.innerHeight) {
return window.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
return -1;
};
Utils.setCheckboxState = function (eCheckbox, state) {
if (typeof state === 'boolean') {
eCheckbox.checked = state;
eCheckbox.indeterminate = false;
}
else {
// isNodeSelected returns back undefined if it's a group and the children
// are a mix of selected and unselected
eCheckbox.indeterminate = true;
}
};
Utils.traverseNodesWithKey = function (nodes, callback) {
var keyParts = [];
recursiveSearchNodes(nodes);
function recursiveSearchNodes(currentNodes) {
currentNodes.forEach(function (node) {
// also checking for children for tree data
if (node.group || node.hasChildren()) {
keyParts.push(node.key);
var key = keyParts.join('|');
callback(node, key);
recursiveSearchNodes(node.childrenAfterGroup);
keyParts.pop();
}
});
}
};
/**
* Converts a camelCase string into hyphenated string
* from https://gist.github.com/youssman/745578062609e8acac9f
* @param {string} str
* @return {string}
*/
Utils.camelCaseToHyphen = function (str) {
if (str === null || str === undefined) {
return null;
}
return str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
};
/**
* Converts a hyphenated string into camelCase string
* from https://stackoverflow.com/questions/6660977/convert-hyphens-to-camel-case-camelcase
* @param {string} str
* @return {string}
*/
Utils.hyphenToCamelCase = function (str) {
if (str === null || str === undefined) {
return null;
}
return str.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
};
Utils.capitalise = function (str) {
return str[0].toUpperCase() + str.substr(1).toLowerCase();
};
/**
* Converts a CSS object into string
* @param {Object} stylesToUse an object eg: {color: 'black', top: '25px'}
* @return {string} A string like "color: black; top: 25px;" for html
*/
Utils.cssStyleObjectToMarkup = function (stylesToUse) {
var _this = this;
if (!stylesToUse) {
return '';
}
var resParts = [];
this.iterateObject(stylesToUse, function (styleKey, styleValue) {
var styleKeyDashed = _this.camelCaseToHyphen(styleKey);
resParts.push(styleKeyDashed + ": " + styleValue + ";");
});
return resParts.join(' ');
};
/**
* Check if a value is numeric
* from http://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers
* @param {any} value
* @return {boolean}
*/
Utils.isNumeric = function (value) {
if (value === '') {
return false;
}
return !isNaN(parseFloat(value)) && isFinite(value);
};
Utils.escape = function (toEscape) {
if (toEscape === null || toEscape === undefined || !toEscape.replace) {
return toEscape;
}
return toEscape.replace(reUnescapedHtml, function (chr) { return HTML_ESCAPES[chr]; });
};
/**
* Mouse wheel (and 2-finger trackpad) support on the web sucks. It is
* complicated, thus this doc is long and (hopefully) detailed enough to answer
* your questions.
*
* If you need to react to the mouse wheel in a predictable way, this code is
* like your bestest friend. * hugs *
*
* As of today, there are 4 DOM event types you can listen to:
*
* 'wheel' -- Chrome(31+), FF(17+), IE(9+)
* 'mousewheel' -- Chrome, IE(6+), Opera, Safari
* 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother!
* 'DOMMouseScroll' -- FF(0.9.7+) since 2003
*
* So what to do? The is the best:
*
* normalizeWheel.getEventType();
*
* In your event callback, use this code to get sane interpretation of the
* deltas. This code will return an object with properties:
*
* spinX -- normalized spin speed (use for zoom) - x plane
* spinY -- " - y plane
* pixelX -- normalized distance (to pixels) - x plane
* pixelY -- " - y plane
*
* Wheel values are provided by the browser assuming you are using the wheel to
* scroll a web page by a number of lines or pixels (or pages). Values can vary
* significantly on different platforms and browsers, forgetting that you can
* scroll at different speeds. Some devices (like trackpads) emit more events
* at smaller increments with fine granularity, and some emit massive jumps with
* linear speed or acceleration.
*
* This code does its best to normalize the deltas for you:
*
* - spin is trying to normalize how far the wheel was spun (or trackpad
* dragged). This is super useful for zoom support where you want to
* throw away the chunky scroll steps on the PC and make those equal to
* the slow and smooth tiny steps on the Mac. Key data: This code tries to
* resolve a single slow step on a wheel to 1.
*
* - pixel is normalizing the desired scroll delta in pixel units. You'll
* get the crazy differences between browsers, but at least it'll be in
* pixels!
*
* - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This
* should translate to positive value zooming IN, negative zooming OUT.
* This matches the newer 'wheel' event.
*
* Why are there spinX, spinY (or pixels)?
*
* - spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn
* with a mouse. It results in side-scrolling in the browser by default.
*
* - spinY is what you expect -- it's the classic axis of a mouse wheel.
*
* - I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and
* probably is by browsers in conjunction with fancy 3D controllers .. but
* you know.
*
* Implementation info:
*
* Examples of 'wheel' event if you scroll slowly (down) by one step with an
* average mouse:
*
* OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120)
* OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12)
* OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A)
* Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120)
* Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120)
*
* On the trackpad:
*
* OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6)
* OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A)
*
* On other/older browsers.. it's more complicated as there can be multiple and
* also missing delta values.
*
* The 'wheel' event is more standard:
*
* http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
*
* The basics is that it includes a unit, deltaMode (pixels, lines, pages), and
* deltaX, deltaY and deltaZ. Some browsers provide other values to maintain
* backward compatibility with older events. Those other values help us
* better normalize spin speed. Example of what the browsers provide:
*
* | event.wheelDelta | event.detail
* ------------------+------------------+--------------
* Safari v5/OS X | -120 | 0
* Safari v5/Win7 | -120 | 0
* Chrome v17/OS X | -120 | 0
* Chrome v17/Win7 | -120 | 0
* IE9/Win7 | -120 | undefined
* Firefox v4/OS X | undefined | 1
* Firefox v4/Win7 | undefined | 3
*
* from: https://github.com/facebook/fixed-data-table/blob/master/src/vendor_upstream/dom/normalizeWheel.js
* @param {any} event
* @return {any}
*/
Utils.normalizeWheel = function (event) {
var PIXEL_STEP = 10;
var LINE_HEIGHT = 40;
var PAGE_HEIGHT = 800;
// spinX, spinY
var sX = 0;
var sY = 0;
// pixelX, pixelY
var pX = 0;
var pY = 0;
// Legacy
if ('detail' in event) {
sY = event.detail;
}
if ('wheelDelta' in event) {
sY = -event.wheelDelta / 120;
}
if ('wheelDeltaY' in event) {
sY = -event.wheelDeltaY / 120;
}
if ('wheelDeltaX' in event) {
sX = -event.wheelDeltaX / 120;
}
// side scrolling on FF with DOMMouseScroll
if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ('deltaY' in event) {
pY = event.deltaY;
}
if ('deltaX' in event) {
pX = event.deltaX;
}
if ((pX || pY) && event.deltaMode) {
if (event.deltaMode == 1) { // delta in LINE units
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
}
else { // delta in PAGE units
pX *= PAGE_HEIGHT;
pY *= PAGE_HEIGHT;
}
}
// Fall-back if spin cannot be determined
if (pX && !sX) {
sX = (pX < 1) ? -1 : 1;
}
if (pY && !sY) {
sY = (pY < 1) ? -1 : 1;
}
return {
spinX: sX,
spinY: sY,
pixelX: pX,
pixelY: pY
};
};
/**
* from https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript
* @param {Function} func The function to be debounced
* @param {number} wait The time in ms to debounce
* @param {boolean} immediate If it should run immediately or wait for the initial debounce delay
* @return {Function} The debounced function
*/
Utils.debounce = function (func, wait, immediate) {
if (immediate === void 0) { immediate = false; }
// 'private' variable for instance
// The returned function will be able to reference this due to closure.
// Each call to the returned function will share this common timer.
var timeout;
// Calling debounce returns a new anonymous function
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// reference the context and args for the setTimeout function
var context = this;
// Should the function be called now? If immediate is true
// and not already in a timeout then the answer is: Yes
var callNow = immediate && !timeout;
// This is the basic debounce behaviour where you can call this
// function several times, but it will only execute once
// [before or after imposing a delay].
// Each time the returned function is called, the timer starts over.
window.clearTimeout(timeout);
// Set the new timeout
timeout = window.setTimeout(function () {
// Inside the timeout function, clear the timeout variable
// which will let the next execution run when in 'immediate' mode
timeout = null;
// Check if the function already ran with the immediate flag
if (!immediate) {
// Call the original function with apply
// apply lets you define the 'this' object as well as the arguments
// (both captured before setTimeout)
func.apply(context, args);
}
}, wait);
// Immediate mode and no wait timer? Execute the function..
if (callNow) {
func.apply(context, args);
}
};
};
/**
* a user once raised an issue - they said that when you opened a popup (eg context menu)
* and then clicked on a selection checkbox, the popup wasn't closed. this is because the
* popup listens for clicks on the body, however ag-grid WAS stopping propagation on the
* checkbox clicks (so the rows didn't pick them up as row selection selection clicks).
* to get around this, we have a pattern to stop propagation for the purposes of ag-Grid,
* but we still let the event pass back to teh body.
* @param {Event} event
*/
Utils.stopPropagationForAgGrid = function (event) {
event[AG_GRID_STOP_PROPAGATION] = true;
};
Utils.isStopPropagationForAgGrid = function (event) {
return event[AG_GRID_STOP_PROPAGATION] === true;
};
Utils.executeInAWhile = function (funcs) {
this.executeAfter(funcs, 400);
};
Utils.executeNextVMTurn = function (funcs) {
this.executeAfter(funcs, 0);
};
Utils.executeAfter = function (funcs, millis) {
if (funcs.length > 0) {
window.setTimeout(function () {
funcs.forEach(function (func) { return func(); });
}, millis);
}
};
Utils.referenceCompare = function (left, right) {
if (left == null && right == null) {
return true;
}
if (left == null && right) {
return false;
}
if (left && right == null) {
return false;
}
return left === right;
};
Utils.get = function (source, expression, defaultValue) {
if (source == null) {
return defaultValue;
}
var keys = expression.split(".");
var objectToRead = source;
while (keys.length > 1) {
objectToRead = objectToRead[keys.shift()];
if (objectToRead == null) {
return defaultValue;
}
}
var value = objectToRead[keys[0]];
return value != null ? value : defaultValue;
};
Utils.set = function (target, expression, value) {
if (target == null) {
return;
}
var keys = expression.split(".");
var objectToUpdate = target;
while (keys.length > 1) {
objectToUpdate = objectToUpdate[keys.shift()];
if (objectToUpdate == null) {
return;
}
}
objectToUpdate[keys[0]] = value;
};
Utils.addSafePassiveEventListener = function (frameworkOverrides, eElement, event, listener) {
var isPassive = this.includes(Utils.PASSIVE_EVENTS, event);
var isOutsideAngular = this.includes(Utils.OUTSIDE_ANGULAR_EVENTS, event);
var options = isPassive ? { passive: true } : undefined;
if (isOutsideAngular) {
frameworkOverrides.addEventListenerOutsideAngular(eElement, event, listener, options);
}
else {
eElement.addEventListener(event, listener, options);
}
};
/**
* Converts a camelCase string into regular text
* from: https://stackoverflow.com/questions/15369566/putting-space-in-camel-case-string-using-regular-expression
* @param {string} camelCase
* @return {string}
*/
Utils.camelCaseToHumanText = function (camelCase) {
if (!camelCase || camelCase == null) {
return null;
}
var rex = /([A-Z])([A-Z])([a-z])|([a-z])([A-Z])/g;
var words = camelCase.replace(rex, '$1$4 $2$3$5').replace('.', ' ').split(' ');
return words.map(function (word) { return word.substring(0, 1).toUpperCase() + ((word.length > 1) ? word.substring(1, word.length) : ''); }).join(' ');
};
/**
* Displays a message to the browser. this is useful in iPad, where you can't easily see the console.
* so the javascript code can use this to give feedback. this is NOT intended to be called in production.
* it is intended the ag-Grid developer calls this to troubleshoot, but then takes out the calls before
* checking in.
* @param {string} msg
*/
Utils.message = function (msg) {
var eMessage = document.createElement('div');
eMessage.innerHTML = msg;
var eBox = document.querySelector('#__ag__message');
if (!eBox) {
var template = "";
eBox = this.loadTemplate(template);
if (document.body) {
document.body.appendChild(eBox);
}
}
eBox.insertBefore(eMessage, eBox.children[0]);
};
/**
* Gets called by: a) ClientSideNodeManager and b) GroupStage to do sorting.
* when in ClientSideNodeManager we always have indexes (as this sorts the items the
* user provided) but when in GroupStage, the nodes can contain filler nodes that
* don't have order id's
* @param {RowNode[]} rowNodes
* @param {Object} rowNodeOrder
*/
Utils.sortRowNodesByOrder = function (rowNodes, rowNodeOrder) {
if (!rowNodes) {
return;
}
var comparator = function (nodeA, nodeB) {
var positionA = rowNodeOrder[nodeA.id];
var positionB = rowNodeOrder[nodeB.id];
var aHasIndex = positionA !== undefined;
var bHasIndex = positionB !== undefined;
var bothNodesAreUserNodes = aHasIndex && bHasIndex;
var bothNodesAreFillerNodes = !aHasIndex && !bHasIndex;
if (bothNodesAreUserNodes) {
// when comparing two nodes the user has provided, they always
// have indexes
return positionA - positionB;
}
else if (bothNodesAreFillerNodes) {
// when comparing two filler nodes, we have no index to compare them
// against, however we want this sorting to be deterministic, so that
// the rows don't jump around as the user does delta updates. so we
// want the same sort result. so we use the __objectId - which doesn't make sense
// from a sorting point of view, but does give consistent behaviour between
// calls. otherwise groups jump around as delta updates are done.
// note: previously here we used nodeId, however this gave a strange order
// as string ordering of numbers is wrong, so using id based on creation order
// as least gives better looking order.
return nodeA.__objectId - nodeB.__objectId;
}
else if (aHasIndex) {
return 1;
}
return -1;
};
// check if the list first needs sorting
var rowNodeA;
var rowNodeB;
var atLeastOneOutOfOrder = false;
for (var i = 0; i < rowNodes.length - 1; i++) {
rowNodeA = rowNodes[i];
rowNodeB = rowNodes[i + 1];
if (comparator(rowNodeA, rowNodeB) > 0) {
atLeastOneOutOfOrder = true;
break;
}
}
if (atLeastOneOutOfOrder) {
rowNodes.sort(comparator);
}
};
Utils.fuzzyCheckStrings = function (inputValues, validValues, allSuggestions) {
var _this = this;
var fuzzyMatches = {};
var invalidInputs = inputValues.filter(function (inputValue) {
return !validValues.some(function (validValue) { return validValue === inputValue; });
});
if (invalidInputs.length > 0) {
invalidInputs.forEach(function (invalidInput) {
return fuzzyMatches[invalidInput] = _this.fuzzySuggestions(invalidInput, allSuggestions);
});
}
return fuzzyMatches;
};
/**
*
* @param {String} inputValue The value to be compared against a list of strings
* @param allSuggestions The list of strings to be compared against
* @param hideIrrelevant By default, fuzzy suggestions will just sort the allSuggestions list, set this to true
* to filter out the irrelevant values
* @param weighted Set this to true, to make letters matched in the order they were typed have priority in the results.
*/
Utils.fuzzySuggestions = function (inputValue, allSuggestions, hideIrrelevant, weighted) {
var search = weighted ? _.string_weighted_distances : _.string_distances;
var thisSuggestions = allSuggestions.map(function (text) { return ({
value: text,
relevance: search(inputValue.toLowerCase(), text.toLocaleLowerCase())
}); });
thisSuggestions.sort(function (a, b) { return b.relevance - a.relevance; });
if (hideIrrelevant) {
thisSuggestions = thisSuggestions.filter(function (suggestion) { return suggestion.relevance !== 0; });
}
return thisSuggestions.map(function (suggestion) { return suggestion.value; });
};
/**
* Algorithm to do fuzzy search
* from https://stackoverflow.com/questions/23305000/javascript-fuzzy-search-that-makes-sense
* @param {string} from
* @return {[]}
*/
Utils.get_bigrams = function (from) {
var s = from.toLowerCase();
var v = new Array(s.length - 1);
var i;
var j;
var ref;
for (i = j = 0, ref = v.length; j <= ref; i = j += 1) {
v[i] = s.slice(i, i + 2);
}
return v;
};
Utils.string_distances = function (str1, str2) {
if (str1.length === 0 && str2.length === 0) {
return 0;
}
var pairs1 = _.get_bigrams(str1);
var pairs2 = _.get_bigrams(str2);
var union = pairs1.length + pairs2.length;
var hit_count = 0;
var j;
var len;
for (j = 0, len = pairs1.length; j < len; j++) {
var x = pairs1[j];
var k = void 0;
var len1 = void 0;
for (k = 0, len1 = pairs2.length; k < len1; k++) {
var y = pairs2[k];
if (x === y) {
hit_count++;
}
}
}
return hit_count > 0 ? (2 * hit_count) / union : 0;
};
Utils.string_weighted_distances = function (str1, str2) {
var a = str1.replace(/\s/g, '');
var b = str2.replace(/\s/g, '');
var weight = 0;
var lastIndex = 0;
for (var i = 0; i < a.length; i++) {
var idx = b.indexOf(a[i]);
if (idx === -1) {
continue;
}
lastIndex = idx;
weight += ((b.length - lastIndex) * 100) / b.length;
weight *= weight;
}
return weight;
};
Utils.isNumpadDelWithNumlockOnForEdgeOrIe = function (event) {
if (Utils.isBrowserEdge() || Utils.isBrowserIE()) {
return event.key === Utils.NUMPAD_DEL_NUMLOCK_ON_KEY &&
event.charCode === Utils.NUMPAD_DEL_NUMLOCK_ON_CHARCODE;
}
return false;
};
/**
* cell renderers are used in a few places. they bind to dom slightly differently to other cell renderes as they
* can return back strings (instead of html elemnt) in the getGui() method. common code placed here to handle that.
* @param {Promise} cellRendererPromise
* @param {HTMLElement} eTarget
*/
Utils.bindCellRendererToHtmlElement = function (cellRendererPromise, eTarget) {
cellRendererPromise.then(function (cellRenderer) {
var gui = cellRenderer.getGui();
if (gui != null) {
if (typeof gui == 'object') {
eTarget.appendChild(gui);
}
else {
eTarget.innerHTML = gui;
}
}
});
};
Utils.convertToSet = function (list) {
var set = new Set();
list.forEach(function (x) { return set.add(x); });
return set;
};
Utils.deepFreeze = function (object) {
var _this = this;
Object.freeze(object);
_.values(object).filter(function (v) { return v != null; }).forEach(function (v) {
if (typeof v === 'object' || typeof v === 'function') {
_this.deepFreeze(v);
}
});
return object;
};
Utils.PASSIVE_EVENTS = ['touchstart', 'touchend', 'touchmove', 'touchcancel'];
Utils.OUTSIDE_ANGULAR_EVENTS = ['mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
Utils.PRINTABLE_CHARACTERS = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!"£$%^&*()_+-=[];\'#,./\\|<>?:@~{}';
Utils.NUMPAD_DEL_NUMLOCK_ON_KEY = 'Del';
Utils.NUMPAD_DEL_NUMLOCK_ON_CHARCODE = 46;
Utils.doOnceFlags = {};
Utils.supports = {};
Utils.isEventSupported = (function () {
var tags = {
select: 'input',
change: 'input',
submit: 'form',
reset: 'form',
error: 'img',
load: 'img',
abort: 'img'
};
var isEventSupported = function (eventName) {
if (typeof Utils.supports[eventName] === 'boolean') {
return Utils.supports[eventName];
}
var el = document.createElement(tags[eventName] || 'div');
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return Utils.supports[eventName] = isSupported;
};
return isEventSupported;
})();
Utils.areEqual = function (a, b) {
return a.length === b.length && a.every(function (value, index) { return b[index] === value; });
};
Utils.keys = function (map) {
var keys = [];
map.forEach(function (_, key) { return keys.push(key); });
return keys;
};
Utils.values = function (object) { return Object.keys(object).map(function (key) { return object[key]; }); };
Utils.includes = function (array, value) { return array.indexOf(value) > -1; };
Utils.compose = function () {
var fns = [];
for (var _i = 0; _i < arguments.length; _i++) {
fns[_i] = arguments[_i];
}
return function (arg) { return fns.reduce(function (composed, f) { return f(composed); }, arg); };
};
Utils.decToHex = function (number, bytes) {
var hex = '';
for (var i = 0; i < bytes; i++) {
hex += String.fromCharCode(number & 0xff);
number >>>= 8;
}
return hex;
};
/**
* It encodes any string in UTF-8 format
* taken from https://github.com/mathiasbynens/utf8.js
* @param {string} s
* @returns {string}
*/
Utils.utf8_encode = function (s) {
var stringFromCharCode = String.fromCharCode;
function ucs2decode(string) {
var output = [];
var counter = 0;
var length = string.length;
var value;
var extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
}
else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
}
else {
output.push(value);
}
}
return output;
}
function checkScalarValue(codePoint) {
if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
throw Error('Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
' is not a scalar value');
}
}
function createByte(codePoint, shift) {
return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
}
function encodeCodePoint(codePoint) {
if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
return stringFromCharCode(codePoint);
}
var symbol = '';
if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
}
else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
checkScalarValue(codePoint);
symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
symbol += createByte(codePoint, 6);
}
else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
symbol += createByte(codePoint, 12);
symbol += createByte(codePoint, 6);
}
symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
return symbol;
}
var codePoints = ucs2decode(s);
var length = codePoints.length;
var index = -1;
var codePoint;
var byteString = '';
while (++index < length) {
codePoint = codePoints[index];
byteString += encodeCodePoint(codePoint);
}
return byteString;
};
Utils.deepCloneObject = function (object) { return JSON.parse(JSON.stringify(object)); };
Utils.getProperty = function (object, key) { return object[key]; };
Utils.setProperty = function (object, key, value) { return object[key] = value; };
//
// IMPORTANT NOTE!
//
// The comments below provide one example of how each icon is used, so that you can find
// an instance of it in the UI and see what it looks like in the UI. Many icons are used
// in multiple places.
//
Utils.iconNameClassMap = {
// header column group shown when expanded (click to contract)
columnGroupOpened: 'expanded',
// header column group shown when contracted (click to expand)
columnGroupClosed: 'contracted',
// tool panel column group contracted (click to expand)
columnSelectClosed: 'tree-closed',
// tool panel column group expanded (click to contract)
columnSelectOpen: 'tree-open',
// column tool panel header expand/collapse all button, shown when some children are expanded and
// others are collapsed
columnSelectIndeterminate: 'tree-indeterminate',
// shown on ghost icon while dragging column to the side of the grid to pin
columnMovePin: 'pin',
// ??? doesn't seem to be used?
columnMoveAdd: 'plus',
// shown on ghost icon while dragging over part of the page that is not a drop zone
columnMoveHide: 'eye-slash',
// shown on ghost icon while dragging columns to reorder
columnMoveMove: 'arrows',
// animating icon shown when dragging a column to the right of the grid causes horizontal scrolling
columnMoveLeft: 'left',
// animating icon shown when dragging a column to the left of the grid causes horizontal scrolling
columnMoveRight: 'right',
// shown on ghost icon while dragging over Row Groups drop zone
columnMoveGroup: 'group',
// shown on ghost icon while dragging over Values drop zone
columnMoveValue: 'aggregation',
// shown on ghost icon while dragging over pivot drop zone
columnMovePivot: 'pivot',
// shown on ghost icon while dragging over drop zone that doesn't support it, e.g.
// string column over aggregation drop zone
dropNotAllowed: 'not-allowed',
// shown on row group when contracted (click to expand)
groupContracted: 'contracted',
// shown on row group when expanded (click to contract)
groupExpanded: 'expanded',
// context menu chart item
chart: 'chart',
// chart window title bar
close: 'cross',
// X (remove) on column 'pill' after adding it to a drop zone list
cancel: 'cancel',
// indicates the currently active pin state in the "Pin column" sub-menu of the column menu
check: 'tick',
// the following checkbox-* items are for checkboxes on themes that don't use a
// native
checkboxChecked: 'checkbox-checked',
checkboxUnchecked: 'checkbox-unchecked',
checkboxIndeterminate: 'checkbox-indeterminate',
checkboxCheckedReadOnly: 'checkbox-checked-readonly',
checkboxUncheckedReadOnly: 'checkbox-unchecked-readonly',
checkboxIndeterminateReadOnly: 'checkbox-indeterminate-readonly',
// "go to first" button in pagination controls
first: 'first',
// "go to previous" button in pagination controls
previous: 'previous',
// "go to next" button in pagination controls
next: 'next',
// "go to last" button in pagination controls
last: 'last',
// shown on top right of chart when chart is linked to range data (click to unlink)
linked: 'linked',
// shown on top right of chart when chart is not linked to range data (click to link)
unlinked: 'unlinked',
// "Choose colour" button on chart settings tab
colorPicker: 'color-picker',
// the following radio-button-* items are for radio buttons on themes that don't use a
// native
radioButtonOn: 'radio-button-on',
radioButtonOff: 'radio-button-off',
// rotating spinner shown by the loading cell renderer
groupLoading: 'loading',
// ??? doesn't seem to be used?
data: 'data',
// button to launch enterprise column menu
menu: 'menu',
// filter tool panel tab
filter: 'filter',
// column tool panel tab
columns: 'columns',
// button in chart regular size window title bar (click to maximise)
maximize: 'maximize',
// button in chart maximised window title bar (click to make regular size)
minimize: 'minimize',
// "Pin column" item in column header menu
menuPin: 'pin',
// "Value aggregation" column menu item (shown on numeric columns when grouping is active)"
menuValue: 'aggregation',
// "Group by {column-name}" item in column header menu
menuAddRowGroup: 'group',
// "Un-Group by {column-name}" item in column header menu
menuRemoveRowGroup: 'group',
// context menu copy item
clipboardCopy: 'copy',
// ??? doesn't seem toi be used?
clipboardCut: 'cut',
// context menu paste item
clipboardPaste: 'paste',
// identifies the pivot drop zone
pivotPanel: 'pivot',
// "Row groups" drop zone in column tool panel
rowGroupPanel: 'group',
// columns tool panel Values drop zone
valuePanel: 'aggregation',
// drag handle used to pick up draggable columns
columnDrag: 'grip',
// drag handle used to pick up draggable rows
rowDrag: 'grip',
// context menu export item
save: 'save',
// version of small-right used in RTL mode
smallLeft: 'small-left',
// separater between column 'pills' when you add multiple columns to the header drop zone
smallRight: 'small-right',
// ??? doesn't seem to be used?
smallUp: 'small-up',
// ??? doesn't seem to be used?
smallDown: 'small-down',
// show on column header when column is sorted ascending
sortAscending: 'asc',
// show on column header when column is sorted descending
sortDescending: 'desc',
// show on column header when column has no sort, only when enabled with gridOptions.unSortIcon=true
sortUnSort: 'none'
};
return Utils;
}());
var NumberSequence = /** @class */ (function () {
function NumberSequence(initValue, step) {
if (initValue === void 0) { initValue = 0; }
if (step === void 0) { step = 1; }
this.nextValue = initValue;
this.step = step;
}
NumberSequence.prototype.next = function () {
var valToReturn = this.nextValue;
this.nextValue += this.step;
return valToReturn;
};
NumberSequence.prototype.peek = function () {
return this.nextValue;
};
NumberSequence.prototype.skip = function (count) {
this.nextValue += count;
};
return NumberSequence;
}());
var _ = Utils;
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var PromiseStatus;
(function (PromiseStatus) {
PromiseStatus[PromiseStatus["IN_PROGRESS"] = 0] = "IN_PROGRESS";
PromiseStatus[PromiseStatus["RESOLVED"] = 1] = "RESOLVED";
})(PromiseStatus || (PromiseStatus = {}));
var Promise = /** @class */ (function () {
function Promise(callback) {
this.status = PromiseStatus.IN_PROGRESS;
this.resolution = null;
this.listOfWaiters = [];
callback(this.onDone.bind(this), this.onReject.bind(this));
}
Promise.all = function (toCombine) {
return new Promise(function (resolve) {
var combinedValues = [];
var remainingToResolve = toCombine.length;
toCombine.forEach(function (source, index) {
source.then(function (sourceResolved) {
remainingToResolve--;
combinedValues[index] = sourceResolved;
if (remainingToResolve == 0) {
resolve(combinedValues);
}
});
combinedValues.push(null); // spl todo: review with Alberto - why?
});
});
};
Promise.resolve = function (value) {
return new Promise(function (resolve) { return resolve(value); });
};
Promise.external = function () {
var capture;
var promise = new Promise(function (resolve) {
capture = resolve;
});
return {
promise: promise,
resolve: function (value) {
capture(value);
}
};
};
Promise.prototype.then = function (func) {
if (this.status === PromiseStatus.IN_PROGRESS) {
this.listOfWaiters.push(func);
}
else {
func(this.resolution);
}
};
Promise.prototype.firstOneOnly = function (func) {
if (this.status === PromiseStatus.IN_PROGRESS) {
if (this.listOfWaiters.length === 0) {
this.listOfWaiters.push(func);
}
}
else {
func(this.resolution);
}
};
Promise.prototype.map = function (adapter) {
var _this = this;
return new Promise(function (resolve) {
_this.then(function (unmapped) {
resolve(adapter(unmapped));
});
});
};
Promise.prototype.resolveNow = function (ifNotResolvedValue, ifResolved) {
if (this.status == PromiseStatus.IN_PROGRESS) {
return ifNotResolvedValue;
}
return ifResolved(this.resolution);
};
Promise.prototype.onDone = function (value) {
this.status = PromiseStatus.RESOLVED;
this.resolution = value;
this.listOfWaiters.forEach(function (waiter) { return waiter(value); });
};
Promise.prototype.onReject = function (params) {
console.warn('TBI');
};
return Promise;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var ColumnKeyCreator = /** @class */ (function () {
function ColumnKeyCreator() {
this.existingKeys = {};
}
ColumnKeyCreator.prototype.addExistingKeys = function (keys) {
for (var i = 0; i < keys.length; i++) {
this.existingKeys[keys[i]] = true;
}
};
ColumnKeyCreator.prototype.getUniqueKey = function (colId, colField) {
// in case user passed in number for colId, convert to string
colId = _.toStringOrNull(colId);
var count = 0;
while (true) {
var idToTry = void 0;
if (colId) {
idToTry = colId;
if (count !== 0) {
idToTry += '_' + count;
}
}
else if (colField) {
idToTry = colField;
if (count !== 0) {
idToTry += '_' + count;
}
}
else {
idToTry = '' + count;
}
if (!this.existingKeys[idToTry]) {
this.existingKeys[idToTry] = true;
return idToTry;
}
count++;
}
};
return ColumnKeyCreator;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var Context = /** @class */ (function () {
function Context(params, logger) {
this.beanWrappers = {};
this.componentsMappedByName = {};
this.destroyed = false;
if (!params || !params.beanClasses) {
return;
}
this.contextParams = params;
this.logger = logger;
this.logger.log(">> creating ag-Application Context");
this.setupComponents();
this.createBeans();
var beanInstances = this.getBeanInstances();
this.wireBeans(beanInstances);
this.logger.log(">> ag-Application Context ready - component is alive");
}
Context.prototype.getBeanInstances = function () {
return _.values(this.beanWrappers).map(function (beanEntry) { return beanEntry.beanInstance; });
};
Context.prototype.setupComponents = function () {
var _this = this;
if (this.contextParams.components) {
this.contextParams.components.forEach(function (componentMeta) { return _this.addComponent(componentMeta); });
}
};
Context.prototype.addComponent = function (componentMeta) {
// get name of the class as a string
// let className = _.getNameOfClass(ComponentClass);
// insert a dash after every capital letter
// let classEscaped = className.replace(/([A-Z])/g, "-$1").toLowerCase();
var classEscaped = componentMeta.componentName.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
// put all to upper case
var classUpperCase = classEscaped.toUpperCase();
// finally store
this.componentsMappedByName[classUpperCase] = componentMeta.componentClass;
};
Context.prototype.createComponentFromElement = function (element, afterPreCreateCallback) {
var key = element.nodeName;
return this.createComponent(key, afterPreCreateCallback);
};
Context.prototype.createComponent = function (key, afterPreCreateCallback) {
if (this.componentsMappedByName && this.componentsMappedByName[key]) {
var newComponent = new this.componentsMappedByName[key]();
this.wireBean(newComponent, afterPreCreateCallback);
return newComponent;
}
return null;
};
Context.prototype.wireBean = function (bean, afterPreCreateCallback) {
if (!bean) {
throw Error("Can't wire to bean since it is null");
}
this.wireBeans([bean], afterPreCreateCallback);
};
Context.prototype.wireBeans = function (beanInstances, afterPreCreateCallback) {
this.autoWireBeans(beanInstances);
this.methodWireBeans(beanInstances);
this.callLifeCycleMethods(beanInstances, 'preConstructMethods');
// the callback sets the attributes, so the component has access to attributes
// before postConstruct methods in the component are executed
if (_.exists(afterPreCreateCallback)) {
beanInstances.forEach(afterPreCreateCallback);
}
this.callLifeCycleMethods(beanInstances, 'postConstructMethods');
};
Context.prototype.createBeans = function () {
var _this = this;
// register all normal beans
this.contextParams.beanClasses.forEach(this.createBeanWrapper.bind(this));
// register override beans, these will overwrite beans above of same name
// instantiate all beans - overridden beans will be left out
_.iterateObject(this.beanWrappers, function (key, beanEntry) {
var constructorParamsMeta;
if (beanEntry.bean.__agBeanMetaData && beanEntry.bean.__agBeanMetaData.autowireMethods && beanEntry.bean.__agBeanMetaData.autowireMethods.agConstructor) {
constructorParamsMeta = beanEntry.bean.__agBeanMetaData.autowireMethods.agConstructor;
}
var constructorParams = _this.getBeansForParameters(constructorParamsMeta, beanEntry.bean.name);
var newInstance = applyToConstructor(beanEntry.bean, constructorParams);
beanEntry.beanInstance = newInstance;
});
var createdBeanNames = Object.keys(this.beanWrappers).join(', ');
this.logger.log("created beans: " + createdBeanNames);
};
// tslint:disable-next-line
Context.prototype.createBeanWrapper = function (Bean) {
var metaData = Bean.__agBeanMetaData;
if (!metaData) {
var beanName = void 0;
if (Bean.prototype.constructor) {
beanName = Bean.prototype.constructor.name;
}
else {
beanName = "" + Bean;
}
console.error("context item " + beanName + " is not a bean");
return;
}
var beanEntry = {
bean: Bean,
beanInstance: null,
beanName: metaData.beanName
};
this.beanWrappers[metaData.beanName] = beanEntry;
};
Context.prototype.autoWireBeans = function (beanInstances) {
var _this = this;
beanInstances.forEach(function (beanInstance) {
_this.forEachMetaDataInHierarchy(beanInstance, function (metaData, beanName) {
var attributes = metaData.agClassAttributes;
if (!attributes) {
return;
}
attributes.forEach(function (attribute) {
var otherBean = _this.lookupBeanInstance(beanName, attribute.beanName, attribute.optional);
beanInstance[attribute.attributeName] = otherBean;
});
});
});
};
Context.prototype.methodWireBeans = function (beanInstances) {
var _this = this;
beanInstances.forEach(function (beanInstance) {
_this.forEachMetaDataInHierarchy(beanInstance, function (metaData, beanName) {
_.iterateObject(metaData.autowireMethods, function (methodName, wireParams) {
// skip constructor, as this is dealt with elsewhere
if (methodName === "agConstructor") {
return;
}
var initParams = _this.getBeansForParameters(wireParams, beanName);
beanInstance[methodName].apply(beanInstance, initParams);
});
});
});
};
Context.prototype.forEachMetaDataInHierarchy = function (beanInstance, callback) {
var prototype = Object.getPrototypeOf(beanInstance);
while (prototype != null) {
var constructor = prototype.constructor;
if (constructor.hasOwnProperty('__agBeanMetaData')) {
var metaData = constructor.__agBeanMetaData;
var beanName = this.getBeanName(constructor);
callback(metaData, beanName);
}
prototype = Object.getPrototypeOf(prototype);
}
};
Context.prototype.getBeanName = function (constructor) {
if (constructor.__agBeanMetaData && constructor.__agBeanMetaData.beanName) {
return constructor.__agBeanMetaData.beanName;
}
var constructorString = constructor.toString();
var beanName = constructorString.substring(9, constructorString.indexOf("("));
return beanName;
};
Context.prototype.getBeansForParameters = function (parameters, beanName) {
var _this = this;
var beansList = [];
if (parameters) {
_.iterateObject(parameters, function (paramIndex, otherBeanName) {
var otherBean = _this.lookupBeanInstance(beanName, otherBeanName);
beansList[Number(paramIndex)] = otherBean;
});
}
return beansList;
};
Context.prototype.lookupBeanInstance = function (wiringBean, beanName, optional) {
if (optional === void 0) { optional = false; }
if (beanName === "context") {
return this;
}
else if (this.contextParams.providedBeanInstances && this.contextParams.providedBeanInstances.hasOwnProperty(beanName)) {
return this.contextParams.providedBeanInstances[beanName];
}
else {
var beanEntry = this.beanWrappers[beanName];
if (beanEntry) {
return beanEntry.beanInstance;
}
if (!optional) {
console.error("ag-Grid: unable to find bean reference " + beanName + " while initialising " + wiringBean);
}
return null;
}
};
Context.prototype.callLifeCycleMethods = function (beanInstances, lifeCycleMethod) {
var _this = this;
beanInstances.forEach(function (beanInstance) {
_this.forEachMetaDataInHierarchy(beanInstance, function (metaData) {
var methods = metaData[lifeCycleMethod];
if (!methods) {
return;
}
methods.forEach(function (methodName) { return beanInstance[methodName](); });
});
});
};
Context.prototype.getBean = function (name) {
return this.lookupBeanInstance("getBean", name, true);
};
Context.prototype.destroy = function () {
// should only be able to destroy once
if (this.destroyed) {
return;
}
this.logger.log(">> Shutting down ag-Application Context");
var beanInstances = this.getBeanInstances();
this.callLifeCycleMethods(beanInstances, 'preDestroyMethods');
this.contextParams.providedBeanInstances = null;
this.destroyed = true;
this.logger.log(">> ag-Application Context shut down - component is dead");
};
return Context;
}());
// taken from: http://stackoverflow.com/questions/3362471/how-can-i-call-a-javascript-constructor-using-call-or-apply
// allows calling 'apply' on a constructor
function applyToConstructor(constructor, argArray) {
var args = [null].concat(argArray);
var factoryFunction = constructor.bind.apply(constructor, args);
return new factoryFunction();
}
function PreConstruct(target, methodName, descriptor) {
var props = getOrCreateProps(target.constructor);
if (!props.postConstructMethods) {
props.preConstructMethods = [];
}
props.preConstructMethods.push(methodName);
}
function PostConstruct(target, methodName, descriptor) {
var props = getOrCreateProps(target.constructor);
if (!props.postConstructMethods) {
props.postConstructMethods = [];
}
props.postConstructMethods.push(methodName);
}
function PreDestroy(target, methodName, descriptor) {
var props = getOrCreateProps(target.constructor);
if (!props.preDestroyMethods) {
props.preDestroyMethods = [];
}
props.preDestroyMethods.push(methodName);
}
function Bean(beanName) {
return function (classConstructor) {
var props = getOrCreateProps(classConstructor);
props.beanName = beanName;
};
}
function Autowired(name) {
return function (target, propertyKey, descriptor) {
autowiredFunc(target, name, false, target, propertyKey, null);
};
}
function Optional(name) {
return function (target, propertyKey, descriptor) {
autowiredFunc(target, name, true, target, propertyKey, null);
};
}
function autowiredFunc(target, name, optional, classPrototype, methodOrAttributeName, index) {
if (name === null) {
console.error("ag-Grid: Autowired name should not be null");
return;
}
if (typeof index === "number") {
console.error("ag-Grid: Autowired should be on an attribute");
return;
}
// it's an attribute on the class
var props = getOrCreateProps(target.constructor);
if (!props.agClassAttributes) {
props.agClassAttributes = [];
}
props.agClassAttributes.push({
attributeName: methodOrAttributeName,
beanName: name,
optional: optional
});
}
function Qualifier(name) {
return function (classPrototype, methodOrAttributeName, index) {
var constructor = typeof classPrototype == "function" ? classPrototype : classPrototype.constructor;
var props;
if (typeof index === "number") {
// it's a parameter on a method
var methodName = void 0;
if (methodOrAttributeName) {
props = getOrCreateProps(constructor);
methodName = methodOrAttributeName;
}
else {
props = getOrCreateProps(constructor);
methodName = "agConstructor";
}
if (!props.autowireMethods) {
props.autowireMethods = {};
}
if (!props.autowireMethods[methodName]) {
props.autowireMethods[methodName] = {};
}
props.autowireMethods[methodName][index] = name;
}
};
}
function getOrCreateProps(target) {
if (!target.hasOwnProperty("__agBeanMetaData")) {
target.__agBeanMetaData = {};
}
return target.__agBeanMetaData;
}
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (undefined && undefined.__decorate) || function (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;
};
var __param = (undefined && undefined.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var EventService = /** @class */ (function () {
function EventService() {
this.allSyncListeners = new Map();
this.allAsyncListeners = new Map();
this.globalSyncListeners = new Set();
this.globalAsyncListeners = new Set();
this.asyncFunctionsQueue = [];
this.scheduled = false;
// using an object performs better than a Set for the number of different events we have
this.firedEvents = {};
}
EventService_1 = EventService;
// because this class is used both inside the context and outside the context, we do not
// use autowired attributes, as that would be confusing, as sometimes the attributes
// would be wired, and sometimes not.
//
// the global event servers used by ag-Grid is autowired by the context once, and this
// setBeans method gets called once.
//
// the times when this class is used outside of the context (eg RowNode has an instance of this
// class) then it is not a bean, and this setBeans method is not called.
EventService.prototype.setBeans = function (loggerFactory, gridOptionsWrapper, globalEventListener) {
if (globalEventListener === void 0) { globalEventListener = null; }
this.logger = loggerFactory.create('EventService');
if (globalEventListener) {
var async = gridOptionsWrapper.useAsyncEvents();
this.addGlobalListener(globalEventListener, async);
}
};
EventService.prototype.getListeners = function (eventType, async) {
var listenerMap = async ? this.allAsyncListeners : this.allSyncListeners;
var listeners = listenerMap.get(eventType);
if (!listeners) {
listeners = new Set();
listenerMap.set(eventType, listeners);
}
return listeners;
};
EventService.prototype.addEventListener = function (eventType, listener, async) {
if (async === void 0) { async = false; }
this.getListeners(eventType, async).add(listener);
};
EventService.prototype.removeEventListener = function (eventType, listener, async) {
if (async === void 0) { async = false; }
this.getListeners(eventType, async).delete(listener);
};
// for some events, it's important that the model gets to hear about them before the view,
// as the model may need to update before the view works on the info. if you register
// via this method, you get notified before the view parts
EventService.prototype.addModalPriorityEventListener = function (eventType, listener, async) {
if (async === void 0) { async = false; }
this.addEventListener(eventType + EventService_1.PRIORITY, listener, async);
};
EventService.prototype.addGlobalListener = function (listener, async) {
if (async === void 0) { async = false; }
(async ? this.globalAsyncListeners : this.globalSyncListeners).add(listener);
};
EventService.prototype.removeGlobalListener = function (listener, async) {
if (async === void 0) { async = false; }
(async ? this.globalAsyncListeners : this.globalSyncListeners).delete(listener);
};
EventService.prototype.dispatchEvent = function (event) {
this.dispatchToListeners(event, true);
this.dispatchToListeners(event, false);
this.firedEvents[event.type] = true;
};
EventService.prototype.dispatchEventOnce = function (event) {
if (!this.firedEvents[event.type]) {
this.dispatchEvent(event);
}
};
EventService.prototype.dispatchToListeners = function (event, async) {
var _this = this;
var eventType = event.type;
var processEventListeners = function (listeners) { return listeners.forEach(function (listener) {
if (async) {
_this.dispatchAsync(function () { return listener(event); });
}
else {
listener(event);
}
}); };
// PRIORITY events should be processed first
processEventListeners(this.getListeners(eventType + EventService_1.PRIORITY, async));
processEventListeners(this.getListeners(eventType, async));
var globalListeners = async ? this.globalAsyncListeners : this.globalSyncListeners;
globalListeners.forEach(function (listener) {
if (async) {
_this.dispatchAsync(function () { return listener(eventType, event); });
}
else {
listener(eventType, event);
}
});
};
// this gets called inside the grid's thread, for each event that it
// wants to set async. the grid then batches the events into one setTimeout()
// because setTimeout() is an expensive operation. ideally we would have
// each event in it's own setTimeout(), but we batch for performance.
EventService.prototype.dispatchAsync = function (func) {
// add to the queue for executing later in the next VM turn
this.asyncFunctionsQueue.push(func);
// check if timeout is already scheduled. the first time the grid calls
// this within it's thread turn, this should be false, so it will schedule
// the 'flush queue' method the first time it comes here. then the flag is
// set to 'true' so it will know it's already scheduled for subsequent calls.
if (!this.scheduled) {
// if not scheduled, schedule one
window.setTimeout(this.flushAsyncQueue.bind(this), 0);
// mark that it is scheduled
this.scheduled = true;
}
};
// this happens in the next VM turn only, and empties the queue of events
EventService.prototype.flushAsyncQueue = function () {
this.scheduled = false;
// we take a copy, because the event listener could be using
// the grid, which would cause more events, which would be potentially
// added to the queue, so safe to take a copy, the new events will
// get executed in a later VM turn rather than risk updating the
// queue as we are flushing it.
var queueCopy = this.asyncFunctionsQueue.slice();
this.asyncFunctionsQueue = [];
// execute the queue
queueCopy.forEach(function (func) { return func(); });
};
var EventService_1;
// this is an old idea niall had, should really take it out, was to do with ordering who gets to process
// events first, to give model and service objects preference over the view
EventService.PRIORITY = '-P1';
__decorate([
__param(0, Qualifier('loggerFactory')),
__param(1, Qualifier('gridOptionsWrapper')),
__param(2, Qualifier('globalEventListener'))
], EventService.prototype, "setBeans", null);
EventService = EventService_1 = __decorate([
Bean('eventService')
], EventService);
return EventService;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var ModuleNames;
(function (ModuleNames) {
// when using modules, user references this
ModuleNames["CommunityCoreModule"] = "@ag-grid-community/core";
// when not using modules, user references this
ModuleNames["CommunityAllModules"] = "@ag-grid-community/all";
// community modules
ModuleNames["InfiniteRowModelModule"] = "@ag-grid-community/infinite-row-model";
ModuleNames["ClientSideRowModelModule"] = "@ag-grid-community/client-side-row-model";
ModuleNames["CsvExportModule"] = "@ag-grid-community/csv-export";
ModuleNames["RowNodeCache"] = "@ag-grid-community/row-node-cache";
// enterprise core - users never import on this, but other enterprise modules do
ModuleNames["EnterpriseCoreModule"] = "@ag-grid-enterprise/core";
// when not using modules, user references this
ModuleNames["EnterpriseAllModules"] = "@ag-grid-enterprise/all";
// enterprise modules
ModuleNames["RowGroupingModule"] = "@ag-grid-enterprise/row-grouping";
ModuleNames["ColumnToolPanelModule"] = "@ag-grid-enterprise/column-tool-panel";
ModuleNames["FiltersToolPanelModule"] = "@ag-grid-enterprise/filters-tool-panel";
ModuleNames["MenuModule"] = "@ag-grid-enterprise/menu";
ModuleNames["SetFilterModule"] = "@ag-grid-enterprise/set-filter";
ModuleNames["StatusBarModule"] = "@ag-grid-enterprise/status-bar";
ModuleNames["SideBarModule"] = "@ag-grid-enterprise/side-bar";
ModuleNames["RangeSelectionModule"] = "@ag-grid-enterprise/range-selection";
ModuleNames["MasterDetailModule"] = "@ag-grid-enterprise/master-detail";
ModuleNames["RichSelectModule"] = "@ag-grid-enterprise/rich-select";
ModuleNames["GridChartsModule"] = "@ag-grid-enterprise/charts";
ModuleNames["ViewportRowModelModule"] = "@ag-grid-enterprise/viewport-row-model";
ModuleNames["ServerSideRowModelModule"] = "@ag-grid-enterprise/server-side-row-model";
ModuleNames["ExcelExportModule"] = "@ag-grid-enterprise/excel-export";
ModuleNames["ClipboardModule"] = "@ag-grid-enterprise/clipboard";
// framework wrappers currently don't provide beans, comps etc, so no need to be modules,
// however i argue they should be as in theory they 'could' provide beans etc
ModuleNames["AngularModule"] = "@ag-grid-community/angular";
ModuleNames["ReactModule"] = "@ag-grid-community/react";
ModuleNames["VueModule"] = "@ag-grid-community/vue";
ModuleNames["PolymerModule"] = "@ag-grid-community/polymer";
// and then this, which is definitely not a grid module, as it should not have any dependency
// on the grid (ie shouldn't even reference the Module interface)
// ChartsModule = "@ag-grid-community/charts-core",
})(ModuleNames || (ModuleNames = {}));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var ModuleRegistry = /** @class */ (function () {
function ModuleRegistry() {
}
ModuleRegistry.register = function (module) {
ModuleRegistry.modulesMap[module.moduleName] = module;
};
ModuleRegistry.registerModules = function (modules) {
if (!modules) {
return;
}
modules.forEach(ModuleRegistry.register);
};
ModuleRegistry.assertRegistered = function (moduleName, reason) {
if (this.isRegistered(moduleName)) {
return true;
}
var warningKey = reason + moduleName;
var warningMessage = "ag-Grid: unable to use " + reason + " as module " + moduleName + " is not present. "
+ ("You need to load the module with: import \"" + moduleName + "\"");
_.doOnce(function () {
console.warn(warningMessage);
}, warningKey);
return false;
};
ModuleRegistry.isRegistered = function (moduleName) {
return !!ModuleRegistry.modulesMap[moduleName];
};
ModuleRegistry.getRegisteredModules = function () {
return _.values(ModuleRegistry.modulesMap);
};
// having in a map a) removes duplicates and b) allows fast lookup
ModuleRegistry.modulesMap = {};
return ModuleRegistry;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate$1 = (undefined && undefined.__decorate) || function (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;
};
// Wrapper around a user provide column definition. The grid treats the column definition as ready only.
// This class contains all the runtime information about a column, plus some logic (the definition has no logic).
// This class implements both interfaces ColumnGroupChild and OriginalColumnGroupChild as the class can
// appear as a child of either the original tree or the displayed tree. However the relevant group classes
// for each type only implements one, as each group can only appear in it's associated tree (eg OriginalColumnGroup
// can only appear in OriginalColumn tree).
var Column = /** @class */ (function () {
function Column(colDef, userProvidedColDef, colId, primary) {
this.moving = false;
this.menuVisible = false;
this.filterActive = false;
this.eventService = new EventService();
this.rowGroupActive = false;
this.pivotActive = false;
this.aggregationActive = false;
this.colDef = colDef;
this.userProvidedColDef = userProvidedColDef;
this.visible = !colDef.hide;
this.sort = colDef.sort;
this.sortedAt = colDef.sortedAt;
this.colId = colId;
this.primary = primary;
}
// gets called when user provides an alternative colDef, eg
Column.prototype.setColDef = function (colDef, userProvidedColDef) {
this.colDef = colDef;
this.userProvidedColDef = userProvidedColDef;
};
Column.prototype.getUserProvidedColDef = function () {
return this.userProvidedColDef;
};
Column.prototype.setParent = function (parent) {
this.parent = parent;
};
Column.prototype.getParent = function () {
return this.parent;
};
Column.prototype.setOriginalParent = function (originalParent) {
this.originalParent = originalParent;
};
Column.prototype.getOriginalParent = function () {
return this.originalParent;
};
// this is done after constructor as it uses gridOptionsWrapper
Column.prototype.initialise = function () {
this.setPinned(this.colDef.pinned);
var minColWidth = this.gridOptionsWrapper.getMinColWidth();
var maxColWidth = this.gridOptionsWrapper.getMaxColWidth();
if (this.colDef.minWidth) {
this.minWidth = this.colDef.minWidth;
}
else {
this.minWidth = minColWidth;
}
if (this.colDef.maxWidth) {
this.maxWidth = this.colDef.maxWidth;
}
else {
this.maxWidth = maxColWidth;
}
if (this.colDef.flex) {
this.flex = this.colDef.flex;
}
this.actualWidth = this.columnUtils.calculateColInitialWidth(this.colDef);
var suppressDotNotation = this.gridOptionsWrapper.isSuppressFieldDotNotation();
this.fieldContainsDots = _.exists(this.colDef.field) && this.colDef.field.indexOf('.') >= 0 && !suppressDotNotation;
this.tooltipFieldContainsDots = _.exists(this.colDef.tooltipField) && this.colDef.tooltipField.indexOf('.') >= 0 && !suppressDotNotation;
this.validate();
};
Column.prototype.isEmptyGroup = function () {
return false;
};
Column.prototype.isRowGroupDisplayed = function (colId) {
if (_.missing(this.colDef) || _.missing(this.colDef.showRowGroup)) {
return false;
}
var showingAllGroups = this.colDef.showRowGroup === true;
var showingThisGroup = this.colDef.showRowGroup === colId;
return showingAllGroups || showingThisGroup;
};
Column.prototype.getUniqueId = function () {
return this.getId();
};
Column.prototype.isPrimary = function () {
return this.primary;
};
Column.prototype.isFilterAllowed = function () {
// filter defined means it's a string, class or true.
// if its false, null or undefined then it's false.
var filterDefined = !!this.colDef.filter || !!this.colDef.filterFramework;
return this.primary && filterDefined;
};
Column.prototype.isFieldContainsDots = function () {
return this.fieldContainsDots;
};
Column.prototype.isTooltipFieldContainsDots = function () {
return this.tooltipFieldContainsDots;
};
Column.prototype.validate = function () {
var colDefAny = this.colDef;
function warnOnce(msg, key, obj) {
_.doOnce(function () {
if (obj) {
console.warn(msg, obj);
}
else {
_.doOnce(function () { return console.warn(msg); }, key);
}
}, key);
}
if (!ModuleRegistry.isRegistered(ModuleNames.RowGroupingModule)) {
var rowGroupingItems = ['enableRowGroup', 'rowGroup', 'rowGroupIndex', 'enablePivot', 'enableValue', 'pivot', 'pivotIndex', 'aggFunc'];
rowGroupingItems.forEach(function (item) {
if (_.exists(colDefAny[item])) {
warnOnce("ag-Grid: " + item + " is only valid with module Row Grouping, your column definition "
+ ("should not have " + item), 'ColumnRowGroupingMissing' + item);
}
});
}
if (!ModuleRegistry.isRegistered(ModuleNames.RichSelectModule)) {
if (this.colDef.cellEditor === 'agRichSelect' || this.colDef.cellEditor === 'agRichSelectCellEditor') {
warnOnce("ag-Grid: " + this.colDef.cellEditor + " can only be used with "
+ ("module " + ModuleNames.RichSelectModule), 'ColumnRichSelectMissing');
}
}
if (this.gridOptionsWrapper.isTreeData()) {
var itemsNotAllowedWithTreeData = ['rowGroup', 'rowGroupIndex', 'pivot', 'pivotIndex'];
itemsNotAllowedWithTreeData.forEach(function (item) {
if (_.exists(colDefAny[item])) {
warnOnce("ag-Grid: " + item + " is not possible when doing tree data, your "
+ ("column definition should not have " + item), 'TreeDataCannotRowGroup');
}
});
}
if (_.exists(this.colDef.width) && typeof this.colDef.width !== 'number') {
warnOnce('ag-Grid: colDef.width should be a number, not ' + typeof this.colDef.width, 'ColumnCheck_asdfawef');
}
if (_.get(this, 'colDef.cellRendererParams.restrictToOneGroup', null)) {
warnOnce('ag-Grid: Since ag-grid 11.0.0 cellRendererParams.restrictToOneGroup is deprecated. You should use showRowGroup', 'ColumnCheck_sksldjf');
}
if (_.get(this, 'colDef.cellRendererParams.keyMap', null)) {
warnOnce('ag-Grid: Since ag-grid 11.0.0 cellRendererParams.keyMap is deprecated. You should use colDef.keyCreator', 'ColumnCheck_ieiruhgdf');
}
if (_.get(this, 'colDef.cellRendererParams.keyMap', null)) {
warnOnce('ag-Grid: Since ag-grid 11.0.0 cellRendererParams.keyMap is deprecated. You should use colDef.keyCreator', 'ColumnCheck_uitolghj');
}
if (colDefAny.floatingCellRenderer) {
warnOnce('ag-Grid: since v11, floatingCellRenderer is now pinnedRowCellRenderer', 'ColumnCheck_soihwewe');
this.colDef.pinnedRowCellRenderer = colDefAny.floatingCellRenderer;
}
if (colDefAny.floatingRendererFramework) {
warnOnce('ag-Grid: since v11, floatingRendererFramework is now pinnedRowCellRendererFramework', 'ColumnCheck_zdkiouhwer');
this.colDef.pinnedRowCellRendererFramework = colDefAny.floatingRendererFramework;
}
if (colDefAny.floatingRendererParams) {
console.warn('ag-Grid: since v11, floatingRendererParams is now pinnedRowCellRendererParams', 'ColumnCheck_retiuhjs');
this.colDef.pinnedRowCellRendererParams = colDefAny.floatingRendererParams;
}
if (colDefAny.floatingValueFormatter) {
warnOnce('ag-Grid: since v11, floatingValueFormatter is now pinnedRowValueFormatter', 'ColumnCheck_qwroeihjdf');
this.colDef.pinnedRowValueFormatter = colDefAny.floatingValueFormatter;
}
if (colDefAny.cellFormatter) {
warnOnce('ag-Grid: since v12, cellFormatter is now valueFormatter', 'ColumnCheck_eoireknml');
if (_.missing(this.colDef.valueFormatter)) {
this.colDef.valueFormatter = colDefAny.cellFormatter;
}
}
if (colDefAny.headerCellTemplate) {
warnOnce('ag-Grid: since v15, headerCellTemplate is gone, use header component instead.', 'ColumnCheck_eroihxcm');
}
if (colDefAny.headerCellRenderer) {
warnOnce('ag-Grid: since v15, headerCellRenderer is gone, use header component instead.', 'ColumnCheck_terteuh');
}
if (colDefAny.volatile) {
warnOnce('ag-Grid: since v16, colDef.volatile is gone, please check refresh docs on how to refresh specific cells.', 'ColumnCheck_weoihjxcv');
}
if (colDefAny.suppressSorting) {
warnOnce("ag-Grid: since v20, colDef.suppressSorting is gone, instead use colDef.sortable=false.", 'ColumnCheck_43ljrer', this.colDef);
this.colDef.sortable = false;
}
if (colDefAny.suppressFilter) {
warnOnce("ag-Grid: since v20, colDef.suppressFilter is gone, instead use colDef.filter=false.", 'ColumnCheck_erlkhfdm', this.colDef);
this.colDef.filter = false;
}
if (colDefAny.suppressResize) {
warnOnce("ag-Grid: since v20, colDef.suppressResize is gone, instead use colDef.resizable=false.", 'ColumnCheck_weoihjxcv', this.colDef);
this.colDef.resizable = false;
}
if (colDefAny.tooltip) {
warnOnce("ag-Grid: since v20.1, colDef.tooltip is gone, instead use colDef.tooltipValueGetter.", 'ColumnCheck_adslknjwef', this.colDef);
this.colDef.tooltipValueGetter = colDefAny.tooltip;
}
if (colDefAny.suppressToolPanel) {
warnOnce("ag-Grid: since v22, colDef.suppressToolPanel is gone, instead use suppressColumnsToolPanel / suppressFiltersToolPanel.", 'ColumnCheck_weihjlsjkdf', this.colDef);
this.colDef.suppressColumnsToolPanel = true;
}
};
Column.prototype.addEventListener = function (eventType, listener) {
this.eventService.addEventListener(eventType, listener);
};
Column.prototype.removeEventListener = function (eventType, listener) {
this.eventService.removeEventListener(eventType, listener);
};
Column.prototype.createIsColumnFuncParams = function (rowNode) {
return {
node: rowNode,
data: rowNode.data,
column: this,
colDef: this.colDef,
context: this.gridOptionsWrapper.getContext(),
api: this.gridOptionsWrapper.getApi(),
columnApi: this.gridOptionsWrapper.getColumnApi()
};
};
Column.prototype.isSuppressNavigable = function (rowNode) {
// if boolean set, then just use it
if (typeof this.colDef.suppressNavigable === 'boolean') {
return this.colDef.suppressNavigable;
}
// if function, then call the function to find out
if (typeof this.colDef.suppressNavigable === 'function') {
var params = this.createIsColumnFuncParams(rowNode);
var userFunc = this.colDef.suppressNavigable;
return userFunc(params);
}
return false;
};
Column.prototype.isCellEditable = function (rowNode) {
// only allow editing of groups if the user has this option enabled
if (rowNode.group && !this.gridOptionsWrapper.isEnableGroupEdit()) {
return false;
}
return this.isColumnFunc(rowNode, this.colDef.editable);
};
Column.prototype.isRowDrag = function (rowNode) {
return this.isColumnFunc(rowNode, this.colDef.rowDrag);
};
Column.prototype.isDndSource = function (rowNode) {
return this.isColumnFunc(rowNode, this.colDef.dndSource);
};
Column.prototype.isCellCheckboxSelection = function (rowNode) {
return this.isColumnFunc(rowNode, this.colDef.checkboxSelection);
};
Column.prototype.isSuppressPaste = function (rowNode) {
return this.isColumnFunc(rowNode, this.colDef ? this.colDef.suppressPaste : null);
};
Column.prototype.isResizable = function () {
return this.colDef.resizable === true;
};
Column.prototype.isColumnFunc = function (rowNode, value) {
// if boolean set, then just use it
if (typeof value === 'boolean') {
return value;
}
// if function, then call the function to find out
if (typeof value === 'function') {
var params = this.createIsColumnFuncParams(rowNode);
var editableFunc = value;
return editableFunc(params);
}
return false;
};
Column.prototype.setMoving = function (moving, source) {
if (source === void 0) { source = "api"; }
this.moving = moving;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_MOVING_CHANGED, source));
};
Column.prototype.createColumnEvent = function (type, source) {
return {
api: this.gridApi,
columnApi: this.columnApi,
type: type,
column: this,
columns: [this],
source: source
};
};
Column.prototype.isMoving = function () {
return this.moving;
};
Column.prototype.getSort = function () {
return this.sort;
};
Column.prototype.setSort = function (sort, source) {
if (source === void 0) { source = "api"; }
if (this.sort !== sort) {
this.sort = sort;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_SORT_CHANGED, source));
}
};
Column.prototype.setMenuVisible = function (visible, source) {
if (source === void 0) { source = "api"; }
if (this.menuVisible !== visible) {
this.menuVisible = visible;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_MENU_VISIBLE_CHANGED, source));
}
};
Column.prototype.isMenuVisible = function () {
return this.menuVisible;
};
Column.prototype.isSortAscending = function () {
return this.sort === Constants.SORT_ASC;
};
Column.prototype.isSortDescending = function () {
return this.sort === Constants.SORT_DESC;
};
Column.prototype.isSortNone = function () {
return _.missing(this.sort);
};
Column.prototype.isSorting = function () {
return _.exists(this.sort);
};
Column.prototype.getSortedAt = function () {
return this.sortedAt;
};
Column.prototype.setSortedAt = function (sortedAt) {
this.sortedAt = sortedAt;
};
Column.prototype.setAggFunc = function (aggFunc) {
this.aggFunc = aggFunc;
};
Column.prototype.getAggFunc = function () {
return this.aggFunc;
};
Column.prototype.getLeft = function () {
return this.left;
};
Column.prototype.getOldLeft = function () {
return this.oldLeft;
};
Column.prototype.getRight = function () {
return this.left + this.actualWidth;
};
Column.prototype.setLeft = function (left, source) {
if (source === void 0) { source = "api"; }
this.oldLeft = this.left;
if (this.left !== left) {
this.left = left;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_LEFT_CHANGED, source));
}
};
Column.prototype.isFilterActive = function () {
return this.filterActive;
};
// additionalEventAttributes is used by provided simple floating filter, so it can add 'floatingFilter=true' to the event
Column.prototype.setFilterActive = function (active, source, additionalEventAttributes) {
if (source === void 0) { source = "api"; }
if (this.filterActive !== active) {
this.filterActive = active;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_FILTER_ACTIVE_CHANGED, source));
}
var filterChangedEvent = this.createColumnEvent(Column.EVENT_FILTER_CHANGED, source);
if (additionalEventAttributes) {
_.mergeDeep(filterChangedEvent, additionalEventAttributes);
}
this.eventService.dispatchEvent(filterChangedEvent);
};
Column.prototype.setPinned = function (pinned) {
if (pinned === true || pinned === Constants.PINNED_LEFT) {
this.pinned = Constants.PINNED_LEFT;
}
else if (pinned === Constants.PINNED_RIGHT) {
this.pinned = Constants.PINNED_RIGHT;
}
else {
this.pinned = null;
}
};
Column.prototype.setFirstRightPinned = function (firstRightPinned, source) {
if (source === void 0) { source = "api"; }
if (this.firstRightPinned !== firstRightPinned) {
this.firstRightPinned = firstRightPinned;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_FIRST_RIGHT_PINNED_CHANGED, source));
}
};
Column.prototype.setLastLeftPinned = function (lastLeftPinned, source) {
if (source === void 0) { source = "api"; }
if (this.lastLeftPinned !== lastLeftPinned) {
this.lastLeftPinned = lastLeftPinned;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_LAST_LEFT_PINNED_CHANGED, source));
}
};
Column.prototype.isFirstRightPinned = function () {
return this.firstRightPinned;
};
Column.prototype.isLastLeftPinned = function () {
return this.lastLeftPinned;
};
Column.prototype.isPinned = function () {
return this.pinned === Constants.PINNED_LEFT || this.pinned === Constants.PINNED_RIGHT;
};
Column.prototype.isPinnedLeft = function () {
return this.pinned === Constants.PINNED_LEFT;
};
Column.prototype.isPinnedRight = function () {
return this.pinned === Constants.PINNED_RIGHT;
};
Column.prototype.getPinned = function () {
return this.pinned;
};
Column.prototype.setVisible = function (visible, source) {
if (source === void 0) { source = "api"; }
var newValue = visible === true;
if (this.visible !== newValue) {
this.visible = newValue;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_VISIBLE_CHANGED, source));
}
};
Column.prototype.isVisible = function () {
return this.visible;
};
Column.prototype.getColDef = function () {
return this.colDef;
};
Column.prototype.getColumnGroupShow = function () {
return this.colDef.columnGroupShow;
};
Column.prototype.getColId = function () {
return this.colId;
};
Column.prototype.getId = function () {
return this.getColId();
};
Column.prototype.getDefinition = function () {
return this.colDef;
};
Column.prototype.getActualWidth = function () {
return this.actualWidth;
};
Column.prototype.createBaseColDefParams = function (rowNode) {
var params = {
node: rowNode,
data: rowNode.data,
colDef: this.colDef,
column: this,
api: this.gridOptionsWrapper.getApi(),
columnApi: this.gridOptionsWrapper.getColumnApi(),
context: this.gridOptionsWrapper.getContext()
};
return params;
};
Column.prototype.getColSpan = function (rowNode) {
if (_.missing(this.colDef.colSpan)) {
return 1;
}
var params = this.createBaseColDefParams(rowNode);
var colSpan = this.colDef.colSpan(params);
// colSpan must be number equal to or greater than 1
return Math.max(colSpan, 1);
};
Column.prototype.getRowSpan = function (rowNode) {
if (_.missing(this.colDef.rowSpan)) {
return 1;
}
var params = this.createBaseColDefParams(rowNode);
var rowSpan = this.colDef.rowSpan(params);
// rowSpan must be number equal to or greater than 1
return Math.max(rowSpan, 1);
};
Column.prototype.setActualWidth = function (actualWidth, source) {
if (source === void 0) { source = "api"; }
if (this.minWidth != null) {
actualWidth = Math.max(actualWidth, this.minWidth);
}
if (this.maxWidth != null) {
actualWidth = Math.min(actualWidth, this.maxWidth);
}
if (this.actualWidth !== actualWidth) {
// disable flex for this column if it was manually resized.
if (this.flex && source !== 'flex') {
this.flex = 0;
}
this.actualWidth = actualWidth;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_WIDTH_CHANGED, source));
}
};
Column.prototype.isGreaterThanMax = function (width) {
if (this.maxWidth != null) {
return width > this.maxWidth;
}
return false;
};
Column.prototype.getMinWidth = function () {
return this.minWidth;
};
Column.prototype.getMaxWidth = function () {
return this.maxWidth;
};
Column.prototype.getFlex = function () {
return this.flex || 0;
};
Column.prototype.setMinimum = function (source) {
if (source === void 0) { source = "api"; }
this.setActualWidth(this.minWidth, source);
};
Column.prototype.setRowGroupActive = function (rowGroup, source) {
if (source === void 0) { source = "api"; }
if (this.rowGroupActive !== rowGroup) {
this.rowGroupActive = rowGroup;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_ROW_GROUP_CHANGED, source));
}
};
Column.prototype.isRowGroupActive = function () {
return this.rowGroupActive;
};
Column.prototype.setPivotActive = function (pivot, source) {
if (source === void 0) { source = "api"; }
if (this.pivotActive !== pivot) {
this.pivotActive = pivot;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_PIVOT_CHANGED, source));
}
};
Column.prototype.isPivotActive = function () {
return this.pivotActive;
};
Column.prototype.isAnyFunctionActive = function () {
return this.isPivotActive() || this.isRowGroupActive() || this.isValueActive();
};
Column.prototype.isAnyFunctionAllowed = function () {
return this.isAllowPivot() || this.isAllowRowGroup() || this.isAllowValue();
};
Column.prototype.setValueActive = function (value, source) {
if (source === void 0) { source = "api"; }
if (this.aggregationActive !== value) {
this.aggregationActive = value;
this.eventService.dispatchEvent(this.createColumnEvent(Column.EVENT_VALUE_CHANGED, source));
}
};
Column.prototype.isValueActive = function () {
return this.aggregationActive;
};
Column.prototype.isAllowPivot = function () {
return this.colDef.enablePivot === true;
};
Column.prototype.isAllowValue = function () {
return this.colDef.enableValue === true;
};
Column.prototype.isAllowRowGroup = function () {
return this.colDef.enableRowGroup === true;
};
Column.prototype.getMenuTabs = function (defaultValues) {
var menuTabs = this.getColDef().menuTabs;
if (menuTabs == null) {
menuTabs = defaultValues;
}
return menuTabs;
};
// this used to be needed, as previous version of ag-grid had lockPosition as column state,
// so couldn't depend on colDef version.
Column.prototype.isLockPosition = function () {
console.warn('ag-Grid: since v21, col.isLockPosition() should not be used, please use col.getColDef().lockPosition instead.');
return this.colDef ? !!this.colDef.lockPosition : false;
};
// this used to be needed, as previous version of ag-grid had lockVisible as column state,
// so couldn't depend on colDef version.
Column.prototype.isLockVisible = function () {
console.warn('ag-Grid: since v21, col.isLockVisible() should not be used, please use col.getColDef().lockVisible instead.');
return this.colDef ? !!this.colDef.lockVisible : false;
};
// this used to be needed, as previous version of ag-grid had lockPinned as column state,
// so couldn't depend on colDef version.
Column.prototype.isLockPinned = function () {
console.warn('ag-Grid: since v21, col.isLockPinned() should not be used, please use col.getColDef().lockPinned instead.');
return this.colDef ? !!this.colDef.lockPinned : false;
};
// + renderedHeaderCell - for making header cell transparent when moving
Column.EVENT_MOVING_CHANGED = 'movingChanged';
// + renderedCell - changing left position
Column.EVENT_LEFT_CHANGED = 'leftChanged';
// + renderedCell - changing width
Column.EVENT_WIDTH_CHANGED = 'widthChanged';
// + renderedCell - for changing pinned classes
Column.EVENT_LAST_LEFT_PINNED_CHANGED = 'lastLeftPinnedChanged';
Column.EVENT_FIRST_RIGHT_PINNED_CHANGED = 'firstRightPinnedChanged';
// + renderedColumn - for changing visibility icon
Column.EVENT_VISIBLE_CHANGED = 'visibleChanged';
// + every time the filter changes, used in the floating filters
Column.EVENT_FILTER_CHANGED = 'filterChanged';
// + renderedHeaderCell - marks the header with filter icon
Column.EVENT_FILTER_ACTIVE_CHANGED = 'filterActiveChanged';
// + renderedHeaderCell - marks the header with sort icon
Column.EVENT_SORT_CHANGED = 'sortChanged';
Column.EVENT_MENU_VISIBLE_CHANGED = 'menuVisibleChanged';
// + toolpanel, for gui updates
Column.EVENT_ROW_GROUP_CHANGED = 'columnRowGroupChanged';
// + toolpanel, for gui updates
Column.EVENT_PIVOT_CHANGED = 'columnPivotChanged';
// + toolpanel, for gui updates
Column.EVENT_VALUE_CHANGED = 'columnValueChanged';
__decorate$1([
Autowired('gridOptionsWrapper')
], Column.prototype, "gridOptionsWrapper", void 0);
__decorate$1([
Autowired('columnUtils')
], Column.prototype, "columnUtils", void 0);
__decorate$1([
Autowired('columnApi')
], Column.prototype, "columnApi", void 0);
__decorate$1([
Autowired('gridApi')
], Column.prototype, "gridApi", void 0);
__decorate$1([
Autowired('context')
], Column.prototype, "context", void 0);
__decorate$1([
PostConstruct
], Column.prototype, "initialise", null);
return Column;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate$2 = (undefined && undefined.__decorate) || function (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;
};
var ColumnGroup = /** @class */ (function () {
function ColumnGroup(originalColumnGroup, groupId, instanceId, pinned) {
// depends on the open/closed state of the group, only displaying columns are stored here
this.displayedChildren = [];
this.localEventService = new EventService();
this.groupId = groupId;
this.instanceId = instanceId;
this.originalColumnGroup = originalColumnGroup;
this.pinned = pinned;
}
// this is static, a it is used outside of this class
ColumnGroup.createUniqueId = function (groupId, instanceId) {
return groupId + '_' + instanceId;
};
// as the user is adding and removing columns, the groups are recalculated.
// this reset clears out all children, ready for children to be added again
ColumnGroup.prototype.reset = function () {
this.parent = null;
this.children = null;
this.displayedChildren = null;
};
ColumnGroup.prototype.getParent = function () {
return this.parent;
};
ColumnGroup.prototype.setParent = function (parent) {
this.parent = parent;
};
ColumnGroup.prototype.getUniqueId = function () {
return ColumnGroup.createUniqueId(this.groupId, this.instanceId);
};
ColumnGroup.prototype.isEmptyGroup = function () {
return this.displayedChildren.length === 0;
};
ColumnGroup.prototype.isMoving = function () {
var allLeafColumns = this.getOriginalColumnGroup().getLeafColumns();
if (!allLeafColumns || allLeafColumns.length === 0) {
return false;
}
return allLeafColumns.every(function (col) { return col.isMoving(); });
};
ColumnGroup.prototype.checkLeft = function () {
// first get all children to setLeft, as it impacts our decision below
this.displayedChildren.forEach(function (child) {
if (child instanceof ColumnGroup) {
child.checkLeft();
}
});
// set our left based on first displayed column
if (this.displayedChildren.length > 0) {
if (this.gridOptionsWrapper.isEnableRtl()) {
var lastChild = _.last(this.displayedChildren);
var lastChildLeft = lastChild.getLeft();
this.setLeft(lastChildLeft);
}
else {
var firstChildLeft = this.displayedChildren[0].getLeft();
this.setLeft(firstChildLeft);
}
}
else {
// this should never happen, as if we have no displayed columns, then
// this groups should not even exist.
this.setLeft(null);
}
};
ColumnGroup.prototype.getLeft = function () {
return this.left;
};
ColumnGroup.prototype.getOldLeft = function () {
return this.oldLeft;
};
ColumnGroup.prototype.setLeft = function (left) {
this.oldLeft = left;
if (this.left !== left) {
this.left = left;
this.localEventService.dispatchEvent(this.createAgEvent(ColumnGroup.EVENT_LEFT_CHANGED));
}
};
ColumnGroup.prototype.getPinned = function () {
return this.pinned;
};
ColumnGroup.prototype.createAgEvent = function (type) {
return { type: type };
};
ColumnGroup.prototype.addEventListener = function (eventType, listener) {
this.localEventService.addEventListener(eventType, listener);
};
ColumnGroup.prototype.removeEventListener = function (eventType, listener) {
this.localEventService.removeEventListener(eventType, listener);
};
ColumnGroup.prototype.getGroupId = function () {
return this.groupId;
};
ColumnGroup.prototype.getInstanceId = function () {
return this.instanceId;
};
ColumnGroup.prototype.isChildInThisGroupDeepSearch = function (wantedChild) {
var result = false;
this.children.forEach(function (foundChild) {
if (wantedChild === foundChild) {
result = true;
}
if (foundChild instanceof ColumnGroup) {
if (foundChild.isChildInThisGroupDeepSearch(wantedChild)) {
result = true;
}
}
});
return result;
};
ColumnGroup.prototype.getActualWidth = function () {
var groupActualWidth = 0;
if (this.displayedChildren) {
this.displayedChildren.forEach(function (child) {
groupActualWidth += child.getActualWidth();
});
}
return groupActualWidth;
};
ColumnGroup.prototype.isResizable = function () {
if (!this.displayedChildren) {
return false;
}
// if at least one child is resizable, then the group is resizable
var result = false;
this.displayedChildren.forEach(function (child) {
if (child.isResizable()) {
result = true;
}
});
return result;
};
ColumnGroup.prototype.getMinWidth = function () {
var result = 0;
this.displayedChildren.forEach(function (groupChild) {
result += groupChild.getMinWidth();
});
return result;
};
ColumnGroup.prototype.addChild = function (child) {
if (!this.children) {
this.children = [];
}
this.children.push(child);
};
ColumnGroup.prototype.getDisplayedChildren = function () {
return this.displayedChildren;
};
ColumnGroup.prototype.getLeafColumns = function () {
var result = [];
this.addLeafColumns(result);
return result;
};
ColumnGroup.prototype.getDisplayedLeafColumns = function () {
var result = [];
this.addDisplayedLeafColumns(result);
return result;
};
// why two methods here doing the same thing?
ColumnGroup.prototype.getDefinition = function () {
return this.originalColumnGroup.getColGroupDef();
};
ColumnGroup.prototype.getColGroupDef = function () {
return this.originalColumnGroup.getColGroupDef();
};
ColumnGroup.prototype.isPadding = function () {
return this.originalColumnGroup.isPadding();
};
ColumnGroup.prototype.isExpandable = function () {
return this.originalColumnGroup.isExpandable();
};
ColumnGroup.prototype.isExpanded = function () {
return this.originalColumnGroup.isExpanded();
};
ColumnGroup.prototype.setExpanded = function (expanded) {
this.originalColumnGroup.setExpanded(expanded);
};
ColumnGroup.prototype.addDisplayedLeafColumns = function (leafColumns) {
this.displayedChildren.forEach(function (child) {
if (child instanceof Column) {
leafColumns.push(child);
}
else if (child instanceof ColumnGroup) {
child.addDisplayedLeafColumns(leafColumns);
}
});
};
ColumnGroup.prototype.addLeafColumns = function (leafColumns) {
this.children.forEach(function (child) {
if (child instanceof Column) {
leafColumns.push(child);
}
else if (child instanceof ColumnGroup) {
child.addLeafColumns(leafColumns);
}
});
};
ColumnGroup.prototype.getChildren = function () {
return this.children;
};
ColumnGroup.prototype.getColumnGroupShow = function () {
return this.originalColumnGroup.getColumnGroupShow();
};
ColumnGroup.prototype.getOriginalColumnGroup = function () {
return this.originalColumnGroup;
};
ColumnGroup.prototype.calculateDisplayedColumns = function () {
var _this = this;
// clear out last time we calculated
this.displayedChildren = [];
var topLevelGroup = this;
// find the column group that is controlling expandable. this is relevant when we have padding (empty)
// groups, where the expandable is actually the first parent that is not a padding group.
if (this.isPadding()) {
while (topLevelGroup.getParent() && topLevelGroup.isPadding()) {
topLevelGroup = topLevelGroup.getParent();
}
}
var isExpandable = topLevelGroup.originalColumnGroup.isExpandable();
// it not expandable, everything is visible
if (!isExpandable) {
this.displayedChildren = this.children;
}
else {
// Add cols based on columnGroupShow
// Note - the below also adds padding groups, these are always added because they never have
// colDef.columnGroupShow set.
this.children.forEach(function (abstractColumn) {
var headerGroupShow = abstractColumn.getColumnGroupShow();
switch (headerGroupShow) {
case ColumnGroup.HEADER_GROUP_SHOW_OPEN:
// when set to open, only show col if group is open
if (topLevelGroup.originalColumnGroup.isExpanded()) {
_this.displayedChildren.push(abstractColumn);
}
break;
case ColumnGroup.HEADER_GROUP_SHOW_CLOSED:
// when set to open, only show col if group is open
if (!topLevelGroup.originalColumnGroup.isExpanded()) {
_this.displayedChildren.push(abstractColumn);
}
break;
default:
// if this abstractColumn is padding, we just want to add it
// to the displayedChildren list if it has displayedChildren itself.
if (!(abstractColumn instanceof ColumnGroup &&
abstractColumn.isPadding() &&
!abstractColumn.displayedChildren.length)) {
_this.displayedChildren.push(abstractColumn);
}
break;
}
});
}
this.localEventService.dispatchEvent(this.createAgEvent(ColumnGroup.EVENT_DISPLAYED_CHILDREN_CHANGED));
};
ColumnGroup.HEADER_GROUP_SHOW_OPEN = 'open';
ColumnGroup.HEADER_GROUP_SHOW_CLOSED = 'closed';
ColumnGroup.HEADER_GROUP_PADDING = 'padding';
ColumnGroup.EVENT_LEFT_CHANGED = 'leftChanged';
ColumnGroup.EVENT_DISPLAYED_CHILDREN_CHANGED = 'displayedChildrenChanged';
__decorate$2([
Autowired('gridOptionsWrapper')
], ColumnGroup.prototype, "gridOptionsWrapper", void 0);
return ColumnGroup;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var OriginalColumnGroup = /** @class */ (function () {
function OriginalColumnGroup(colGroupDef, groupId, padding, level) {
this.localEventService = new EventService();
this.expandable = false;
this.colGroupDef = colGroupDef;
this.groupId = groupId;
this.expanded = colGroupDef && !!colGroupDef.openByDefault;
this.padding = padding;
this.level = level;
}
OriginalColumnGroup.prototype.setOriginalParent = function (originalParent) {
this.originalParent = originalParent;
};
OriginalColumnGroup.prototype.getOriginalParent = function () {
return this.originalParent;
};
OriginalColumnGroup.prototype.getLevel = function () {
return this.level;
};
OriginalColumnGroup.prototype.isVisible = function () {
// return true if at least one child is visible
if (this.children) {
return this.children.some(function (child) { return child.isVisible(); });
}
return false;
};
OriginalColumnGroup.prototype.isPadding = function () {
return this.padding;
};
OriginalColumnGroup.prototype.setExpanded = function (expanded) {
this.expanded = expanded === undefined ? false : expanded;
var event = {
type: OriginalColumnGroup.EVENT_EXPANDED_CHANGED
};
this.localEventService.dispatchEvent(event);
};
OriginalColumnGroup.prototype.isExpandable = function () {
return this.expandable;
};
OriginalColumnGroup.prototype.isExpanded = function () {
return this.expanded;
};
OriginalColumnGroup.prototype.getGroupId = function () {
return this.groupId;
};
OriginalColumnGroup.prototype.getId = function () {
return this.getGroupId();
};
OriginalColumnGroup.prototype.setChildren = function (children) {
this.children = children;
};
OriginalColumnGroup.prototype.getChildren = function () {
return this.children;
};
OriginalColumnGroup.prototype.getColGroupDef = function () {
return this.colGroupDef;
};
OriginalColumnGroup.prototype.getLeafColumns = function () {
var result = [];
this.addLeafColumns(result);
return result;
};
OriginalColumnGroup.prototype.addLeafColumns = function (leafColumns) {
if (!this.children) {
return;
}
this.children.forEach(function (child) {
if (child instanceof Column) {
leafColumns.push(child);
}
else if (child instanceof OriginalColumnGroup) {
child.addLeafColumns(leafColumns);
}
});
};
OriginalColumnGroup.prototype.getColumnGroupShow = function () {
return this.padding ? ColumnGroup.HEADER_GROUP_PADDING : this.colGroupDef.columnGroupShow;
};
// need to check that this group has at least one col showing when both expanded and contracted.
// if not, then we don't allow expanding and contracting on this group
OriginalColumnGroup.prototype.setupExpandable = function () {
var _this = this;
this.setExpandable();
// note - we should be removing this event listener
this.getLeafColumns().forEach(function (col) { return col.addEventListener(Column.EVENT_VISIBLE_CHANGED, _this.onColumnVisibilityChanged.bind(_this)); });
};
OriginalColumnGroup.prototype.setExpandable = function () {
if (this.isPadding()) {
return;
}
// want to make sure the group doesn't disappear when it's open
var atLeastOneShowingWhenOpen = false;
// want to make sure the group doesn't disappear when it's closed
var atLeastOneShowingWhenClosed = false;
// want to make sure the group has something to show / hide
var atLeastOneChangeable = false;
var children = this.findChildren();
for (var i = 0, j = children.length; i < j; i++) {
var abstractColumn = children[i];
if (!abstractColumn.isVisible()) {
continue;
}
// if the abstractColumn is a grid generated group, there will be no colDef
var headerGroupShow = abstractColumn.getColumnGroupShow();
if (headerGroupShow === ColumnGroup.HEADER_GROUP_SHOW_OPEN) {
atLeastOneShowingWhenOpen = true;
atLeastOneChangeable = true;
}
else if (headerGroupShow === ColumnGroup.HEADER_GROUP_SHOW_CLOSED) {
atLeastOneShowingWhenClosed = true;
atLeastOneChangeable = true;
}
else {
atLeastOneShowingWhenOpen = true;
atLeastOneShowingWhenClosed = true;
if (headerGroupShow === ColumnGroup.HEADER_GROUP_PADDING) {
var column = abstractColumn;
atLeastOneChangeable = atLeastOneChangeable || column.children.some(function (child) { return child.getColumnGroupShow() !== undefined; });
}
}
}
var expandable = atLeastOneShowingWhenOpen && atLeastOneShowingWhenClosed && atLeastOneChangeable;
if (this.expandable !== expandable) {
this.expandable = expandable;
var event_1 = {
type: OriginalColumnGroup.EVENT_EXPANDABLE_CHANGED
};
this.localEventService.dispatchEvent(event_1);
}
};
OriginalColumnGroup.prototype.findChildren = function () {
var children = this.children;
var firstChild = children[0];
if (firstChild && (!firstChild.isPadding || !firstChild.isPadding())) {
return children;
}
while (children.length === 1 && children[0] instanceof OriginalColumnGroup) {
children = children[0].children;
}
return children;
};
OriginalColumnGroup.prototype.onColumnVisibilityChanged = function () {
this.setExpandable();
};
OriginalColumnGroup.prototype.addEventListener = function (eventType, listener) {
this.localEventService.addEventListener(eventType, listener);
};
OriginalColumnGroup.prototype.removeEventListener = function (eventType, listener) {
this.localEventService.removeEventListener(eventType, listener);
};
OriginalColumnGroup.EVENT_EXPANDED_CHANGED = 'expandedChanged';
OriginalColumnGroup.EVENT_EXPANDABLE_CHANGED = 'expandableChanged';
return OriginalColumnGroup;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var DefaultColumnTypes = {
numericColumn: {
headerClass: "ag-numeric-header",
cellClass: "ag-numeric-cell"
}
};
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate$3 = (undefined && undefined.__decorate) || function (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;
};
var __param$1 = (undefined && undefined.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
// takes ColDefs and ColGroupDefs and turns them into Columns and OriginalGroups
var ColumnFactory = /** @class */ (function () {
function ColumnFactory() {
}
ColumnFactory.prototype.setBeans = function (loggerFactory) {
this.logger = loggerFactory.create('ColumnFactory');
};
ColumnFactory.prototype.createColumnTree = function (defs, primaryColumns, existingColumns) {
// column key creator dishes out unique column id's in a deterministic way,
// so if we have two grids (that could be master/slave) with same column definitions,
// then this ensures the two grids use identical id's.
var columnKeyCreator = new ColumnKeyCreator();
if (existingColumns) {
var existingKeys = existingColumns.map(function (col) { return col.getId(); });
columnKeyCreator.addExistingKeys(existingKeys);
}
// we take a copy of the columns as we are going to be removing from them
var existingColsCopy = existingColumns ? existingColumns.slice() : null;
// create am unbalanced tree that maps the provided definitions
var unbalancedTree = this.recursivelyCreateColumns(defs, 0, primaryColumns, existingColsCopy, columnKeyCreator, null);
var treeDept = this.findMaxDept(unbalancedTree, 0);
this.logger.log('Number of levels for grouped columns is ' + treeDept);
var columnTree = this.balanceColumnTree(unbalancedTree, 0, treeDept, columnKeyCreator);
var deptFirstCallback = function (child, parent) {
if (child instanceof OriginalColumnGroup) {
child.setupExpandable();
}
// we set the original parents at the end, rather than when we go along, as balancing the tree
// adds extra levels into the tree. so we can only set parents when balancing is done.
child.setOriginalParent(parent);
};
this.columnUtils.depthFirstOriginalTreeSearch(null, columnTree, deptFirstCallback);
return {
columnTree: columnTree,
treeDept: treeDept
};
};
ColumnFactory.prototype.createForAutoGroups = function (autoGroupCols, gridBalancedTree) {
var _this = this;
var autoColBalancedTree = [];
autoGroupCols.forEach(function (col) {
var fakeTreeItem = _this.createAutoGroupTreeItem(gridBalancedTree, col);
autoColBalancedTree.push(fakeTreeItem);
});
return autoColBalancedTree;
};
ColumnFactory.prototype.createAutoGroupTreeItem = function (balancedColumnTree, column) {
var dept = this.findDepth(balancedColumnTree);
// at the end, this will be the top of the tree item.
var nextChild = column;
for (var i = dept - 1; i >= 0; i--) {
var autoGroup = new OriginalColumnGroup(null, "FAKE_PATH_" + column.getId() + "}_" + i, true, i);
this.context.wireBean(autoGroup);
autoGroup.setChildren([nextChild]);
nextChild.setOriginalParent(autoGroup);
nextChild = autoGroup;
}
// at this point, the nextChild is the top most item in the tree
return nextChild;
};
ColumnFactory.prototype.findDepth = function (balancedColumnTree) {
var dept = 0;
var pointer = balancedColumnTree;
while (pointer && pointer[0] && pointer[0] instanceof OriginalColumnGroup) {
dept++;
pointer = pointer[0].getChildren();
}
return dept;
};
ColumnFactory.prototype.balanceColumnTree = function (unbalancedTree, currentDept, columnDept, columnKeyCreator) {
var result = [];
// go through each child, for groups, recurse a level deeper,
// for columns we need to pad
for (var i = 0; i < unbalancedTree.length; i++) {
var child = unbalancedTree[i];
if (child instanceof OriginalColumnGroup) {
// child is a group, all we do is go to the next level of recursion
var originalGroup = child;
var newChildren = this.balanceColumnTree(originalGroup.getChildren(), currentDept + 1, columnDept, columnKeyCreator);
originalGroup.setChildren(newChildren);
result.push(originalGroup);
}
else {
// child is a column - so here we add in the padded column groups if needed
var firstPaddedGroup = void 0;
var currentPaddedGroup = void 0;
// this for loop will NOT run any loops if no padded column groups are needed
for (var j = columnDept - 1; j >= currentDept; j--) {
var newColId = columnKeyCreator.getUniqueKey(null, null);
var colGroupDefMerged = this.createMergedColGroupDef(null);
var paddedGroup = new OriginalColumnGroup(colGroupDefMerged, newColId, true, currentDept);
this.context.wireBean(paddedGroup);
if (currentPaddedGroup) {
currentPaddedGroup.setChildren([paddedGroup]);
}
currentPaddedGroup = paddedGroup;
if (!firstPaddedGroup) {
firstPaddedGroup = currentPaddedGroup;
}
}
// likewise this if statement will not run if no padded groups
if (firstPaddedGroup) {
result.push(firstPaddedGroup);
var hasGroups = unbalancedTree.some(function (child) { return child instanceof OriginalColumnGroup; });
if (hasGroups) {
currentPaddedGroup.setChildren([child]);
continue;
}
else {
currentPaddedGroup.setChildren(unbalancedTree);
break;
}
}
result.push(child);
}
}
return result;
};
ColumnFactory.prototype.findMaxDept = function (treeChildren, dept) {
var maxDeptThisLevel = dept;
for (var i = 0; i < treeChildren.length; i++) {
var abstractColumn = treeChildren[i];
if (abstractColumn instanceof OriginalColumnGroup) {
var originalGroup = abstractColumn;
var newDept = this.findMaxDept(originalGroup.getChildren(), dept + 1);
if (maxDeptThisLevel < newDept) {
maxDeptThisLevel = newDept;
}
}
}
return maxDeptThisLevel;
};
ColumnFactory.prototype.recursivelyCreateColumns = function (defs, level, primaryColumns, existingColsCopy, columnKeyCreator, parent) {
var _this = this;
var result = [];
if (!defs) {
return result;
}
defs.forEach(function (def) {
var newGroupOrColumn;
if (_this.isColumnGroup(def)) {
newGroupOrColumn = _this.createColumnGroup(primaryColumns, def, level, existingColsCopy, columnKeyCreator, parent);
}
else {
newGroupOrColumn = _this.createColumn(primaryColumns, def, existingColsCopy, columnKeyCreator, parent);
}
result.push(newGroupOrColumn);
});
return result;
};
ColumnFactory.prototype.createColumnGroup = function (primaryColumns, colGroupDef, level, existingColumns, columnKeyCreator, parent) {
var colGroupDefMerged = this.createMergedColGroupDef(colGroupDef);
var groupId = columnKeyCreator.getUniqueKey(colGroupDefMerged.groupId, null);
var originalGroup = new OriginalColumnGroup(colGroupDefMerged, groupId, false, level);
this.context.wireBean(originalGroup);
var children = this.recursivelyCreateColumns(colGroupDefMerged.children, level + 1, primaryColumns, existingColumns, columnKeyCreator, originalGroup);
originalGroup.setChildren(children);
return originalGroup;
};
ColumnFactory.prototype.createMergedColGroupDef = function (colGroupDef) {
var colGroupDefMerged = {};
_.assign(colGroupDefMerged, this.gridOptionsWrapper.getDefaultColGroupDef());
_.assign(colGroupDefMerged, colGroupDef);
this.checkForDeprecatedItems(colGroupDefMerged);
return colGroupDefMerged;
};
ColumnFactory.prototype.createColumn = function (primaryColumns, colDef, existingColsCopy, columnKeyCreator, parent) {
var colDefMerged = this.mergeColDefs(colDef);
this.checkForDeprecatedItems(colDefMerged);
// see if column already exists
var column = this.findExistingColumn(colDef, existingColsCopy);
if (!column) {
// no existing column, need to create one
var colId = columnKeyCreator.getUniqueKey(colDefMerged.colId, colDefMerged.field);
column = new Column(colDefMerged, colDef, colId, primaryColumns);
this.context.wireBean(column);
}
else {
column.setColDef(colDefMerged, colDef);
}
return column;
};
ColumnFactory.prototype.findExistingColumn = function (colDef, existingColsCopy) {
var res = _.find(existingColsCopy, function (col) {
var oldColDef = col.getUserProvidedColDef();
if (!oldColDef) {
return false;
}
// first check object references
if (oldColDef === colDef) {
return true;
}
// second check id's
var oldColHadId = oldColDef.colId !== null && oldColDef.colId !== undefined;
if (oldColHadId) {
return oldColDef.colId === colDef.colId;
}
return false;
});
// make sure we remove, so if user provided duplicate id, then we don't have more than
// one column instance for colDef with common id
if (res) {
_.removeFromArray(existingColsCopy, res);
}
return res;
};
ColumnFactory.prototype.mergeColDefs = function (colDef) {
// start with empty merged definition
var colDefMerged = {};
// merge properties from default column definitions
_.assign(colDefMerged, this.gridOptionsWrapper.getDefaultColDef());
// merge properties from column type properties
if (colDef.type) {
this.assignColumnTypes(colDef, colDefMerged);
}
// merge properties from column definitions
_.assign(colDefMerged, colDef);
return colDefMerged;
};
ColumnFactory.prototype.assignColumnTypes = function (colDef, colDefMerged) {
var typeKeys;
if (colDef.type instanceof Array) {
var invalidArray = colDef.type.some(function (a) { return typeof a !== 'string'; });
if (invalidArray) {
console.warn("ag-grid: if colDef.type is supplied an array it should be of type 'string[]'");
}
else {
typeKeys = colDef.type;
}
}
else if (typeof colDef.type === 'string') {
typeKeys = colDef.type.split(',');
}
else {
console.warn("ag-grid: colDef.type should be of type 'string' | 'string[]'");
return;
}
// merge user defined with default column types
var allColumnTypes = _.assign({}, this.gridOptionsWrapper.getColumnTypes(), DefaultColumnTypes);
typeKeys.forEach(function (t) {
var typeColDef = allColumnTypes[t.trim()];
if (typeColDef) {
_.assign(colDefMerged, typeColDef);
}
else {
console.warn("ag-grid: colDef.type '" + t + "' does not correspond to defined gridOptions.columnTypes");
}
});
};
ColumnFactory.prototype.checkForDeprecatedItems = function (colDef) {
if (colDef) {
var colDefNoType = colDef; // take out the type, so we can access attributes not defined in the type
if (colDefNoType.group !== undefined) {
console.warn('ag-grid: colDef.group is invalid, please check documentation on how to do grouping as it changed in version 3');
}
if (colDefNoType.headerGroup !== undefined) {
console.warn('ag-grid: colDef.headerGroup is invalid, please check documentation on how to do grouping as it changed in version 3');
}
if (colDefNoType.headerGroupShow !== undefined) {
console.warn('ag-grid: colDef.headerGroupShow is invalid, should be columnGroupShow, please check documentation on how to do grouping as it changed in version 3');
}
if (colDefNoType.suppressRowGroup !== undefined) {
console.warn('ag-grid: colDef.suppressRowGroup is deprecated, please use colDef.type instead');
}
if (colDefNoType.suppressAggregation !== undefined) {
console.warn('ag-grid: colDef.suppressAggregation is deprecated, please use colDef.type instead');
}
if (colDefNoType.suppressRowGroup || colDefNoType.suppressAggregation) {
console.warn('ag-grid: colDef.suppressAggregation and colDef.suppressRowGroup are deprecated, use allowRowGroup, allowPivot and allowValue instead');
}
if (colDefNoType.displayName) {
console.warn("ag-grid: Found displayName " + colDefNoType.displayName + ", please use headerName instead, displayName is deprecated.");
colDefNoType.headerName = colDefNoType.displayName;
}
}
};
// if object has children, we assume it's a group
ColumnFactory.prototype.isColumnGroup = function (abstractColDef) {
return abstractColDef.children !== undefined;
};
__decorate$3([
Autowired('gridOptionsWrapper')
], ColumnFactory.prototype, "gridOptionsWrapper", void 0);
__decorate$3([
Autowired('columnUtils')
], ColumnFactory.prototype, "columnUtils", void 0);
__decorate$3([
Autowired('context')
], ColumnFactory.prototype, "context", void 0);
__decorate$3([
__param$1(0, Qualifier('loggerFactory'))
], ColumnFactory.prototype, "setBeans", null);
ColumnFactory = __decorate$3([
Bean('columnFactory')
], ColumnFactory);
return ColumnFactory;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var Events = /** @class */ (function () {
function Events() {
}
/** Everything has changed with the columns. Either complete new set of columns set, or user called setState()*/
Events.EVENT_COLUMN_EVERYTHING_CHANGED = 'columnEverythingChanged';
/** User has set in new columns. */
Events.EVENT_NEW_COLUMNS_LOADED = 'newColumnsLoaded';
/** The pivot mode flag was changed */
Events.EVENT_COLUMN_PIVOT_MODE_CHANGED = 'columnPivotModeChanged';
/** A row group column was added, removed or order changed. */
Events.EVENT_COLUMN_ROW_GROUP_CHANGED = 'columnRowGroupChanged';
/** expandAll / collapseAll was called from the api. */
Events.EVENT_EXPAND_COLLAPSE_ALL = 'expandOrCollapseAll';
/** A pivot column was added, removed or order changed. */
Events.EVENT_COLUMN_PIVOT_CHANGED = 'columnPivotChanged';
/** The list of grid columns has changed. */
Events.EVENT_GRID_COLUMNS_CHANGED = 'gridColumnsChanged';
/** A value column was added, removed or agg function was changed. */
Events.EVENT_COLUMN_VALUE_CHANGED = 'columnValueChanged';
/** A column was moved */
Events.EVENT_COLUMN_MOVED = 'columnMoved';
/** One or more columns was shown / hidden */
Events.EVENT_COLUMN_VISIBLE = 'columnVisible';
/** One or more columns was pinned / unpinned*/
Events.EVENT_COLUMN_PINNED = 'columnPinned';
/** A column group was opened / closed */
Events.EVENT_COLUMN_GROUP_OPENED = 'columnGroupOpened';
/** One or more columns was resized. If just one, the column in the event is set. */
Events.EVENT_COLUMN_RESIZED = 'columnResized';
/** The list of displayed columns has changed, can result from columns open / close, column move, pivot, group, etc */
Events.EVENT_DISPLAYED_COLUMNS_CHANGED = 'displayedColumnsChanged';
/** The list of virtual columns has changed, results from viewport changing */
Events.EVENT_VIRTUAL_COLUMNS_CHANGED = 'virtualColumnsChanged';
/** A row group was opened / closed */
Events.EVENT_ROW_GROUP_OPENED = 'rowGroupOpened';
/** The client has set new data into the grid */
Events.EVENT_ROW_DATA_CHANGED = 'rowDataChanged';
/** The client has updated data for the grid */
Events.EVENT_ROW_DATA_UPDATED = 'rowDataUpdated';
/** The client has set new floating data into the grid */
Events.EVENT_PINNED_ROW_DATA_CHANGED = 'pinnedRowDataChanged';
/** Range selection has changed */
Events.EVENT_RANGE_SELECTION_CHANGED = 'rangeSelectionChanged';
/** Chart Range selection has changed */
Events.EVENT_CHART_RANGE_SELECTION_CHANGED = 'chartRangeSelectionChanged';
/** Chart Options have changed */
Events.EVENT_CHART_OPTIONS_CHANGED = 'chartOptionsChanged';
/** For when the tool panel is shown / hidden */
Events.EVENT_TOOL_PANEL_VISIBLE_CHANGED = 'toolPanelVisibleChanged';
/** Model was updated - grid updates the drawn rows when this happens */
Events.EVENT_MODEL_UPDATED = 'modelUpdated';
Events.EVENT_PASTE_START = 'pasteStart';
Events.EVENT_PASTE_END = 'pasteEnd';
Events.EVENT_FILL_START = 'fillStart';
Events.EVENT_FILL_END = 'fillEnd';
Events.EVENT_CELL_CLICKED = 'cellClicked';
Events.EVENT_CELL_DOUBLE_CLICKED = 'cellDoubleClicked';
Events.EVENT_CELL_MOUSE_DOWN = 'cellMouseDown';
Events.EVENT_CELL_CONTEXT_MENU = 'cellContextMenu';
Events.EVENT_CELL_VALUE_CHANGED = 'cellValueChanged';
Events.EVENT_ROW_VALUE_CHANGED = 'rowValueChanged';
Events.EVENT_CELL_FOCUSED = 'cellFocused';
Events.EVENT_ROW_SELECTED = 'rowSelected';
Events.EVENT_SELECTION_CHANGED = 'selectionChanged';
Events.EVENT_CELL_KEY_DOWN = 'cellKeyDown';
Events.EVENT_CELL_KEY_PRESS = 'cellKeyPress';
Events.EVENT_CELL_MOUSE_OVER = 'cellMouseOver';
Events.EVENT_CELL_MOUSE_OUT = 'cellMouseOut';
/** 2 events for filtering. The grid LISTENS for filterChanged and afterFilterChanged */
Events.EVENT_FILTER_CHANGED = 'filterChanged';
/** Filter was change but not applied. Only useful if apply buttons are used in filters. */
Events.EVENT_FILTER_MODIFIED = 'filterModified';
Events.EVENT_FILTER_OPENED = 'filterOpened';
Events.EVENT_SORT_CHANGED = 'sortChanged';
/** A row was removed from the dom, for any reason. Use to clean up resources (if any) used by the row. */
Events.EVENT_VIRTUAL_ROW_REMOVED = 'virtualRowRemoved';
Events.EVENT_ROW_CLICKED = 'rowClicked';
Events.EVENT_ROW_DOUBLE_CLICKED = 'rowDoubleClicked';
/** Gets called once after the grid has finished initialising. */
Events.EVENT_GRID_READY = 'gridReady';
/** Width of height of the main grid div has changed. Grid listens for this and does layout of grid if it's
* changed, so always filling the space it was given. */
Events.EVENT_GRID_SIZE_CHANGED = 'gridSizeChanged';
/** The indexes of the rows rendered has changed, eg user has scrolled to a new vertical position. */
Events.EVENT_VIEWPORT_CHANGED = 'viewportChanged';
/** Rows were rendered for the first time (ie on async data load). */
Events.EVENT_FIRST_DATA_RENDERED = 'firstDataRendered';
/** A column drag has started, either resizing a column or moving a column. */
Events.EVENT_DRAG_STARTED = 'dragStarted';
/** A column drag has stopped */
Events.EVENT_DRAG_STOPPED = 'dragStopped';
Events.EVENT_ROW_EDITING_STARTED = 'rowEditingStarted';
Events.EVENT_ROW_EDITING_STOPPED = 'rowEditingStopped';
Events.EVENT_CELL_EDITING_STARTED = 'cellEditingStarted';
Events.EVENT_CELL_EDITING_STOPPED = 'cellEditingStopped';
/** Main body of grid has scrolled, either horizontally or vertically */
Events.EVENT_BODY_SCROLL = 'bodyScroll';
Events.EVENT_ANIMATION_QUEUE_EMPTY = 'animationQueueEmpty';
Events.EVENT_HEIGHT_SCALE_CHANGED = 'heightScaleChanged';
/** The displayed page for pagination has changed. For example the data was filtered or sorted,
* or the user has moved to a different page. */
Events.EVENT_PAGINATION_CHANGED = 'paginationChanged';
/** Only used by React, Angular 2+, Web Components and VueJS ag-Grid components
* (not used if doing plain JavaScript or Angular 1.x). If the grid receives changes due
* to bound properties, this event fires after the grid has finished processing the change. */
Events.EVENT_COMPONENT_STATE_CHANGED = 'componentStateChanged';
/** All items from here down are used internally by the grid, not intended for external use. */
// not documented, either experimental, or we just don't want users using an depending on them
Events.EVENT_BODY_HEIGHT_CHANGED = 'bodyHeightChanged';
Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED = 'displayedColumnsWidthChanged';
Events.EVENT_SCROLL_VISIBILITY_CHANGED = 'scrollVisibilityChanged';
Events.EVENT_COLUMN_HOVER_CHANGED = 'columnHoverChanged';
Events.EVENT_FLASH_CELLS = 'flashCells';
Events.EVENT_ROW_DRAG_ENTER = 'rowDragEnter';
Events.EVENT_ROW_DRAG_MOVE = 'rowDragMove';
Events.EVENT_ROW_DRAG_LEAVE = 'rowDragLeave';
Events.EVENT_ROW_DRAG_END = 'rowDragEnd';
// primarily for charts
Events.EVENT_POPUP_TO_FRONT = 'popupToFront';
// these are used for server side group and agg - only used by CS with Viewport Row Model - intention is
// to design these better around server side functions and then release to general public when fully working with
// all the row models.
Events.EVENT_COLUMN_ROW_GROUP_CHANGE_REQUEST = 'columnRowGroupChangeRequest';
Events.EVENT_COLUMN_PIVOT_CHANGE_REQUEST = 'columnPivotChangeRequest';
Events.EVENT_COLUMN_VALUE_CHANGE_REQUEST = 'columnValueChangeRequest';
Events.EVENT_COLUMN_AGG_FUNC_CHANGE_REQUEST = 'columnAggFuncChangeRequest';
return Events;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
// class returns unique instance id's for columns.
// eg, the following calls (in this order) will result in:
//
// getInstanceIdForKey('country') => 0
// getInstanceIdForKey('country') => 1
// getInstanceIdForKey('country') => 2
// getInstanceIdForKey('country') => 3
// getInstanceIdForKey('age') => 0
// getInstanceIdForKey('age') => 1
// getInstanceIdForKey('country') => 4
var GroupInstanceIdCreator = /** @class */ (function () {
function GroupInstanceIdCreator() {
// this map contains keys to numbers, so we remember what the last call was
this.existingIds = {};
}
GroupInstanceIdCreator.prototype.getInstanceIdForKey = function (key) {
var lastResult = this.existingIds[key];
var result;
if (typeof lastResult !== 'number') {
// first time this key
result = 0;
}
else {
result = lastResult + 1;
}
this.existingIds[key] = result;
return result;
};
return GroupInstanceIdCreator;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate$4 = (undefined && undefined.__decorate) || function (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;
};
var __param$2 = (undefined && undefined.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var ColumnController = /** @class */ (function () {
function ColumnController() {
// header row count, based on user provided columns
this.primaryHeaderRowCount = 0;
this.secondaryHeaderRowCount = 0;
this.secondaryColumnsPresent = false;
// header row count, either above, or based on pivoting if we are pivoting
this.gridHeaderRowCount = 0;
// these are the lists used by the rowRenderer to render nodes. almost the leaf nodes of the above
// displayed trees, however it also takes into account if the groups are open or not.
this.displayedLeftColumns = [];
this.displayedRightColumns = [];
this.displayedCenterColumns = [];
// all three lists above combined
this.allDisplayedColumns = [];
// same as above, except trimmed down to only columns within the viewport
this.allDisplayedVirtualColumns = [];
this.allDisplayedCenterVirtualColumns = [];
this.rowGroupColumns = [];
this.valueColumns = [];
this.pivotColumns = [];
this.ready = false;
this.autoGroupsNeedBuilding = false;
this.pivotMode = false;
this.bodyWidth = 0;
this.leftWidth = 0;
this.rightWidth = 0;
this.bodyWidthDirty = true;
this.flexActive = false;
}
ColumnController.prototype.init = function () {
var pivotMode = this.gridOptionsWrapper.isPivotMode();
this.suppressColumnVirtualisation = this.gridOptionsWrapper.isSuppressColumnVirtualisation();
if (this.isPivotSettingAllowed(pivotMode)) {
this.pivotMode = pivotMode;
}
this.usingTreeData = this.gridOptionsWrapper.isTreeData();
};
ColumnController.prototype.setColumnDefs = function (columnDefs, source) {
if (source === void 0) { source = "api"; }
var colsPreviouslyExisted = !!this.columnDefs;
this.columnDefs = columnDefs;
// always invalidate cache on changing columns, as the column id's for the new columns
// could overlap with the old id's, so the cache would return old values for new columns.
this.valueCache.expire();
// NOTE ==================
// we should be destroying the existing columns and groups if they exist, for example, the original column
// group adds a listener to the columns, it should be also removing the listeners
this.autoGroupsNeedBuilding = true;
var oldPrimaryColumns = this.primaryColumns;
var balancedTreeResult = this.columnFactory.createColumnTree(columnDefs, true, oldPrimaryColumns);
this.primaryColumnTree = balancedTreeResult.columnTree;
this.primaryHeaderRowCount = balancedTreeResult.treeDept + 1;
this.primaryColumns = this.getColumnsFromTree(this.primaryColumnTree);
this.extractRowGroupColumns(source, oldPrimaryColumns);
this.extractPivotColumns(source, oldPrimaryColumns);
this.createValueColumns(source, oldPrimaryColumns);
this.ready = true;
this.updateGridColumns();
this.updateDisplayedColumns(source);
this.checkDisplayedVirtualColumns();
if (this.gridOptionsWrapper.isDeltaColumnMode() && colsPreviouslyExisted) {
this.resetColumnState(true, source);
}
var eventEverythingChanged = {
type: Events.EVENT_COLUMN_EVERYTHING_CHANGED,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(eventEverythingChanged);
var newColumnsLoadedEvent = {
type: Events.EVENT_NEW_COLUMNS_LOADED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(newColumnsLoadedEvent);
this.flexActive = !!_.find(this.getDisplayedCenterColumns(), function (col) { return !!col.getFlex(); });
};
ColumnController.prototype.isAutoRowHeightActive = function () {
return this.autoRowHeightColumns && this.autoRowHeightColumns.length > 0;
};
ColumnController.prototype.getAllAutoRowHeightCols = function () {
return this.autoRowHeightColumns;
};
ColumnController.prototype.setVirtualViewportLeftAndRight = function () {
if (this.gridOptionsWrapper.isEnableRtl()) {
this.viewportLeft = this.bodyWidth - this.scrollPosition - this.scrollWidth;
this.viewportRight = this.bodyWidth - this.scrollPosition;
}
else {
this.viewportLeft = this.scrollPosition;
this.viewportRight = this.scrollWidth + this.scrollPosition;
}
};
// used by clipboard service, to know what columns to paste into
ColumnController.prototype.getDisplayedColumnsStartingAt = function (column) {
var currentColumn = column;
var result = [];
while (currentColumn && _.exists(currentColumn)) {
result.push(currentColumn);
currentColumn = this.getDisplayedColAfter(currentColumn);
}
return result;
};
// checks what columns are currently displayed due to column virtualisation. fires an event
// if the list of columns has changed.
// + setColumnWidth(), setVirtualViewportPosition(), setColumnDefs(), sizeColumnsToFit()
ColumnController.prototype.checkDisplayedVirtualColumns = function () {
// check displayCenterColumnTree exists first, as it won't exist when grid is initialising
if (!_.exists(this.displayedCenterColumns)) {
return;
}
var hashBefore = this.allDisplayedVirtualColumns.map(function (column) { return column.getId(); }).join('#');
this.updateVirtualSets();
var hashAfter = this.allDisplayedVirtualColumns.map(function (column) { return column.getId(); }).join('#');
if (hashBefore !== hashAfter) {
var event_1 = {
type: Events.EVENT_VIRTUAL_COLUMNS_CHANGED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(event_1);
}
};
ColumnController.prototype.setVirtualViewportPosition = function (scrollWidth, scrollPosition) {
if (scrollWidth !== this.scrollWidth || scrollPosition !== this.scrollPosition || this.bodyWidthDirty) {
this.scrollWidth = scrollWidth;
this.scrollPosition = scrollPosition;
// we need to call setVirtualViewportLeftAndRight() at least once after the body width changes,
// as the viewport can stay the same, but in RTL, if body width changes, we need to work out the
// virtual columns again
this.bodyWidthDirty = true;
this.setVirtualViewportLeftAndRight();
if (this.ready) {
this.checkDisplayedVirtualColumns();
}
}
};
ColumnController.prototype.isPivotMode = function () {
return this.pivotMode;
};
ColumnController.prototype.isPivotSettingAllowed = function (pivot) {
if (pivot) {
if (this.gridOptionsWrapper.isTreeData()) {
console.warn("ag-Grid: Pivot mode not available in conjunction Tree Data i.e. 'gridOptions.treeData: true'");
return false;
}
return true;
}
return true;
};
ColumnController.prototype.setPivotMode = function (pivotMode, source) {
if (source === void 0) { source = "api"; }
if (pivotMode === this.pivotMode) {
return;
}
if (!this.isPivotSettingAllowed(this.pivotMode)) {
return;
}
this.pivotMode = pivotMode;
// we need to update grid columns to cover the scenario where user has groupSuppressAutoColumn=true, as
// this means we don't use auto group column UNLESS we are in pivot mode (it's mandatory in pivot mode),
// so need to updateGridColumn() to check it autoGroupCol needs to be added / removed
this.autoGroupsNeedBuilding = true;
this.updateGridColumns();
this.updateDisplayedColumns(source);
var event = {
type: Events.EVENT_COLUMN_PIVOT_MODE_CHANGED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.getSecondaryPivotColumn = function (pivotKeys, valueColKey) {
if (!this.secondaryColumnsPresent) {
return null;
}
var valueColumnToFind = this.getPrimaryColumn(valueColKey);
var foundColumn = null;
if (this.secondaryColumns) {
this.secondaryColumns.forEach(function (column) {
var thisPivotKeys = column.getColDef().pivotKeys;
var pivotValueColumn = column.getColDef().pivotValueColumn;
var pivotKeyMatches = _.compareArrays(thisPivotKeys, pivotKeys);
var pivotValueMatches = pivotValueColumn === valueColumnToFind;
if (pivotKeyMatches && pivotValueMatches) {
foundColumn = column;
}
});
}
return foundColumn;
};
ColumnController.prototype.setBeans = function (loggerFactory) {
this.logger = loggerFactory.create('ColumnController');
};
ColumnController.prototype.setFirstRightAndLastLeftPinned = function (source) {
var lastLeft;
var firstRight;
if (this.gridOptionsWrapper.isEnableRtl()) {
lastLeft = this.displayedLeftColumns ? this.displayedLeftColumns[0] : null;
firstRight = this.displayedRightColumns ? _.last(this.displayedRightColumns) : null;
}
else {
lastLeft = this.displayedLeftColumns ? _.last(this.displayedLeftColumns) : null;
firstRight = this.displayedRightColumns ? this.displayedRightColumns[0] : null;
}
this.gridColumns.forEach(function (column) {
column.setLastLeftPinned(column === lastLeft, source);
column.setFirstRightPinned(column === firstRight, source);
});
};
ColumnController.prototype.autoSizeColumns = function (keys, skipHeader, source) {
// because of column virtualisation, we can only do this function on columns that are
// actually rendered, as non-rendered columns (outside the viewport and not rendered
// due to column virtualisation) are not present. this can result in all rendered columns
// getting narrowed, which in turn introduces more rendered columns on the RHS which
// did not get autosized in the original run, leaving the visible grid with columns on
// the LHS sized, but RHS no. so we keep looping through the visible columns until
// no more cols are available (rendered) to be resized
var _this = this;
if (source === void 0) { source = "api"; }
// keep track of which cols we have resized in here
var columnsAutosized = [];
// initialise with anything except 0 so that while loop executes at least once
var changesThisTimeAround = -1;
if (skipHeader == null) {
skipHeader = this.gridOptionsWrapper.isSkipHeaderOnAutoSize();
}
while (changesThisTimeAround !== 0) {
changesThisTimeAround = 0;
this.actionOnGridColumns(keys, function (column) {
// if already autosized, skip it
if (columnsAutosized.indexOf(column) >= 0) {
return false;
}
// get how wide this col should be
var preferredWidth = _this.autoWidthCalculator.getPreferredWidthForColumn(column, skipHeader);
// preferredWidth = -1 if this col is not on the screen
if (preferredWidth > 0) {
var newWidth = _this.normaliseColumnWidth(column, preferredWidth);
column.setActualWidth(newWidth, source);
columnsAutosized.push(column);
changesThisTimeAround++;
}
return true;
}, source);
}
if (columnsAutosized.length) {
var event_2 = {
type: Events.EVENT_COLUMN_RESIZED,
columns: columnsAutosized,
column: columnsAutosized.length === 1 ? columnsAutosized[0] : null,
finished: true,
api: this.gridApi,
columnApi: this.columnApi,
source: "autosizeColumns"
};
this.eventService.dispatchEvent(event_2);
}
};
ColumnController.prototype.autoSizeColumn = function (key, skipHeader, source) {
if (source === void 0) { source = "api"; }
if (key) {
this.autoSizeColumns([key], skipHeader, source);
}
};
ColumnController.prototype.autoSizeAllColumns = function (skipHeader, source) {
if (source === void 0) { source = "api"; }
var allDisplayedColumns = this.getAllDisplayedColumns();
this.autoSizeColumns(allDisplayedColumns, skipHeader, source);
};
ColumnController.prototype.getColumnsFromTree = function (rootColumns) {
var result = [];
var recursiveFindColumns = function (childColumns) {
for (var i = 0; i < childColumns.length; i++) {
var child = childColumns[i];
if (child instanceof Column) {
result.push(child);
}
else if (child instanceof OriginalColumnGroup) {
recursiveFindColumns(child.getChildren());
}
}
};
recursiveFindColumns(rootColumns);
return result;
};
ColumnController.prototype.getAllDisplayedColumnGroups = function () {
if (this.displayedLeftColumnTree && this.displayedRightColumnTree && this.displayedCentreColumnTree) {
return this.displayedLeftColumnTree
.concat(this.displayedCentreColumnTree)
.concat(this.displayedRightColumnTree);
}
return null;
};
// + columnSelectPanel
ColumnController.prototype.getPrimaryColumnTree = function () {
return this.primaryColumnTree;
};
// + gridPanel -> for resizing the body and setting top margin
ColumnController.prototype.getHeaderRowCount = function () {
return this.gridHeaderRowCount;
};
// + headerRenderer -> setting pinned body width
ColumnController.prototype.getLeftDisplayedColumnGroups = function () {
return this.displayedLeftColumnTree;
};
// + headerRenderer -> setting pinned body width
ColumnController.prototype.getRightDisplayedColumnGroups = function () {
return this.displayedRightColumnTree;
};
// + headerRenderer -> setting pinned body width
ColumnController.prototype.getCenterDisplayedColumnGroups = function () {
return this.displayedCentreColumnTree;
};
ColumnController.prototype.getDisplayedColumnGroups = function (type) {
switch (type) {
case Constants.PINNED_LEFT:
return this.getLeftDisplayedColumnGroups();
case Constants.PINNED_RIGHT:
return this.getRightDisplayedColumnGroups();
default:
return this.getCenterDisplayedColumnGroups();
}
};
// gridPanel -> ensureColumnVisible
ColumnController.prototype.isColumnDisplayed = function (column) {
return this.getAllDisplayedColumns().indexOf(column) >= 0;
};
// + csvCreator
ColumnController.prototype.getAllDisplayedColumns = function () {
return this.allDisplayedColumns;
};
ColumnController.prototype.getAllDisplayedVirtualColumns = function () {
return this.allDisplayedVirtualColumns;
};
ColumnController.prototype.getDisplayedLeftColumnsForRow = function (rowNode) {
if (!this.colSpanActive) {
return this.displayedLeftColumns;
}
return this.getDisplayedColumnsForRow(rowNode, this.displayedLeftColumns);
};
ColumnController.prototype.getDisplayedRightColumnsForRow = function (rowNode) {
if (!this.colSpanActive) {
return this.displayedRightColumns;
}
return this.getDisplayedColumnsForRow(rowNode, this.displayedRightColumns);
};
ColumnController.prototype.getDisplayedColumnsForRow = function (rowNode, displayedColumns, filterCallback, emptySpaceBeforeColumn) {
var result = [];
var lastConsideredCol = null;
var _loop_1 = function (i) {
var col = displayedColumns[i];
var maxAllowedColSpan = displayedColumns.length - i;
var colSpan = Math.min(col.getColSpan(rowNode), maxAllowedColSpan);
var columnsToCheckFilter = [col];
if (colSpan > 1) {
var colsToRemove = colSpan - 1;
for (var j = 1; j <= colsToRemove; j++) {
columnsToCheckFilter.push(displayedColumns[i + j]);
}
i += colsToRemove;
}
// see which cols we should take out for column virtualisation
var filterPasses;
if (filterCallback) {
// if user provided a callback, means some columns may not be in the viewport.
// the user will NOT provide a callback if we are talking about pinned areas,
// as pinned areas have no horizontal scroll and do not virtualise the columns.
// if lots of columns, that means column spanning, and we set filterPasses = true
// if one or more of the columns spanned pass the filter.
filterPasses = false;
columnsToCheckFilter.forEach(function (colForFilter) {
if (filterCallback(colForFilter)) {
filterPasses = true;
}
});
}
else {
filterPasses = true;
}
if (filterPasses) {
if (result.length === 0 && lastConsideredCol) {
var gapBeforeColumn = emptySpaceBeforeColumn ? emptySpaceBeforeColumn(col) : false;
if (gapBeforeColumn) {
result.push(lastConsideredCol);
}
}
result.push(col);
}
lastConsideredCol = col;
out_i_1 = i;
};
var out_i_1;
for (var i = 0; i < displayedColumns.length; i++) {
_loop_1(i);
i = out_i_1;
}
return result;
};
// + rowRenderer
// if we are not column spanning, this just returns back the virtual centre columns,
// however if we are column spanning, then different rows can have different virtual
// columns, so we have to work out the list for each individual row.
ColumnController.prototype.getAllDisplayedCenterVirtualColumnsForRow = function (rowNode) {
var _this = this;
if (!this.colSpanActive) {
return this.allDisplayedCenterVirtualColumns;
}
var emptySpaceBeforeColumn = function (col) { return col.getLeft() > _this.viewportLeft; };
// if doing column virtualisation, then we filter based on the viewport.
var filterCallback = this.suppressColumnVirtualisation ? null : this.isColumnInViewport.bind(this);
return this.getDisplayedColumnsForRow(rowNode, this.displayedCenterColumns, filterCallback, emptySpaceBeforeColumn);
};
ColumnController.prototype.isColumnInViewport = function (col) {
var columnLeft = col.getLeft();
var columnRight = col.getLeft() + col.getActualWidth();
// adding 200 for buffer size, so some cols off viewport are rendered.
// this helps horizontal scrolling so user rarely sees white space (unless
// they scroll horizontally fast). however we are conservative, as the more
// buffer the slower the vertical redraw speed
var leftBounds = this.viewportLeft - 200;
var rightBounds = this.viewportRight + 200;
var columnToMuchLeft = columnLeft < leftBounds && columnRight < leftBounds;
var columnToMuchRight = columnLeft > rightBounds && columnRight > rightBounds;
return !columnToMuchLeft && !columnToMuchRight;
};
// used by:
// + angularGrid -> setting pinned body width
// note: this should be cached
ColumnController.prototype.getPinnedLeftContainerWidth = function () {
return this.getWidthOfColsInList(this.displayedLeftColumns);
};
// note: this should be cached
ColumnController.prototype.getPinnedRightContainerWidth = function () {
return this.getWidthOfColsInList(this.displayedRightColumns);
};
ColumnController.prototype.updatePrimaryColumnList = function (keys, masterList, actionIsAdd, columnCallback, eventType, source) {
var _this = this;
if (source === void 0) { source = "api"; }
if (!keys || _.missingOrEmpty(keys)) {
return;
}
var atLeastOne = false;
keys.forEach(function (key) {
var columnToAdd = _this.getPrimaryColumn(key);
if (!columnToAdd) {
return;
}
if (actionIsAdd) {
if (masterList.indexOf(columnToAdd) >= 0) {
return;
}
masterList.push(columnToAdd);
}
else {
if (masterList.indexOf(columnToAdd) < 0) {
return;
}
_.removeFromArray(masterList, columnToAdd);
}
columnCallback(columnToAdd);
atLeastOne = true;
});
if (!atLeastOne) {
return;
}
if (this.autoGroupsNeedBuilding) {
this.updateGridColumns();
}
this.updateDisplayedColumns(source);
var event = {
type: eventType,
columns: masterList,
column: masterList.length === 1 ? masterList[0] : null,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.setRowGroupColumns = function (colKeys, source) {
if (source === void 0) { source = "api"; }
this.autoGroupsNeedBuilding = true;
this.setPrimaryColumnList(colKeys, this.rowGroupColumns, Events.EVENT_COLUMN_ROW_GROUP_CHANGED, this.setRowGroupActive.bind(this), source);
};
ColumnController.prototype.setRowGroupActive = function (active, column, source) {
if (active === column.isRowGroupActive()) {
return;
}
column.setRowGroupActive(active, source);
if (!active && !this.gridOptionsWrapper.isSuppressMakeColumnVisibleAfterUnGroup()) {
column.setVisible(true, source);
}
};
ColumnController.prototype.addRowGroupColumn = function (key, source) {
if (source === void 0) { source = "api"; }
if (key) {
this.addRowGroupColumns([key], source);
}
};
ColumnController.prototype.addRowGroupColumns = function (keys, source) {
if (source === void 0) { source = "api"; }
this.autoGroupsNeedBuilding = true;
this.updatePrimaryColumnList(keys, this.rowGroupColumns, true, this.setRowGroupActive.bind(this, true), Events.EVENT_COLUMN_ROW_GROUP_CHANGED, source);
};
ColumnController.prototype.removeRowGroupColumns = function (keys, source) {
if (source === void 0) { source = "api"; }
this.autoGroupsNeedBuilding = true;
this.updatePrimaryColumnList(keys, this.rowGroupColumns, false, this.setRowGroupActive.bind(this, false), Events.EVENT_COLUMN_ROW_GROUP_CHANGED, source);
};
ColumnController.prototype.removeRowGroupColumn = function (key, source) {
if (source === void 0) { source = "api"; }
if (key) {
this.removeRowGroupColumns([key], source);
}
};
ColumnController.prototype.addPivotColumns = function (keys, source) {
if (source === void 0) { source = "api"; }
this.updatePrimaryColumnList(keys, this.pivotColumns, true, function (column) { return column.setPivotActive(true, source); }, Events.EVENT_COLUMN_PIVOT_CHANGED, source);
};
ColumnController.prototype.setPivotColumns = function (colKeys, source) {
if (source === void 0) { source = "api"; }
this.setPrimaryColumnList(colKeys, this.pivotColumns, Events.EVENT_COLUMN_PIVOT_CHANGED, function (added, column) {
column.setPivotActive(added, source);
}, source);
};
ColumnController.prototype.addPivotColumn = function (key, source) {
if (source === void 0) { source = "api"; }
this.addPivotColumns([key], source);
};
ColumnController.prototype.removePivotColumns = function (keys, source) {
if (source === void 0) { source = "api"; }
this.updatePrimaryColumnList(keys, this.pivotColumns, false, function (column) { return column.setPivotActive(false, source); }, Events.EVENT_COLUMN_PIVOT_CHANGED, source);
};
ColumnController.prototype.removePivotColumn = function (key, source) {
if (source === void 0) { source = "api"; }
this.removePivotColumns([key], source);
};
ColumnController.prototype.setPrimaryColumnList = function (colKeys, masterList, eventName, columnCallback, source) {
var _this = this;
masterList.length = 0;
if (_.exists(colKeys)) {
colKeys.forEach(function (key) {
var column = _this.getPrimaryColumn(key);
if (column) {
masterList.push(column);
}
});
}
this.primaryColumns.forEach(function (column) {
var added = masterList.indexOf(column) >= 0;
columnCallback(added, column);
});
if (this.autoGroupsNeedBuilding) {
this.updateGridColumns();
}
this.updateDisplayedColumns(source);
var event = {
type: eventName,
columns: masterList,
column: masterList.length === 1 ? masterList[0] : null,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.setValueColumns = function (colKeys, source) {
if (source === void 0) { source = "api"; }
this.setPrimaryColumnList(colKeys, this.valueColumns, Events.EVENT_COLUMN_VALUE_CHANGED, this.setValueActive.bind(this), source);
};
ColumnController.prototype.setValueActive = function (active, column, source) {
if (active === column.isValueActive()) {
return;
}
column.setValueActive(active, source);
if (active && !column.getAggFunc()) {
var defaultAggFunc = this.aggFuncService.getDefaultAggFunc(column);
column.setAggFunc(defaultAggFunc);
}
};
ColumnController.prototype.addValueColumns = function (keys, source) {
if (source === void 0) { source = "api"; }
this.updatePrimaryColumnList(keys, this.valueColumns, true, this.setValueActive.bind(this, true), Events.EVENT_COLUMN_VALUE_CHANGED, source);
};
ColumnController.prototype.addValueColumn = function (colKey, source) {
if (source === void 0) { source = "api"; }
if (colKey) {
this.addValueColumns([colKey], source);
}
};
ColumnController.prototype.removeValueColumn = function (colKey, source) {
if (source === void 0) { source = "api"; }
this.removeValueColumns([colKey], source);
};
ColumnController.prototype.removeValueColumns = function (keys, source) {
if (source === void 0) { source = "api"; }
this.updatePrimaryColumnList(keys, this.valueColumns, false, this.setValueActive.bind(this, false), Events.EVENT_COLUMN_VALUE_CHANGED, source);
};
// returns the width we can set to this col, taking into consideration min and max widths
ColumnController.prototype.normaliseColumnWidth = function (column, newWidth) {
if (newWidth < column.getMinWidth()) {
newWidth = column.getMinWidth();
}
if (column.isGreaterThanMax(newWidth)) {
newWidth = column.getMaxWidth();
}
return newWidth;
};
ColumnController.prototype.getPrimaryOrGridColumn = function (key) {
var column = this.getPrimaryColumn(key);
return column || this.getGridColumn(key);
};
ColumnController.prototype.setColumnWidth = function (key, // @key - the column who's size we want to change
newWidth, // @newWidth - width in pixels
shiftKey, // @takeFromAdjacent - if user has 'shift' pressed, then pixels are taken from adjacent column
finished, // @finished - ends up in the event, tells the user if more events are to come
source) {
if (source === void 0) { source = "api"; }
var col = this.getPrimaryOrGridColumn(key);
if (!col) {
return;
}
var sets = [];
sets.push({
width: newWidth,
ratios: [1],
columns: [col]
});
// if user wants to do shift resize by default, then we invert the shift operation
var defaultIsShift = this.gridOptionsWrapper.getColResizeDefault() === 'shift';
if (defaultIsShift) {
shiftKey = !shiftKey;
}
if (shiftKey) {
var otherCol = this.getDisplayedColAfter(col);
if (!otherCol) {
return;
}
var widthDiff = col.getActualWidth() - newWidth;
var otherColWidth = otherCol.getActualWidth() + widthDiff;
sets.push({
width: otherColWidth,
ratios: [1],
columns: [otherCol]
});
}
this.resizeColumnSets(sets, finished, source);
if (this.flexActive) {
this.refreshFlexedColumns();
}
};
ColumnController.prototype.checkMinAndMaxWidthsForSet = function (columnResizeSet) {
var columns = columnResizeSet.columns, width = columnResizeSet.width;
// every col has a min width, so sum them all up and see if we have enough room
// for all the min widths
var minWidthAccumulated = 0;
var maxWidthAccumulated = 0;
var maxWidthActive = true;
columns.forEach(function (col) {
minWidthAccumulated += col.getMinWidth();
if (col.getMaxWidth() > 0) {
maxWidthAccumulated += col.getMaxWidth();
}
else {
// if at least one columns has no max width, it means the group of columns
// then has no max width, as at least one column can take as much width as possible
maxWidthActive = false;
}
});
var minWidthPasses = width >= minWidthAccumulated;
var maxWidthPasses = !maxWidthActive || (width <= maxWidthAccumulated);
return minWidthPasses && maxWidthPasses;
};
// method takes sets of columns and resizes them. either all sets will be resized, or nothing
// be resized. this is used for example when user tries to resize a group and holds shift key,
// then both the current group (grows), and the adjacent group (shrinks), will get resized,
// so that's two sets for this method.
ColumnController.prototype.resizeColumnSets = function (resizeSets, finished, source) {
var passMinMaxCheck = _.every(resizeSets, this.checkMinAndMaxWidthsForSet.bind(this));
if (!passMinMaxCheck) {
// even though we are not going to resize beyond min/max size, we still need to raise event when finished
if (finished) {
var columns = resizeSets && resizeSets.length > 0 ? resizeSets[0].columns : null;
var event_3 = {
type: Events.EVENT_COLUMN_RESIZED,
columns: columns,
column: columns && columns.length === 1 ? columns[0] : null,
finished: finished,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event_3);
}
return; // don't resize!
}
var changedCols = [];
var allCols = [];
resizeSets.forEach(function (set) {
var width = set.width, columns = set.columns, ratios = set.ratios;
// keep track of pixels used, and last column gets the remaining,
// to cater for rounding errors, and min width adjustments
var newWidths = {};
var finishedCols = {};
columns.forEach(function (col) { return allCols.push(col); });
// the loop below goes through each col. if a col exceeds it's min/max width,
// it then gets set to its min/max width and the column is removed marked as 'finished'
// and the calculation is done again leaving this column out. take for example columns
// {A, width: 50, maxWidth: 100}
// {B, width: 50}
// {C, width: 50}
// and then the set is set to width 600 - on the first pass the grid tries to set each column
// to 200. it checks A and sees 200 > 100 and so sets the width to 100. col A is then marked
// as 'finished' and the calculation is done again with the remaining cols B and C, which end up
// splitting the remaining 500 pixels.
var finishedColsGrew = true;
var loopCount = 0;
var _loop_2 = function () {
loopCount++;
if (loopCount > 1000) {
// this should never happen, but in the future, someone might introduce a bug here,
// so we stop the browser from hanging and report bug properly
console.error('ag-Grid: infinite loop in resizeColumnSets');
return "break";
}
finishedColsGrew = false;
var subsetCols = [];
var subsetRatioTotal = 0;
var pixelsToDistribute = width;
columns.forEach(function (col, index) {
var thisColFinished = finishedCols[col.getId()];
if (thisColFinished) {
pixelsToDistribute -= newWidths[col.getId()];
}
else {
subsetCols.push(col);
var ratioThisCol = ratios[index];
subsetRatioTotal += ratioThisCol;
}
});
// because we are not using all of the ratios (cols can be missing),
// we scale the ratio. if all columns are included, then subsetRatioTotal=1,
// and so the ratioScale will be 1.
var ratioScale = 1 / subsetRatioTotal;
subsetCols.forEach(function (col, index) {
var lastCol = index === (subsetCols.length - 1);
var colNewWidth;
if (lastCol) {
colNewWidth = pixelsToDistribute;
}
else {
colNewWidth = Math.round(ratios[index] * width * ratioScale);
pixelsToDistribute -= colNewWidth;
}
if (colNewWidth < col.getMinWidth()) {
colNewWidth = col.getMinWidth();
finishedCols[col.getId()] = true;
finishedColsGrew = true;
}
else if (col.getMaxWidth() > 0 && colNewWidth > col.getMaxWidth()) {
colNewWidth = col.getMaxWidth();
finishedCols[col.getId()] = true;
finishedColsGrew = true;
}
newWidths[col.getId()] = colNewWidth;
});
};
while (finishedColsGrew) {
var state_1 = _loop_2();
if (state_1 === "break")
break;
}
columns.forEach(function (col) {
var newWidth = newWidths[col.getId()];
if (col.getActualWidth() !== newWidth) {
col.setActualWidth(newWidth, source);
changedCols.push(col);
}
});
});
// if no cols changed, then no need to update more or send event.
var atLeastOneColChanged = changedCols.length > 0;
if (atLeastOneColChanged) {
this.setLeftValues(source);
this.updateBodyWidths();
this.checkDisplayedVirtualColumns();
}
// check for change first, to avoid unnecessary firing of events
// however we always fire 'finished' events. this is important
// when groups are resized, as if the group is changing slowly,
// eg 1 pixel at a time, then each change will fire change events
// in all the columns in the group, but only one with get the pixel.
if (atLeastOneColChanged || finished) {
var event_4 = {
type: Events.EVENT_COLUMN_RESIZED,
columns: allCols,
column: allCols.length === 1 ? allCols[0] : null,
finished: finished,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event_4);
}
};
ColumnController.prototype.setColumnAggFunc = function (column, aggFunc, source) {
if (source === void 0) { source = "api"; }
if (!column) {
return;
}
column.setAggFunc(aggFunc);
var event = {
type: Events.EVENT_COLUMN_VALUE_CHANGED,
columns: [column],
column: column,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.moveRowGroupColumn = function (fromIndex, toIndex, source) {
if (source === void 0) { source = "api"; }
var column = this.rowGroupColumns[fromIndex];
this.rowGroupColumns.splice(fromIndex, 1);
this.rowGroupColumns.splice(toIndex, 0, column);
var event = {
type: Events.EVENT_COLUMN_ROW_GROUP_CHANGED,
columns: this.rowGroupColumns,
column: this.rowGroupColumns.length === 1 ? this.rowGroupColumns[0] : null,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.moveColumns = function (columnsToMoveKeys, toIndex, source) {
if (source === void 0) { source = "api"; }
this.columnAnimationService.start();
if (toIndex > this.gridColumns.length - columnsToMoveKeys.length) {
console.warn('ag-Grid: tried to insert columns in invalid location, toIndex = ' + toIndex);
console.warn('ag-Grid: remember that you should not count the moving columns when calculating the new index');
return;
}
// we want to pull all the columns out first and put them into an ordered list
var columnsToMove = this.getGridColumns(columnsToMoveKeys);
var failedRules = !this.doesMovePassRules(columnsToMove, toIndex);
if (failedRules) {
return;
}
_.moveInArray(this.gridColumns, columnsToMove, toIndex);
this.updateDisplayedColumns(source);
var event = {
type: Events.EVENT_COLUMN_MOVED,
columns: columnsToMove,
column: columnsToMove.length === 1 ? columnsToMove[0] : null,
toIndex: toIndex,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event);
this.columnAnimationService.finish();
};
ColumnController.prototype.doesMovePassRules = function (columnsToMove, toIndex) {
// make a copy of what the grid columns would look like after the move
var proposedColumnOrder = this.gridColumns.slice();
_.moveInArray(proposedColumnOrder, columnsToMove, toIndex);
// then check that the new proposed order of the columns passes all rules
if (!this.doesMovePassMarryChildren(proposedColumnOrder)) {
return false;
}
if (!this.doesMovePassLockedPositions(proposedColumnOrder)) {
return false;
}
return true;
};
ColumnController.prototype.doesMovePassLockedPositions = function (proposedColumnOrder) {
var foundNonLocked = false;
var rulePassed = true;
// go though the cols, see if any non-locked appear before any locked
proposedColumnOrder.forEach(function (col) {
if (col.getColDef().lockPosition) {
if (foundNonLocked) {
rulePassed = false;
}
}
else {
foundNonLocked = true;
}
});
return rulePassed;
};
ColumnController.prototype.doesMovePassMarryChildren = function (allColumnsCopy) {
var rulePassed = true;
this.columnUtils.depthFirstOriginalTreeSearch(null, this.gridBalancedTree, function (child) {
if (!(child instanceof OriginalColumnGroup)) {
return;
}
var columnGroup = child;
var marryChildren = columnGroup.getColGroupDef() && columnGroup.getColGroupDef().marryChildren;
if (!marryChildren) {
return;
}
var newIndexes = [];
columnGroup.getLeafColumns().forEach(function (col) {
var newColIndex = allColumnsCopy.indexOf(col);
newIndexes.push(newColIndex);
});
var maxIndex = Math.max.apply(Math, newIndexes);
var minIndex = Math.min.apply(Math, newIndexes);
// spread is how far the first column in this group is away from the last column
var spread = maxIndex - minIndex;
var maxSpread = columnGroup.getLeafColumns().length - 1;
// if the columns
if (spread > maxSpread) {
rulePassed = false;
}
// console.log(`maxIndex = ${maxIndex}, minIndex = ${minIndex}, spread = ${spread}, maxSpread = ${maxSpread}, fail = ${spread > (count-1)}`)
// console.log(allColumnsCopy.map( col => col.getColDef().field).join(','));
});
return rulePassed;
};
ColumnController.prototype.moveColumn = function (key, toIndex, source) {
if (source === void 0) { source = "api"; }
this.moveColumns([key], toIndex, source);
};
ColumnController.prototype.moveColumnByIndex = function (fromIndex, toIndex, source) {
if (source === void 0) { source = "api"; }
var column = this.gridColumns[fromIndex];
this.moveColumn(column, toIndex, source);
};
// used by:
// + angularGrid -> for setting body width
// + rowController -> setting main row widths (when inserting and resizing)
// need to cache this
ColumnController.prototype.getBodyContainerWidth = function () {
return this.bodyWidth;
};
ColumnController.prototype.getContainerWidth = function (pinned) {
switch (pinned) {
case Constants.PINNED_LEFT:
return this.leftWidth;
case Constants.PINNED_RIGHT:
return this.rightWidth;
default:
return this.bodyWidth;
}
};
// after setColumnWidth or updateGroupsAndDisplayedColumns
ColumnController.prototype.updateBodyWidths = function () {
var newBodyWidth = this.getWidthOfColsInList(this.displayedCenterColumns);
var newLeftWidth = this.getWidthOfColsInList(this.displayedLeftColumns);
var newRightWidth = this.getWidthOfColsInList(this.displayedRightColumns);
// this is used by virtual col calculation, for RTL only, as a change to body width can impact displayed
// columns, due to RTL inverting the y coordinates
this.bodyWidthDirty = this.bodyWidth !== newBodyWidth;
var atLeastOneChanged = this.bodyWidth !== newBodyWidth || this.leftWidth !== newLeftWidth || this.rightWidth !== newRightWidth;
if (atLeastOneChanged) {
this.bodyWidth = newBodyWidth;
this.leftWidth = newLeftWidth;
this.rightWidth = newRightWidth;
// when this fires, it is picked up by the gridPanel, which ends up in
// gridPanel calling setWidthAndScrollPosition(), which in turn calls setVirtualViewportPosition()
var event_5 = {
type: Events.EVENT_DISPLAYED_COLUMNS_WIDTH_CHANGED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(event_5);
}
};
// + rowController
ColumnController.prototype.getValueColumns = function () {
return this.valueColumns ? this.valueColumns : [];
};
// + rowController
ColumnController.prototype.getPivotColumns = function () {
return this.pivotColumns ? this.pivotColumns : [];
};
// + clientSideRowModel
ColumnController.prototype.isPivotActive = function () {
return this.pivotColumns && this.pivotColumns.length > 0 && this.pivotMode;
};
// + toolPanel
ColumnController.prototype.getRowGroupColumns = function () {
return this.rowGroupColumns ? this.rowGroupColumns : [];
};
// + rowController -> while inserting rows
ColumnController.prototype.getDisplayedCenterColumns = function () {
return this.displayedCenterColumns;
};
// + rowController -> while inserting rows
ColumnController.prototype.getDisplayedLeftColumns = function () {
return this.displayedLeftColumns;
};
ColumnController.prototype.getDisplayedRightColumns = function () {
return this.displayedRightColumns;
};
ColumnController.prototype.getDisplayedColumns = function (type) {
switch (type) {
case Constants.PINNED_LEFT:
return this.getDisplayedLeftColumns();
case Constants.PINNED_RIGHT:
return this.getDisplayedRightColumns();
default:
return this.getDisplayedCenterColumns();
}
};
// used by:
// + clientSideRowController -> sorting, building quick filter text
// + headerRenderer -> sorting (clearing icon)
ColumnController.prototype.getAllPrimaryColumns = function () {
return this.primaryColumns ? this.primaryColumns.slice() : null;
};
ColumnController.prototype.getSecondaryColumns = function () {
return this.secondaryColumns ? this.secondaryColumns.slice() : null;
};
ColumnController.prototype.getAllColumnsForQuickFilter = function () {
return this.columnsForQuickFilter;
};
// + moveColumnController
ColumnController.prototype.getAllGridColumns = function () {
return this.gridColumns;
};
ColumnController.prototype.isEmpty = function () {
return _.missingOrEmpty(this.gridColumns);
};
ColumnController.prototype.isRowGroupEmpty = function () {
return _.missingOrEmpty(this.rowGroupColumns);
};
ColumnController.prototype.setColumnVisible = function (key, visible, source) {
if (source === void 0) { source = "api"; }
this.setColumnsVisible([key], visible, source);
};
ColumnController.prototype.setColumnsVisible = function (keys, visible, source) {
var _this = this;
if (source === void 0) { source = "api"; }
this.columnAnimationService.start();
this.actionOnGridColumns(keys, function (column) {
if (column.isVisible() !== visible) {
column.setVisible(visible, source);
return true;
}
return false;
}, source, function () {
var event = {
type: Events.EVENT_COLUMN_VISIBLE,
visible: visible,
column: null,
columns: null,
api: _this.gridApi,
columnApi: _this.columnApi,
source: source
};
return event;
});
this.columnAnimationService.finish();
};
ColumnController.prototype.setColumnPinned = function (key, pinned, source) {
if (source === void 0) { source = "api"; }
if (key) {
this.setColumnsPinned([key], pinned, source);
}
};
ColumnController.prototype.setColumnsPinned = function (keys, pinned, source) {
var _this = this;
if (source === void 0) { source = "api"; }
if (this.gridOptionsWrapper.getDomLayout() === 'print') {
console.warn("Changing the column pinning status is not allowed with domLayout='print'");
return;
}
this.columnAnimationService.start();
var actualPinned;
if (pinned === true || pinned === Constants.PINNED_LEFT) {
actualPinned = Constants.PINNED_LEFT;
}
else if (pinned === Constants.PINNED_RIGHT) {
actualPinned = Constants.PINNED_RIGHT;
}
else {
actualPinned = null;
}
this.actionOnGridColumns(keys, function (col) {
if (col.getPinned() !== actualPinned) {
col.setPinned(actualPinned);
return true;
}
return false;
}, source, function () {
var event = {
type: Events.EVENT_COLUMN_PINNED,
pinned: actualPinned,
column: null,
columns: null,
api: _this.gridApi,
columnApi: _this.columnApi,
source: source
};
return event;
});
this.columnAnimationService.finish();
};
// does an action on a set of columns. provides common functionality for looking up the
// columns based on key, getting a list of effected columns, and then updated the event
// with either one column (if it was just one col) or a list of columns
// used by: autoResize, setVisible, setPinned
ColumnController.prototype.actionOnGridColumns = function (// the column keys this action will be on
keys,
// the action to do - if this returns false, the column was skipped
// and won't be included in the event
action,
// should return back a column event of the right type
source, createEvent) {
var _this = this;
if (_.missingOrEmpty(keys)) {
return;
}
var updatedColumns = [];
keys.forEach(function (key) {
var column = _this.getGridColumn(key);
if (!column) {
return;
}
// need to check for false with type (ie !== instead of !=)
// as not returning anything (undefined) would also be false
var resultOfAction = action(column);
if (resultOfAction !== false) {
updatedColumns.push(column);
}
});
if (!updatedColumns.length) {
return;
}
this.updateDisplayedColumns(source);
if (_.exists(createEvent) && createEvent) {
var event_6 = createEvent();
event_6.columns = updatedColumns;
event_6.column = updatedColumns.length === 1 ? updatedColumns[0] : null;
this.eventService.dispatchEvent(event_6);
}
};
ColumnController.prototype.getDisplayedColBefore = function (col) {
var allDisplayedColumns = this.getAllDisplayedColumns();
var oldIndex = allDisplayedColumns.indexOf(col);
if (oldIndex > 0) {
return allDisplayedColumns[oldIndex - 1];
}
return null;
};
// used by:
// + rowRenderer -> for navigation
ColumnController.prototype.getDisplayedColAfter = function (col) {
var allDisplayedColumns = this.getAllDisplayedColumns();
var oldIndex = allDisplayedColumns.indexOf(col);
if (oldIndex < (allDisplayedColumns.length - 1)) {
return allDisplayedColumns[oldIndex + 1];
}
return null;
};
ColumnController.prototype.getDisplayedGroupAfter = function (columnGroup) {
// pick one col in this group at random
var col = columnGroup.getDisplayedLeafColumns()[0];
var requiredLevel = columnGroup.getOriginalColumnGroup().getLevel();
while (true) {
// keep moving to the next col, until we get to another group
col = this.getDisplayedColAfter(col);
// if no col after, means no group after
if (!col) {
return null;
}
// get group at same level as the one we are looking for
var groupPointer = col.getParent();
while (groupPointer.getOriginalColumnGroup().getLevel() !== requiredLevel) {
groupPointer = groupPointer.getParent();
}
if (groupPointer !== columnGroup) {
return groupPointer;
}
}
};
ColumnController.prototype.isPinningLeft = function () {
return this.displayedLeftColumns.length > 0;
};
ColumnController.prototype.isPinningRight = function () {
return this.displayedRightColumns.length > 0;
};
ColumnController.prototype.getPrimaryAndSecondaryAndAutoColumns = function () {
var result = this.primaryColumns ? this.primaryColumns.slice(0) : [];
if (this.groupAutoColumns && _.exists(this.groupAutoColumns)) {
this.groupAutoColumns.forEach(function (col) { return result.push(col); });
}
if (this.secondaryColumnsPresent && this.secondaryColumns) {
this.secondaryColumns.forEach(function (column) { return result.push(column); });
}
return result;
};
ColumnController.prototype.createStateItemFromColumn = function (column) {
var rowGroupIndex = column.isRowGroupActive() ? this.rowGroupColumns.indexOf(column) : null;
var pivotIndex = column.isPivotActive() ? this.pivotColumns.indexOf(column) : null;
var aggFunc = column.isValueActive() ? column.getAggFunc() : null;
return {
colId: column.getColId(),
hide: !column.isVisible(),
aggFunc: aggFunc,
width: column.getActualWidth(),
pivotIndex: pivotIndex,
pinned: column.getPinned(),
rowGroupIndex: rowGroupIndex
};
};
ColumnController.prototype.getColumnState = function () {
if (_.missing(this.primaryColumns)) {
return [];
}
var primaryColumnState = this.primaryColumns.map(this.createStateItemFromColumn.bind(this));
var groupAutoColumnState = this.groupAutoColumns
// if groupAutoCols, then include them
? this.groupAutoColumns.map(this.createStateItemFromColumn.bind(this))
// otherwise no
: [];
var columnStateList = groupAutoColumnState.concat(primaryColumnState);
if (!this.pivotMode) {
this.orderColumnStateList(columnStateList);
}
return columnStateList;
};
ColumnController.prototype.orderColumnStateList = function (columnStateList) {
var gridColumnIds = this.gridColumns.map(function (column) { return column.getColId(); });
columnStateList.sort(function (itemA, itemB) {
var posA = gridColumnIds.indexOf(itemA.colId);
var posB = gridColumnIds.indexOf(itemB.colId);
return posA - posB;
});
};
ColumnController.prototype.resetColumnState = function (suppressEverythingEvent, source) {
// NOTE = there is one bug here that no customer has noticed - if a column has colDef.lockPosition,
// this is ignored below when ordering the cols. to work, we should always put lockPosition cols first.
// As a work around, developers should just put lockPosition columns first in their colDef list.
if (suppressEverythingEvent === void 0) { suppressEverythingEvent = false; }
if (source === void 0) { source = "api"; }
// we can't use 'allColumns' as the order might of messed up, so get the primary ordered list
var primaryColumns = this.getColumnsFromTree(this.primaryColumnTree);
var columnStates = [];
// we start at 1000, so if user has mix of rowGroup and group specified, it will work with both.
// eg IF user has ColA.rowGroupIndex=0, ColB.rowGroupIndex=1, ColC.rowGroup=true,
// THEN result will be ColA.rowGroupIndex=0, ColB.rowGroupIndex=1, ColC.rowGroup=1000
var letRowGroupIndex = 1000;
var letPivotIndex = 1000;
if (primaryColumns) {
primaryColumns.forEach(function (column) {
var rowGroupIndex = column.getColDef().rowGroupIndex;
var rowGroup = column.getColDef().rowGroup;
var pivotIndex = column.getColDef().pivotIndex;
var pivot = column.getColDef().pivot;
var stateItem = {
colId: column.getColId(),
aggFunc: column.getColDef().aggFunc,
hide: column.getColDef().hide,
pinned: column.getColDef().pinned,
rowGroupIndex: rowGroupIndex,
pivotIndex: column.getColDef().pivotIndex,
width: column.getColDef().width
};
if (_.missing(rowGroupIndex) && rowGroup) {
stateItem.rowGroupIndex = letRowGroupIndex++;
}
if (_.missing(pivotIndex) && pivot) {
stateItem.pivotIndex = letPivotIndex++;
}
columnStates.push(stateItem);
});
}
this.setColumnState(columnStates, suppressEverythingEvent, source);
};
ColumnController.prototype.setColumnState = function (columnStates, suppressEverythingEvent, source) {
var _this = this;
if (suppressEverythingEvent === void 0) { suppressEverythingEvent = false; }
if (source === void 0) { source = "api"; }
if (_.missingOrEmpty(this.primaryColumns)) {
return false;
}
var columnStateBefore = this.getColumnState();
this.autoGroupsNeedBuilding = true;
// at the end below, this list will have all columns we got no state for
var columnsWithNoState = this.primaryColumns.slice();
this.rowGroupColumns = [];
this.valueColumns = [];
this.pivotColumns = [];
var success = true;
var rowGroupIndexes = {};
var pivotIndexes = {};
var autoGroupColumnStates = [];
if (columnStates) {
columnStates.forEach(function (state) {
// auto group columns are re-created so deferring syncing with ColumnState
if (_.exists(_this.getAutoColumn(state.colId))) {
autoGroupColumnStates.push(state);
return;
}
var column = _this.getPrimaryColumn(state.colId);
if (!column) {
console.warn('ag-grid: column ' + state.colId + ' not found');
success = false;
}
else {
_this.syncColumnWithStateItem(column, state, rowGroupIndexes, pivotIndexes, source);
_.removeFromArray(columnsWithNoState, column);
}
});
}
// anything left over, we got no data for, so add in the column as non-value, non-rowGroup and hidden
columnsWithNoState.forEach(this.syncColumnWithNoState.bind(this));
// sort the lists according to the indexes that were provided
this.rowGroupColumns.sort(this.sortColumnListUsingIndexes.bind(this, rowGroupIndexes));
this.pivotColumns.sort(this.sortColumnListUsingIndexes.bind(this, pivotIndexes));
this.updateGridColumns();
// sync newly created auto group columns with ColumnState
autoGroupColumnStates.forEach(function (stateItem) {
var autoCol = _this.getAutoColumn(stateItem.colId);
_this.syncColumnWithStateItem(autoCol, stateItem, rowGroupIndexes, pivotIndexes, source);
});
if (columnStates) {
var orderOfColIds_1 = columnStates.map(function (stateItem) { return stateItem.colId; });
this.gridColumns.sort(function (colA, colB) {
var indexA = orderOfColIds_1.indexOf(colA.getId());
var indexB = orderOfColIds_1.indexOf(colB.getId());
return indexA - indexB;
});
}
// this is already done in updateGridColumns, however we changed the order above (to match the order of the state
// columns) so we need to do it again. we could of put logic into the order above to take into account fixed
// columns, however if we did then we would have logic for updating fixed columns twice. reusing the logic here
// is less sexy for the code here, but it keeps consistency.
this.putFixedColumnsFirst();
this.updateDisplayedColumns(source);
if (!suppressEverythingEvent) {
var event_7 = {
type: Events.EVENT_COLUMN_EVERYTHING_CHANGED,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event_7);
}
this.raiseColumnEvents(columnStateBefore, source);
return success;
};
ColumnController.prototype.raiseColumnEvents = function (columnStateBefore, source) {
var _this = this;
if (this.gridOptionsWrapper.isSuppressSetColumnStateEvents()) {
return;
}
var columnStateAfter = this.getColumnState();
// raises generic ColumnEvents where all columns are returned rather than what has changed
var raiseEventWithAllColumns = function (eventType, idMapper, columns) {
var unchanged = _.compareArrays(columnStateBefore.map(idMapper).sort(), columnStateAfter.map(idMapper).sort());
if (unchanged) {
return;
}
// returning all columns rather than what has changed!
var event = {
type: eventType,
columns: columns,
column: columns.length === 1 ? columns[0] : null,
api: _this.gridApi,
columnApi: _this.columnApi,
source: source
};
_this.eventService.dispatchEvent(event);
};
// determines which columns have changed according to supplied predicate
var getChangedColumns = function (changedPredicate) {
var changedColumns = [];
var columnStateBeforeMap = {};
columnStateBefore.forEach(function (col) {
columnStateBeforeMap[col.colId] = col;
});
_this.gridColumns.forEach(function (column) {
var colStateBefore = columnStateBeforeMap[column.getColId()];
if (!colStateBefore || changedPredicate(colStateBefore, column)) {
changedColumns.push(column);
}
});
return changedColumns;
};
// generic ColumnEvents which return current column list
var valueColumnIdMapper = function (cs) { return cs.colId + '-' + cs.aggFunc; };
raiseEventWithAllColumns(Events.EVENT_COLUMN_VALUE_CHANGED, valueColumnIdMapper, this.valueColumns);
var pivotColumnIdMapper = function (cs) { return cs.colId + '-' + cs.pivotIndex; };
raiseEventWithAllColumns(Events.EVENT_COLUMN_PIVOT_CHANGED, pivotColumnIdMapper, this.pivotColumns);
var rowGroupColumnIdMapper = function (cs) { return cs.colId + '-' + cs.rowGroupIndex; };
raiseEventWithAllColumns(Events.EVENT_COLUMN_ROW_GROUP_CHANGED, rowGroupColumnIdMapper, this.rowGroupColumns);
// specific ColumnEvents which return what's changed
var pinnedChangePredicate = function (cs, c) { return cs.pinned !== c.getPinned(); };
this.raiseColumnPinnedEvent(getChangedColumns(pinnedChangePredicate), source);
var visibilityChangePredicate = function (cs, c) { return cs.hide === c.isVisible(); };
var cols = getChangedColumns(visibilityChangePredicate);
this.raiseColumnVisibleEvent(cols, source);
var resizeChangePredicate = function (cs, c) { return cs.width !== c.getActualWidth(); };
this.raiseColumnResizeEvent(getChangedColumns(resizeChangePredicate), source);
// special handling for moved column events
this.raiseColumnMovedEvent(columnStateBefore, source);
};
ColumnController.prototype.raiseColumnPinnedEvent = function (changedColumns, source) {
if (!changedColumns.length) {
return;
}
var event = {
type: Events.EVENT_COLUMN_PINNED,
pinned: null,
columns: changedColumns,
column: null,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.raiseColumnVisibleEvent = function (changedColumns, source) {
if (!changedColumns.length) {
return;
}
var event = {
type: Events.EVENT_COLUMN_VISIBLE,
visible: undefined,
columns: changedColumns,
column: null,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.raiseColumnResizeEvent = function (changedColumns, source) {
if (!changedColumns.length) {
return;
}
var event = {
type: Events.EVENT_COLUMN_RESIZED,
columns: changedColumns,
column: null,
finished: true,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.raiseColumnMovedEvent = function (columnStateBefore, source) {
var movedColumns = [];
var columnStateAfter = this.getColumnState();
var _loop_3 = function (i) {
var before = columnStateBefore[i];
var after = columnStateAfter[i];
// don't consider column if reintroduced or hidden
if (!before || after.hide) {
return "continue";
}
if (before.colId !== after.colId) {
var predicate = function (column) { return column.getColId() === after.colId; };
var movedColumn = _.find(this_1.allDisplayedColumns, predicate);
movedColumns.push(movedColumn);
}
};
var this_1 = this;
for (var i = 0; i < columnStateAfter.length; i++) {
_loop_3(i);
}
if (!movedColumns.length) {
return;
}
var event = {
type: Events.EVENT_COLUMN_MOVED,
columns: movedColumns,
column: null,
toIndex: undefined,
api: this.gridApi,
columnApi: this.columnApi,
source: source
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.sortColumnListUsingIndexes = function (indexes, colA, colB) {
var indexA = indexes[colA.getId()];
var indexB = indexes[colB.getId()];
return indexA - indexB;
};
ColumnController.prototype.syncColumnWithNoState = function (column, source) {
column.setVisible(false, source);
column.setAggFunc(null);
column.setPinned(null);
column.setRowGroupActive(false, source);
column.setPivotActive(false, source);
column.setValueActive(false, source);
};
ColumnController.prototype.syncColumnWithStateItem = function (column, stateItem, rowGroupIndexes, pivotIndexes, source) {
if (!column) {
return;
}
// following ensures we are left with boolean true or false, eg converts (null, undefined, 0) all to true
column.setVisible(!stateItem.hide, source);
// sets pinned to 'left' or 'right'
column.setPinned(stateItem.pinned);
// if width provided and valid, use it, otherwise stick with the old width
var minColWidth = this.gridOptionsWrapper.getMinColWidth();
if (stateItem.width && minColWidth &&
(stateItem.width >= minColWidth)) {
column.setActualWidth(stateItem.width, source);
}
if (typeof stateItem.aggFunc === 'string') {
column.setAggFunc(stateItem.aggFunc);
column.setValueActive(true, source);
this.valueColumns.push(column);
}
else {
if (_.exists(stateItem.aggFunc)) {
console.warn('ag-Grid: stateItem.aggFunc must be a string. if using your own aggregation ' +
'functions, register the functions first before using them in get/set state. This is because it is' +
'intended for the column state to be stored and retrieved as simple JSON.');
}
column.setAggFunc(null);
column.setValueActive(false, source);
}
if (typeof stateItem.rowGroupIndex === 'number') {
this.rowGroupColumns.push(column);
column.setRowGroupActive(true, source);
rowGroupIndexes[column.getId()] = stateItem.rowGroupIndex;
}
else {
column.setRowGroupActive(false, source);
}
if (typeof stateItem.pivotIndex === 'number') {
this.pivotColumns.push(column);
column.setPivotActive(true, source);
pivotIndexes[column.getId()] = stateItem.pivotIndex;
}
else {
column.setPivotActive(false, source);
}
};
ColumnController.prototype.getGridColumns = function (keys) {
return this.getColumns(keys, this.getGridColumn.bind(this));
};
ColumnController.prototype.getColumns = function (keys, columnLookupCallback) {
var foundColumns = [];
if (keys) {
keys.forEach(function (key) {
var column = columnLookupCallback(key);
if (column) {
foundColumns.push(column);
}
});
}
return foundColumns;
};
// used by growGroupPanel
ColumnController.prototype.getColumnWithValidation = function (key) {
if (key == null) {
return null;
}
var column = this.getGridColumn(key);
if (!column) {
console.warn('ag-Grid: could not find column ' + key);
}
return column;
};
ColumnController.prototype.getPrimaryColumn = function (key) {
return this.getColumn(key, this.primaryColumns);
};
ColumnController.prototype.getGridColumn = function (key) {
return this.getColumn(key, this.gridColumns);
};
ColumnController.prototype.getColumn = function (key, columnList) {
if (!key) {
return null;
}
for (var i = 0; i < columnList.length; i++) {
if (this.columnsMatch(columnList[i], key)) {
return columnList[i];
}
}
return this.getAutoColumn(key);
};
ColumnController.prototype.getAutoColumn = function (key) {
var _this = this;
if (!this.groupAutoColumns ||
!_.exists(this.groupAutoColumns) ||
_.missing(this.groupAutoColumns)) {
return null;
}
return _.find(this.groupAutoColumns, function (groupCol) { return _this.columnsMatch(groupCol, key); });
};
ColumnController.prototype.columnsMatch = function (column, key) {
var columnMatches = column === key;
var colDefMatches = column.getColDef() === key;
var idMatches = column.getColId() == key;
return columnMatches || colDefMatches || idMatches;
};
ColumnController.prototype.getDisplayNameForColumn = function (column, location, includeAggFunc) {
if (includeAggFunc === void 0) { includeAggFunc = false; }
if (!column) {
return null;
}
var headerName = this.getHeaderName(column.getColDef(), column, null, null, location);
if (includeAggFunc) {
return this.wrapHeaderNameWithAggFunc(column, headerName);
}
return headerName;
};
ColumnController.prototype.getDisplayNameForOriginalColumnGroup = function (columnGroup, originalColumnGroup, location) {
var colGroupDef = originalColumnGroup ? originalColumnGroup.getColGroupDef() : null;
if (colGroupDef) {
return this.getHeaderName(colGroupDef, null, columnGroup, originalColumnGroup, location);
}
return null;
};
ColumnController.prototype.getDisplayNameForColumnGroup = function (columnGroup, location) {
return this.getDisplayNameForOriginalColumnGroup(columnGroup, columnGroup.getOriginalColumnGroup(), location);
};
// location is where the column is going to appear, ie who is calling us
ColumnController.prototype.getHeaderName = function (colDef, column, columnGroup, originalColumnGroup, location) {
var headerValueGetter = colDef.headerValueGetter;
if (headerValueGetter) {
var params = {
colDef: colDef,
column: column,
columnGroup: columnGroup,
originalColumnGroup: originalColumnGroup,
location: location,
api: this.gridOptionsWrapper.getApi(),
context: this.gridOptionsWrapper.getContext()
};
if (typeof headerValueGetter === 'function') {
// valueGetter is a function, so just call it
return headerValueGetter(params);
}
else if (typeof headerValueGetter === 'string') {
// valueGetter is an expression, so execute the expression
return this.expressionService.evaluate(headerValueGetter, params);
}
console.warn('ag-grid: headerValueGetter must be a function or a string');
return '';
}
else if (colDef.headerName != null) {
return colDef.headerName;
}
else if (colDef.field) {
return _.camelCaseToHumanText(colDef.field);
}
return '';
};
/*
private getHeaderGroupName(columnGroup: ColumnGroup): string {
let colGroupDef = columnGroup.getOriginalColumnGroup().getColGroupDef();
let headerValueGetter = colGroupDef.headerValueGetter;
if (headerValueGetter) {
let params = {
columnGroup: columnGroup,
colDef: colGroupDef,
api: this.gridOptionsWrapper.getApi(),
context: this.gridOptionsWrapper.getContext()
};
if (typeof headerValueGetter === 'function') {
// valueGetter is a function, so just call it
return headerValueGetter(params);
} else if (typeof headerValueGetter === 'string') {
// valueGetter is an expression, so execute the expression
return this.expressionService.evaluate(headerValueGetter, params);
} else {
console.warn('ag-grid: headerValueGetter must be a function or a string');
return '';
}
} else {
return colGroupDef.headerName;
}
}
*/
ColumnController.prototype.wrapHeaderNameWithAggFunc = function (column, headerName) {
if (this.gridOptionsWrapper.isSuppressAggFuncInHeader()) {
return headerName;
}
// only columns with aggregation active can have aggregations
var pivotValueColumn = column.getColDef().pivotValueColumn;
var pivotActiveOnThisColumn = _.exists(pivotValueColumn);
var aggFunc = null;
var aggFuncFound;
// otherwise we have a measure that is active, and we are doing aggregation on it
if (pivotActiveOnThisColumn) {
aggFunc = pivotValueColumn ? pivotValueColumn.getAggFunc() : null;
aggFuncFound = true;
}
else {
var measureActive = column.isValueActive();
var aggregationPresent = this.pivotMode || !this.isRowGroupEmpty();
if (measureActive && aggregationPresent) {
aggFunc = column.getAggFunc();
aggFuncFound = true;
}
else {
aggFuncFound = false;
}
}
if (aggFuncFound) {
var aggFuncString = (typeof aggFunc === 'string') ? aggFunc : 'func';
var localeTextFunc = this.gridOptionsWrapper.getLocaleTextFunc();
var aggFuncStringTranslated = localeTextFunc(aggFuncString, aggFuncString);
return aggFuncStringTranslated + "(" + headerName + ")";
}
return headerName;
};
// returns the group with matching colId and instanceId. If instanceId is missing,
// matches only on the colId.
ColumnController.prototype.getColumnGroup = function (colId, instanceId) {
if (!colId) {
return null;
}
if (colId instanceof ColumnGroup) {
return colId;
}
var allColumnGroups = this.getAllDisplayedColumnGroups();
var checkInstanceId = typeof instanceId === 'number';
var result = null;
this.columnUtils.depthFirstAllColumnTreeSearch(allColumnGroups, function (child) {
if (child instanceof ColumnGroup) {
var columnGroup = child;
var matched = void 0;
if (checkInstanceId) {
matched = colId === columnGroup.getGroupId() && instanceId === columnGroup.getInstanceId();
}
else {
matched = colId === columnGroup.getGroupId();
}
if (matched) {
result = columnGroup;
}
}
});
return result;
};
ColumnController.prototype.isReady = function () {
return this.ready;
};
ColumnController.prototype.createValueColumns = function (source, oldPrimaryColumns) {
this.valueColumns = this.extractColumns(oldPrimaryColumns, this.valueColumns, function (col, flag) { return col.setValueActive(flag, source); },
// aggFunc doesn't have index variant, cos order of value cols doesn't matter, so always return null
function () { return null; },
// aggFunc is a string, so return it's existence
function (colDef) { return !!colDef.aggFunc; });
// all new columns added will have aggFunc missing, so set it to what is in the colDef
this.valueColumns.forEach(function (col) {
if (!col.getAggFunc()) {
col.setAggFunc(col.getColDef().aggFunc);
}
});
};
ColumnController.prototype.extractRowGroupColumns = function (source, oldPrimaryColumns) {
this.rowGroupColumns = this.extractColumns(oldPrimaryColumns, this.rowGroupColumns, function (col, flag) { return col.setRowGroupActive(flag, source); }, function (colDef) { return colDef.rowGroupIndex; }, function (colDef) { return colDef.rowGroup; });
};
ColumnController.prototype.extractColumns = function (oldPrimaryColumns, previousCols, setFlagFunc, getIndexFunc, getValueFunc) {
var _this = this;
if (!previousCols) {
previousCols = [];
}
// remove cols that no longer exist
var colPresentInPrimaryFunc = function (col) { return _this.primaryColumns.indexOf(col) >= 0; };
var colMissingFromPrimaryFunc = function (col) { return _this.primaryColumns.indexOf(col) < 0; };
var colNewFunc = function (col) { return !oldPrimaryColumns || oldPrimaryColumns.indexOf(col) < 0; };
var removedCols = previousCols.filter(colMissingFromPrimaryFunc);
var existingCols = previousCols.filter(colPresentInPrimaryFunc);
var newPrimaryCols = this.primaryColumns.filter(colNewFunc);
removedCols.forEach(function (col) { return setFlagFunc(col, false); });
var newCols = [];
// we only want to work on new columns, as old columns already got processed first time around
// pull out items with xxxIndex
newPrimaryCols.forEach(function (col) {
var index = getIndexFunc(col.getColDef());
if (typeof index === 'number') {
newCols.push(col);
}
});
// then sort them
newCols.sort(function (colA, colB) {
var indexA = getIndexFunc(colA.getColDef());
var indexB = getIndexFunc(colB.getColDef());
if (indexA === indexB) {
return 0;
}
else if (indexA < indexB) {
return -1;
}
return 1;
});
// now just pull out items xxx (boolean value), they will be added at the end
// after the indexed ones, but in the order the columns appear
newPrimaryCols.forEach(function (col) {
var booleanValue = getValueFunc(col.getColDef());
if (booleanValue) {
// if user already specified xxxIndex then we skip it as this col already included
if (newCols.indexOf(col) >= 0) {
return;
}
newCols.push(col);
}
});
newCols.forEach(function (col) { return setFlagFunc(col, true); });
var res = existingCols.concat(newCols);
return res;
};
ColumnController.prototype.extractPivotColumns = function (source, oldPrimaryColumns) {
this.pivotColumns = this.extractColumns(oldPrimaryColumns, this.pivotColumns, function (col, flag) { return col.setPivotActive(flag, source); }, function (colDef) { return colDef.pivotIndex; }, function (colDef) { return colDef.pivot; });
};
ColumnController.prototype.resetColumnGroupState = function (source) {
if (source === void 0) { source = "api"; }
var stateItems = [];
this.columnUtils.depthFirstOriginalTreeSearch(null, this.primaryColumnTree, function (child) {
if (child instanceof OriginalColumnGroup) {
var groupState = {
groupId: child.getGroupId(),
open: child.getColGroupDef().openByDefault
};
stateItems.push(groupState);
}
});
this.setColumnGroupState(stateItems, source);
};
ColumnController.prototype.getColumnGroupState = function () {
var columnGroupState = [];
this.columnUtils.depthFirstOriginalTreeSearch(null, this.gridBalancedTree, function (node) {
if (node instanceof OriginalColumnGroup) {
var originalColumnGroup = node;
columnGroupState.push({
groupId: originalColumnGroup.getGroupId(),
open: originalColumnGroup.isExpanded()
});
}
});
return columnGroupState;
};
ColumnController.prototype.setColumnGroupState = function (stateItems, source) {
var _this = this;
if (source === void 0) { source = "api"; }
this.columnAnimationService.start();
var impactedGroups = [];
stateItems.forEach(function (stateItem) {
var groupKey = stateItem.groupId;
var newValue = stateItem.open;
var originalColumnGroup = _this.getOriginalColumnGroup(groupKey);
if (!originalColumnGroup) {
return;
}
if (originalColumnGroup.isExpanded() === newValue) {
return;
}
_this.logger.log('columnGroupOpened(' + originalColumnGroup.getGroupId() + ',' + newValue + ')');
originalColumnGroup.setExpanded(newValue);
impactedGroups.push(originalColumnGroup);
});
this.updateGroupsAndDisplayedColumns(source);
this.setFirstRightAndLastLeftPinned(source);
impactedGroups.forEach(function (originalColumnGroup) {
var event = {
type: Events.EVENT_COLUMN_GROUP_OPENED,
columnGroup: originalColumnGroup,
api: _this.gridApi,
columnApi: _this.columnApi
};
_this.eventService.dispatchEvent(event);
});
this.columnAnimationService.finish();
};
// called by headerRenderer - when a header is opened or closed
ColumnController.prototype.setColumnGroupOpened = function (key, newValue, source) {
if (source === void 0) { source = "api"; }
var keyAsString;
if (key instanceof OriginalColumnGroup) {
keyAsString = key.getId();
}
else {
keyAsString = key;
}
this.setColumnGroupState([{ groupId: keyAsString, open: newValue }], source);
};
ColumnController.prototype.getOriginalColumnGroup = function (key) {
if (key instanceof OriginalColumnGroup) {
return key;
}
if (typeof key !== 'string') {
console.error('ag-Grid: group key must be a string');
}
// otherwise, search for the column group by id
var res = null;
this.columnUtils.depthFirstOriginalTreeSearch(null, this.gridBalancedTree, function (node) {
if (node instanceof OriginalColumnGroup) {
var originalColumnGroup = node;
if (originalColumnGroup.getId() === key) {
res = originalColumnGroup;
}
}
});
return res;
};
ColumnController.prototype.calculateColumnsForDisplay = function () {
var _this = this;
var columnsForDisplay;
if (this.pivotMode && !this.secondaryColumnsPresent) {
// pivot mode is on, but we are not pivoting, so we only
// show columns we are aggregating on
columnsForDisplay = this.gridColumns.filter(function (column) {
var isAutoGroupCol = _this.groupAutoColumns && _.includes(_this.groupAutoColumns, column);
var isValueCol = _this.valueColumns && _.includes(_this.valueColumns, column);
return isAutoGroupCol || isValueCol;
});
}
else {
// otherwise continue as normal. this can be working on the primary
// or secondary columns, whatever the gridColumns are set to
columnsForDisplay = this.gridColumns.filter(function (column) {
// keep col if a) it's auto-group or b) it's visible
var isAutoGroupCol = _this.groupAutoColumns && _.includes(_this.groupAutoColumns, column);
return isAutoGroupCol || column.isVisible();
});
}
return columnsForDisplay;
};
ColumnController.prototype.checkColSpanActiveInCols = function (columns) {
var result = false;
columns.forEach(function (col) {
if (_.exists(col.getColDef().colSpan)) {
result = true;
}
});
return result;
};
ColumnController.prototype.calculateColumnsForGroupDisplay = function () {
var _this = this;
this.groupDisplayColumns = [];
var checkFunc = function (col) {
var colDef = col.getColDef();
if (colDef && _.exists(colDef.showRowGroup)) {
_this.groupDisplayColumns.push(col);
}
};
this.gridColumns.forEach(checkFunc);
if (this.groupAutoColumns) {
this.groupAutoColumns.forEach(checkFunc);
}
};
ColumnController.prototype.getGroupDisplayColumns = function () {
return this.groupDisplayColumns;
};
ColumnController.prototype.updateDisplayedColumns = function (source) {
var columnsForDisplay = this.calculateColumnsForDisplay();
this.buildDisplayedTrees(columnsForDisplay);
this.calculateColumnsForGroupDisplay();
// also called when group opened/closed
this.updateGroupsAndDisplayedColumns(source);
// also called when group opened/closed
this.setFirstRightAndLastLeftPinned(source);
};
ColumnController.prototype.isSecondaryColumnsPresent = function () {
return this.secondaryColumnsPresent;
};
ColumnController.prototype.setSecondaryColumns = function (colDefs, source) {
if (source === void 0) { source = "api"; }
var newColsPresent = colDefs && colDefs.length > 0;
// if not cols passed, and we had to cols anyway, then do nothing
if (!newColsPresent && !this.secondaryColumnsPresent) {
return;
}
if (newColsPresent) {
this.processSecondaryColumnDefinitions(colDefs);
var balancedTreeResult = this.columnFactory.createColumnTree(colDefs, false);
this.secondaryBalancedTree = balancedTreeResult.columnTree;
this.secondaryHeaderRowCount = balancedTreeResult.treeDept + 1;
this.secondaryColumns = this.getColumnsFromTree(this.secondaryBalancedTree);
this.secondaryColumnsPresent = true;
}
else {
this.secondaryBalancedTree = null;
this.secondaryHeaderRowCount = -1;
this.secondaryColumns = null;
this.secondaryColumnsPresent = false;
}
this.updateGridColumns();
this.updateDisplayedColumns(source);
};
ColumnController.prototype.processSecondaryColumnDefinitions = function (colDefs) {
var columnCallback = this.gridOptionsWrapper.getProcessSecondaryColDefFunc();
var groupCallback = this.gridOptionsWrapper.getProcessSecondaryColGroupDefFunc();
if (!columnCallback && !groupCallback) {
return undefined;
}
var searchForColDefs = function (colDefs2) {
colDefs2.forEach(function (abstractColDef) {
var isGroup = _.exists(abstractColDef.children);
if (isGroup) {
var colGroupDef = abstractColDef;
if (groupCallback) {
groupCallback(colGroupDef);
}
searchForColDefs(colGroupDef.children);
}
else {
var colDef = abstractColDef;
if (columnCallback) {
columnCallback(colDef);
}
}
});
};
if (colDefs) {
searchForColDefs(colDefs);
}
};
// called from: setColumnState, setColumnDefs, setSecondaryColumns
ColumnController.prototype.updateGridColumns = function () {
if (this.gridColsArePrimary) {
this.lastPrimaryOrder = this.gridColumns;
}
if (this.secondaryColumns && this.secondaryBalancedTree) {
this.gridBalancedTree = this.secondaryBalancedTree.slice();
this.gridHeaderRowCount = this.secondaryHeaderRowCount;
this.gridColumns = this.secondaryColumns.slice();
this.gridColsArePrimary = false;
}
else {
this.gridBalancedTree = this.primaryColumnTree.slice();
this.gridHeaderRowCount = this.primaryHeaderRowCount;
this.gridColumns = this.primaryColumns.slice();
this.gridColsArePrimary = true;
// updateGridColumns gets called after user adds a row group. we want to maintain the order of the columns
// when this happens (eg if user moved a column) rather than revert back to the original column order.
// likewise if changing in/out of pivot mode, we want to maintain the order of the primary cols
this.orderGridColsLikeLastPrimary();
}
this.addAutoGroupToGridColumns();
this.autoRowHeightColumns = this.gridColumns.filter(function (col) { return col.getColDef().autoHeight; });
this.putFixedColumnsFirst();
this.setupQuickFilterColumns();
this.clearDisplayedColumns();
this.colSpanActive = this.checkColSpanActiveInCols(this.gridColumns);
var event = {
type: Events.EVENT_GRID_COLUMNS_CHANGED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.orderGridColsLikeLastPrimary = function () {
var _this = this;
if (_.missing(this.lastPrimaryOrder)) {
return;
}
// only do the sort if at least one column is accounted for. columns will be not accounted for
// if changing from secondary to primary columns
var noColsFound = true;
this.gridColumns.forEach(function (col) {
if (_this.lastPrimaryOrder.indexOf(col) >= 0) {
noColsFound = false;
}
});
if (noColsFound) {
return;
}
// order cols in the same order as before. we need to make sure that all
// cols still exists, so filter out any that no longer exist.
var oldColsOrdered = this.lastPrimaryOrder.filter(function (col) { return _this.gridColumns.indexOf(col) >= 0; });
var newColsOrdered = this.gridColumns.filter(function (col) { return oldColsOrdered.indexOf(col) < 0; });
// add in the new columns, at the end (if no group), or at the end of the group (if a group)
var newGridColumns = oldColsOrdered.slice();
newColsOrdered.forEach(function (newCol) {
var parent = newCol.getOriginalParent();
// if no parent, means we are not grouping, so just add the column to the end
if (!parent) {
newGridColumns.push(newCol);
return;
}
// find the group the column belongs to. if no siblings at the current level (eg col in group on it's
// own) then go up one level and look for siblings there.
var siblings = [];
while (!siblings.length && parent) {
var leafCols = parent.getLeafColumns();
leafCols.forEach(function (leafCol) {
var presentInNewGriColumns = newGridColumns.indexOf(leafCol) >= 0;
var noYetInSiblings = siblings.indexOf(leafCol) < 0;
if (presentInNewGriColumns && noYetInSiblings) {
siblings.push(leafCol);
}
});
parent = parent.getOriginalParent();
}
// if no siblings exist at any level, this means the col is in a group (or parent groups) on it's own
if (!siblings.length) {
newGridColumns.push(newCol);
return;
}
// find index of last column in the group
var indexes = siblings.map(function (col) { return newGridColumns.indexOf(col); });
var lastIndex = Math.max.apply(Math, indexes);
_.insertIntoArray(newGridColumns, newCol, lastIndex + 1);
});
this.gridColumns = newGridColumns;
};
ColumnController.prototype.isPrimaryColumnGroupsPresent = function () {
return this.primaryHeaderRowCount > 1;
};
// if we are using autoGroupCols, then they should be included for quick filter. this covers the
// following scenarios:
// a) user provides 'field' into autoGroupCol of normal grid, so now because a valid col to filter leafs on
// b) using tree data and user depends on autoGroupCol for first col, and we also want to filter on this
// (tree data is a bit different, as parent rows can be filtered on, unlike row grouping)
ColumnController.prototype.setupQuickFilterColumns = function () {
if (this.groupAutoColumns) {
this.columnsForQuickFilter = this.primaryColumns.concat(this.groupAutoColumns);
}
else {
this.columnsForQuickFilter = this.primaryColumns;
}
};
ColumnController.prototype.putFixedColumnsFirst = function () {
var locked = this.gridColumns.filter(function (c) { return c.getColDef().lockPosition; });
var unlocked = this.gridColumns.filter(function (c) { return !c.getColDef().lockPosition; });
this.gridColumns = locked.concat(unlocked);
};
ColumnController.prototype.addAutoGroupToGridColumns = function () {
// add in auto-group here
this.createGroupAutoColumnsIfNeeded();
if (_.missing(this.groupAutoColumns)) {
return;
}
this.gridColumns = this.groupAutoColumns ? this.groupAutoColumns.concat(this.gridColumns) : this.gridColumns;
var autoColBalancedTree = this.columnFactory.createForAutoGroups(this.groupAutoColumns, this.gridBalancedTree);
this.gridBalancedTree = autoColBalancedTree.concat(this.gridBalancedTree);
};
// gets called after we copy down grid columns, to make sure any part of the gui
// that tries to draw, eg the header, it will get empty lists of columns rather
// than stale columns. for example, the header will received gridColumnsChanged
// event, so will try and draw, but it will draw successfully when it acts on the
// virtualColumnsChanged event
ColumnController.prototype.clearDisplayedColumns = function () {
this.displayedLeftColumnTree = [];
this.displayedRightColumnTree = [];
this.displayedCentreColumnTree = [];
this.displayedLeftHeaderRows = {};
this.displayedRightHeaderRows = {};
this.displayedCentreHeaderRows = {};
this.displayedLeftColumns = [];
this.displayedRightColumns = [];
this.displayedCenterColumns = [];
this.allDisplayedColumns = [];
this.allDisplayedVirtualColumns = [];
};
ColumnController.prototype.updateGroupsAndDisplayedColumns = function (source) {
this.updateOpenClosedVisibilityInColumnGroups();
this.updateDisplayedColumnsFromTrees(source);
this.updateVirtualSets();
this.updateBodyWidths();
// this event is picked up by the gui, headerRenderer and rowRenderer, to recalculate what columns to display
var event = {
type: Events.EVENT_DISPLAYED_COLUMNS_CHANGED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(event);
};
ColumnController.prototype.updateDisplayedColumnsFromTrees = function (source) {
this.addToDisplayedColumns(this.displayedLeftColumnTree, this.displayedLeftColumns);
this.addToDisplayedColumns(this.displayedCentreColumnTree, this.displayedCenterColumns);
this.addToDisplayedColumns(this.displayedRightColumnTree, this.displayedRightColumns);
this.setupAllDisplayedColumns();
this.setLeftValues(source);
};
ColumnController.prototype.setupAllDisplayedColumns = function () {
if (this.gridOptionsWrapper.isEnableRtl()) {
this.allDisplayedColumns = this.displayedRightColumns
.concat(this.displayedCenterColumns)
.concat(this.displayedLeftColumns);
}
else {
this.allDisplayedColumns = this.displayedLeftColumns
.concat(this.displayedCenterColumns)
.concat(this.displayedRightColumns);
}
};
// sets the left pixel position of each column
ColumnController.prototype.setLeftValues = function (source) {
this.setLeftValuesOfColumns(source);
this.setLeftValuesOfGroups();
};
ColumnController.prototype.setLeftValuesOfColumns = function (source) {
var _this = this;
// go through each list of displayed columns
var allColumns = this.primaryColumns.slice(0);
// let totalColumnWidth = this.getWidthOfColsInList()
var doingRtl = this.gridOptionsWrapper.isEnableRtl();
[
this.displayedLeftColumns,
this.displayedRightColumns,
this.displayedCenterColumns
].forEach(function (columns) {
if (doingRtl) {
// when doing RTL, we start at the top most pixel (ie RHS) and work backwards
var left_1 = _this.getWidthOfColsInList(columns);
columns.forEach(function (column) {
left_1 -= column.getActualWidth();
column.setLeft(left_1, source);
});
}
else {
// otherwise normal LTR, we start at zero
var left_2 = 0;
columns.forEach(function (column) {
column.setLeft(left_2, source);
left_2 += column.getActualWidth();
});
}
_.removeAllFromArray(allColumns, columns);
});
// items left in allColumns are columns not displayed, so remove the left position. this is
// important for the rows, as if a col is made visible, then taken out, then made visible again,
// we don't want the animation of the cell floating in from the old position, whatever that was.
allColumns.forEach(function (column) {
column.setLeft(null, source);
});
};
ColumnController.prototype.setLeftValuesOfGroups = function () {
// a groups left value is the lest left value of it's children
[
this.displayedLeftColumnTree,
this.displayedRightColumnTree,
this.displayedCentreColumnTree
].forEach(function (columns) {
columns.forEach(function (column) {
if (column instanceof ColumnGroup) {
var columnGroup = column;
columnGroup.checkLeft();
}
});
});
};
ColumnController.prototype.addToDisplayedColumns = function (displayedColumnTree, displayedColumns) {
displayedColumns.length = 0;
this.columnUtils.depthFirstDisplayedColumnTreeSearch(displayedColumnTree, function (child) {
if (child instanceof Column) {
displayedColumns.push(child);
}
});
};
ColumnController.prototype.updateDisplayedCenterVirtualColumns = function () {
if (this.suppressColumnVirtualisation) {
// no virtualisation, so don't filter
this.allDisplayedCenterVirtualColumns = this.displayedCenterColumns;
}
else {
// filter out what should be visible
this.allDisplayedCenterVirtualColumns = this.filterOutColumnsWithinViewport();
}
this.allDisplayedVirtualColumns = this.allDisplayedCenterVirtualColumns
.concat(this.displayedLeftColumns)
.concat(this.displayedRightColumns);
// return map of virtual col id's, for easy lookup when building the groups.
// the map will be colId=>true, ie col id's mapping to 'true'.
var result = {};
this.allDisplayedVirtualColumns.forEach(function (col) {
result[col.getId()] = true;
});
return result;
};
ColumnController.prototype.getVirtualHeaderGroupRow = function (type, dept) {
var result;
switch (type) {
case Constants.PINNED_LEFT:
result = this.displayedLeftHeaderRows[dept];
break;
case Constants.PINNED_RIGHT:
result = this.displayedRightHeaderRows[dept];
break;
default:
result = this.displayedCentreHeaderRows[dept];
break;
}
if (_.missing(result)) {
result = [];
}
return result;
};
ColumnController.prototype.updateDisplayedVirtualGroups = function (virtualColIds) {
// go through each group, see if any of it's cols are displayed, and if yes,
// then this group is included
this.displayedLeftHeaderRows = {};
this.displayedRightHeaderRows = {};
this.displayedCentreHeaderRows = {};
var testGroup = function (children, result, dept) {
var returnValue = false;
for (var i = 0; i < children.length; i++) {
// see if this item is within viewport
var child = children[i];
var addThisItem = void 0;
if (child instanceof Column) {
// for column, test if column is included
addThisItem = virtualColIds[child.getId()] === true;
}
else {
// if group, base decision on children
var columnGroup = child;
addThisItem = testGroup(columnGroup.getDisplayedChildren(), result, dept + 1);
}
if (addThisItem) {
returnValue = true;
if (!result[dept]) {
result[dept] = [];
}
result[dept].push(child);
}
}
return returnValue;
};
testGroup(this.displayedLeftColumnTree, this.displayedLeftHeaderRows, 0);
testGroup(this.displayedRightColumnTree, this.displayedRightHeaderRows, 0);
testGroup(this.displayedCentreColumnTree, this.displayedCentreHeaderRows, 0);
};
ColumnController.prototype.updateVirtualSets = function () {
var virtualColIds = this.updateDisplayedCenterVirtualColumns();
this.updateDisplayedVirtualGroups(virtualColIds);
};
ColumnController.prototype.filterOutColumnsWithinViewport = function () {
return this.displayedCenterColumns.filter(this.isColumnInViewport.bind(this));
};
ColumnController.prototype.refreshFlexedColumns = function (updatedFlexViewportWidth, source) {
if (source === void 0) { source = 'flex'; }
if (!this.flexActive) {
return;
}
this.flexViewportWidth = updatedFlexViewportWidth || this.flexViewportWidth;
if (!this.flexViewportWidth) {
return;
}
// If the grid has left-over space, divide it between flexing columns in proportion to their flex value.
// A "flexing column" is one that has a 'flex' value set and is not currently being constrained by its
// minWidth or maxWidth rules.
var knownWidthColumns = this.displayedCenterColumns.filter(function (col) { return !col.getFlex(); });
var flexingColumns = this.displayedCenterColumns.filter(function (col) { return col.getFlex(); });
var flexingColumnSizes = [];
var spaceForFlexingColumns;
outer: while (true) {
var totalFlex = flexingColumns.reduce(function (count, col) { return count + col.getFlex(); }, 0);
spaceForFlexingColumns = this.flexViewportWidth - this.getWidthOfColsInList(knownWidthColumns);
for (var i = 0; i < flexingColumns.length; i++) {
var col = flexingColumns[i];
var widthByFlexRule = spaceForFlexingColumns * col.getFlex() / totalFlex;
var constrainedWidth = void 0;
if (widthByFlexRule < col.getMinWidth()) {
constrainedWidth = col.getMinWidth();
}
else if (col.getMaxWidth() != null && widthByFlexRule > col.getMaxWidth()) {
constrainedWidth = col.getMaxWidth();
}
if (constrainedWidth) {
// This column is not in fact flexing as it is being constrained to a specific size
// so remove it from the list of flexing columns and start again
col.setActualWidth(constrainedWidth, source);
_.removeFromArray(flexingColumns, col);
knownWidthColumns.push(col);
continue outer;
}
flexingColumnSizes[i] = Math.round(widthByFlexRule);
}
break;
}
var remainingSpace = spaceForFlexingColumns;
flexingColumns.forEach(function (col, i) {
col.setActualWidth(Math.min(flexingColumnSizes[i], remainingSpace), source);
remainingSpace -= flexingColumnSizes[i];
});
this.setLeftValues(source);
this.updateBodyWidths();
this.fireResizedEventForColumns(flexingColumns, source);
};
// called from api
ColumnController.prototype.sizeColumnsToFit = function (gridWidth, source, silent) {
if (source === void 0) { source = "sizeColumnsToFit"; }
// avoid divide by zero
var allDisplayedColumns = this.getAllDisplayedColumns();
if (gridWidth <= 0 || !allDisplayedColumns.length) {
return;
}
var colsToSpread = [];
var colsToNotSpread = [];
allDisplayedColumns.forEach(function (column) {
if (column.getColDef().suppressSizeToFit === true) {
colsToNotSpread.push(column);
}
else {
colsToSpread.push(column);
}
});
// make a copy of the cols that are going to be resized
var colsToFireEventFor = colsToSpread.slice(0);
var finishedResizing = false;
var moveToNotSpread = function (column) {
_.removeFromArray(colsToSpread, column);
colsToNotSpread.push(column);
};
while (!finishedResizing) {
finishedResizing = true;
var availablePixels = gridWidth - this.getWidthOfColsInList(colsToNotSpread);
if (availablePixels <= 0) {
// no width, set everything to minimum
colsToSpread.forEach(function (column) {
column.setMinimum(source);
});
}
else {
var scale = availablePixels / this.getWidthOfColsInList(colsToSpread);
// we set the pixels for the last col based on what's left, as otherwise
// we could be a pixel or two short or extra because of rounding errors.
var pixelsForLastCol = availablePixels;
// backwards through loop, as we are removing items as we go
for (var i = colsToSpread.length - 1; i >= 0; i--) {
var column = colsToSpread[i];
var newWidth = Math.round(column.getActualWidth() * scale);
if (newWidth < column.getMinWidth()) {
column.setMinimum(source);
moveToNotSpread(column);
finishedResizing = false;
}
else if (column.isGreaterThanMax(newWidth)) {
column.setActualWidth(column.getMaxWidth(), source);
moveToNotSpread(column);
finishedResizing = false;
}
else {
var onLastCol = i === 0;
if (onLastCol) {
column.setActualWidth(pixelsForLastCol, source);
}
else {
column.setActualWidth(newWidth, source);
}
}
pixelsForLastCol -= newWidth;
}
}
}
this.setLeftValues(source);
this.updateBodyWidths();
if (silent) {
return;
}
this.fireResizedEventForColumns(colsToFireEventFor, source);
};
ColumnController.prototype.fireResizedEventForColumns = function (columns, source) {
var _this = this;
columns.forEach(function (column) {
var event = {
type: Events.EVENT_COLUMN_RESIZED,
column: column,
columns: [column],
finished: true,
api: _this.gridApi,
columnApi: _this.columnApi,
source: source
};
_this.eventService.dispatchEvent(event);
});
};
ColumnController.prototype.buildDisplayedTrees = function (visibleColumns) {
var leftVisibleColumns = [];
var rightVisibleColumns = [];
var centerVisibleColumns = [];
visibleColumns.forEach(function (column) {
switch (column.getPinned()) {
case "left":
leftVisibleColumns.push(column);
break;
case "right":
rightVisibleColumns.push(column);
break;
default:
centerVisibleColumns.push(column);
break;
}
});
var groupInstanceIdCreator = new GroupInstanceIdCreator();
this.displayedLeftColumnTree = this.displayedGroupCreator.createDisplayedGroups(leftVisibleColumns, this.gridBalancedTree, groupInstanceIdCreator, Constants.PINNED_LEFT, this.displayedLeftColumnTree);
this.displayedRightColumnTree = this.displayedGroupCreator.createDisplayedGroups(rightVisibleColumns, this.gridBalancedTree, groupInstanceIdCreator, Constants.PINNED_RIGHT, this.displayedRightColumnTree);
this.displayedCentreColumnTree = this.displayedGroupCreator.createDisplayedGroups(centerVisibleColumns, this.gridBalancedTree, groupInstanceIdCreator, null, this.displayedCentreColumnTree);
};
ColumnController.prototype.updateOpenClosedVisibilityInColumnGroups = function () {
var allColumnGroups = this.getAllDisplayedColumnGroups();
this.columnUtils.depthFirstAllColumnTreeSearch(allColumnGroups, function (child) {
if (child instanceof ColumnGroup) {
var columnGroup = child;
columnGroup.calculateDisplayedColumns();
}
});
};
ColumnController.prototype.getGroupAutoColumns = function () {
return this.groupAutoColumns;
};
ColumnController.prototype.createGroupAutoColumnsIfNeeded = function () {
if (!this.autoGroupsNeedBuilding) {
return;
}
this.autoGroupsNeedBuilding = false;
var groupFullWidthRow = this.gridOptionsWrapper.isGroupUseEntireRow(this.pivotMode);
// we never suppress auto col for pivot mode, as there is no way for user to provide group columns
// in pivot mode. pivot mode has auto group column (provide by grid) and value columns (provided by
// pivot feature in the grid).
var groupSuppressAutoColumn = this.gridOptionsWrapper.isGroupSuppressAutoColumn() && !this.pivotMode;
var groupSuppressRow = this.gridOptionsWrapper.isGroupSuppressRow();
var groupingActive = this.rowGroupColumns.length > 0 || this.usingTreeData;
var needAutoColumns = groupingActive && !groupSuppressAutoColumn && !groupFullWidthRow && !groupSuppressRow;
if (needAutoColumns) {
var newAutoGroupCols = this.autoGroupColService.createAutoGroupColumns(this.rowGroupColumns);
var autoColsDifferent = !this.autoColsEqual(newAutoGroupCols, this.groupAutoColumns);
if (autoColsDifferent) {
this.groupAutoColumns = newAutoGroupCols;
}
}
else {
this.groupAutoColumns = null;
}
};
ColumnController.prototype.autoColsEqual = function (colsA, colsB) {
var bothMissing = !colsA && !colsB;
if (bothMissing) {
return true;
}
var atLeastOneListMissing = !colsA || !colsB;
if (atLeastOneListMissing || colsA.length !== colsB.length) {
return false;
}
for (var i = 0; i < colsA.length; i++) {
var colA = colsA[i];
var colB = colsB[i];
if (colA.getColId() !== colB.getColId()) {
return false;
}
}
return true;
};
ColumnController.prototype.getWidthOfColsInList = function (columnList) {
return columnList.reduce(function (width, col) { return width + col.getActualWidth(); }, 0);
};
ColumnController.prototype.getGridBalancedTree = function () {
return this.gridBalancedTree;
};
__decorate$4([
Autowired('gridOptionsWrapper')
], ColumnController.prototype, "gridOptionsWrapper", void 0);
__decorate$4([
Autowired('expressionService')
], ColumnController.prototype, "expressionService", void 0);
__decorate$4([
Autowired('columnFactory')
], ColumnController.prototype, "columnFactory", void 0);
__decorate$4([
Autowired('displayedGroupCreator')
], ColumnController.prototype, "displayedGroupCreator", void 0);
__decorate$4([
Autowired('autoWidthCalculator')
], ColumnController.prototype, "autoWidthCalculator", void 0);
__decorate$4([
Autowired('eventService')
], ColumnController.prototype, "eventService", void 0);
__decorate$4([
Autowired('columnUtils')
], ColumnController.prototype, "columnUtils", void 0);
__decorate$4([
Autowired('context')
], ColumnController.prototype, "context", void 0);
__decorate$4([
Autowired('columnAnimationService')
], ColumnController.prototype, "columnAnimationService", void 0);
__decorate$4([
Autowired('autoGroupColService')
], ColumnController.prototype, "autoGroupColService", void 0);
__decorate$4([
Optional('aggFuncService')
], ColumnController.prototype, "aggFuncService", void 0);
__decorate$4([
Optional('valueCache')
], ColumnController.prototype, "valueCache", void 0);
__decorate$4([
Autowired('columnApi')
], ColumnController.prototype, "columnApi", void 0);
__decorate$4([
Autowired('gridApi')
], ColumnController.prototype, "gridApi", void 0);
__decorate$4([
PostConstruct
], ColumnController.prototype, "init", null);
__decorate$4([
__param$2(0, Qualifier('loggerFactory'))
], ColumnController.prototype, "setBeans", null);
ColumnController = __decorate$4([
Bean('columnController')
], ColumnController);
return ColumnController;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate$5 = (undefined && undefined.__decorate) || function (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;
};
// takes in a list of columns, as specified by the column definitions, and returns column groups
var ColumnUtils = /** @class */ (function () {
function ColumnUtils() {
}
ColumnUtils.prototype.calculateColInitialWidth = function (colDef) {
var optionsWrapper = this.gridOptionsWrapper;
var minColWidth = colDef.minWidth != null ? colDef.minWidth : optionsWrapper.getMinColWidth();
var maxColWidth = colDef.maxWidth != null ? colDef.maxWidth : (optionsWrapper.getMaxColWidth() || _.getMaxSafeInteger());
var width = colDef.width != null ? colDef.width : optionsWrapper.getColWidth();
return Math.max(Math.min(width, maxColWidth), minColWidth);
};
ColumnUtils.prototype.getOriginalPathForColumn = function (column, originalBalancedTree) {
var result = [];
var found = false;
var recursePath = function (balancedColumnTree, dept) {
for (var i = 0; i < balancedColumnTree.length; i++) {
if (found) {
return;
}
// quit the search, so 'result' is kept with the found result
var node = balancedColumnTree[i];
if (node instanceof OriginalColumnGroup) {
var nextNode = node;
recursePath(nextNode.getChildren(), dept + 1);
result[dept] = node;
}
else if (node === column) {
found = true;
}
}
};
recursePath(originalBalancedTree, 0);
// we should always find the path, but in case there is a bug somewhere, returning null
// will make it fail rather than provide a 'hard to track down' bug
return found ? result : null;
};
/* public getPathForColumn(column: Column, allDisplayedColumnGroups: ColumnGroupChild[]): ColumnGroup[] {
let result: ColumnGroup[] = [];
let found = false;
recursePath(allDisplayedColumnGroups, 0);
// we should always find the path, but in case there is a bug somewhere, returning null
// will make it fail rather than provide a 'hard to track down' bug
if (found) {
return result;
} else {
return null;
}
function recursePath(balancedColumnTree: ColumnGroupChild[], dept: number): void {
for (let i = 0; i node;
recursePath(nextNode.getChildren(), dept+1);
result[dept] = node;
} else {
if (node === column) {
found = true;
}
}
}
}
}*/
ColumnUtils.prototype.depthFirstOriginalTreeSearch = function (parent, tree, callback) {
var _this = this;
if (!tree) {
return;
}
tree.forEach(function (child) {
if (child instanceof OriginalColumnGroup) {
_this.depthFirstOriginalTreeSearch(child, child.getChildren(), callback);
}
callback(child, parent);
});
};
ColumnUtils.prototype.depthFirstAllColumnTreeSearch = function (tree, callback) {
var _this = this;
if (!tree) {
return;
}
tree.forEach(function (child) {
if (child instanceof ColumnGroup) {
_this.depthFirstAllColumnTreeSearch(child.getChildren(), callback);
}
callback(child);
});
};
ColumnUtils.prototype.depthFirstDisplayedColumnTreeSearch = function (tree, callback) {
var _this = this;
if (!tree) {
return;
}
tree.forEach(function (child) {
if (child instanceof ColumnGroup) {
_this.depthFirstDisplayedColumnTreeSearch(child.getDisplayedChildren(), callback);
}
callback(child);
});
};
__decorate$5([
Autowired('gridOptionsWrapper')
], ColumnUtils.prototype, "gridOptionsWrapper", void 0);
ColumnUtils = __decorate$5([
Bean('columnUtils')
], ColumnUtils);
return ColumnUtils;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate$6 = (undefined && undefined.__decorate) || function (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;
};
// takes in a list of columns, as specified by the column definitions, and returns column groups
var DisplayedGroupCreator = /** @class */ (function () {
function DisplayedGroupCreator() {
}
DisplayedGroupCreator.prototype.createDisplayedGroups = function (
// all displayed columns sorted - this is the columns the grid should show
sortedVisibleColumns,
// the tree of columns, as provided by the users, used to know what groups columns roll up into
balancedColumnTree,
// creates unique id's for the group
groupInstanceIdCreator,
// whether it's left, right or center col
pinned,
// we try to reuse old groups if we can, to allow gui to do animation
oldDisplayedGroups) {
var _this = this;
var result = [];
var previousRealPath;
var previousOriginalPath;
var oldColumnsMapped = this.mapOldGroupsById(oldDisplayedGroups);
// go through each column, then do a bottom up comparison to the previous column, and start
// to share groups if they converge at any point.
sortedVisibleColumns.forEach(function (currentColumn) {
var currentOriginalPath = _this.getOriginalPathForColumn(balancedColumnTree, currentColumn);
var currentRealPath = [];
var firstColumn = !previousOriginalPath;
for (var i = 0; i < currentOriginalPath.length; i++) {
if (firstColumn || currentOriginalPath[i] !== previousOriginalPath[i]) {
// new group needed
var newGroup = _this.createColumnGroup(currentOriginalPath[i], groupInstanceIdCreator, oldColumnsMapped, pinned);
currentRealPath[i] = newGroup;
// if top level, add to result, otherwise add to parent
if (i == 0) {
result.push(newGroup);
}
else {
currentRealPath[i - 1].addChild(newGroup);
}
}
else {
// reuse old group
currentRealPath[i] = previousRealPath[i];
}
}
var noColumnGroups = currentRealPath.length === 0;
if (noColumnGroups) {
// if we are not grouping, then the result of the above is an empty
// path (no groups), and we just add the column to the root list.
result.push(currentColumn);
}
else {
var leafGroup = _.last(currentRealPath);
leafGroup.addChild(currentColumn);
}
previousRealPath = currentRealPath;
previousOriginalPath = currentOriginalPath;
});
this.setupParentsIntoColumns(result, null);
return result;
};
DisplayedGroupCreator.prototype.createColumnGroup = function (originalGroup, groupInstanceIdCreator, oldColumnsMapped, pinned) {
var groupId = originalGroup.getGroupId();
var instanceId = groupInstanceIdCreator.getInstanceIdForKey(groupId);
var uniqueId = ColumnGroup.createUniqueId(groupId, instanceId);
var columnGroup = oldColumnsMapped[uniqueId];
// if the user is setting new colDefs, it is possible that the id's overlap, and we
// would have a false match from above. so we double check we are talking about the
// same original column group.
if (columnGroup && columnGroup.getOriginalColumnGroup() !== originalGroup) {
columnGroup = null;
}
if (_.exists(columnGroup)) {
// clean out the old column group here, as we will be adding children into it again
columnGroup.reset();
}
else {
columnGroup = new ColumnGroup(originalGroup, groupId, instanceId, pinned);
this.context.wireBean(columnGroup);
}
return columnGroup;
};
// returns back a 2d map of ColumnGroup as follows: groupId -> instanceId -> ColumnGroup
DisplayedGroupCreator.prototype.mapOldGroupsById = function (displayedGroups) {
var result = {};
var recursive = function (columnsOrGroups) {
columnsOrGroups.forEach(function (columnOrGroup) {
if (columnOrGroup instanceof ColumnGroup) {
var columnGroup = columnOrGroup;
result[columnOrGroup.getUniqueId()] = columnGroup;
recursive(columnGroup.getChildren());
}
});
};
if (displayedGroups) {
recursive(displayedGroups);
}
return result;
};
DisplayedGroupCreator.prototype.setupParentsIntoColumns = function (columnsOrGroups, parent) {
var _this = this;
columnsOrGroups.forEach(function (columnsOrGroup) {
columnsOrGroup.setParent(parent);
if (columnsOrGroup instanceof ColumnGroup) {
var columnGroup = columnsOrGroup;
_this.setupParentsIntoColumns(columnGroup.getChildren(), columnGroup);
}
});
};
DisplayedGroupCreator.prototype.getOriginalPathForColumn = function (balancedColumnTree, column) {
var result = [];
var found = false;
var recursePath = function (balancedColumnTree, dept) {
for (var i = 0; i < balancedColumnTree.length; i++) {
// quit the search, so 'result' is kept with the found result
if (found) {
return;
}
var node = balancedColumnTree[i];
if (node instanceof OriginalColumnGroup) {
var nextNode = node;
recursePath(nextNode.getChildren(), dept + 1);
result[dept] = node;
}
else if (node === column) {
found = true;
}
}
};
recursePath(balancedColumnTree, 0);
// it's possible we didn't find a path. this happens if the column is generated
// by the grid (auto-group), in that the definition didn't come from the client. in this case,
// we create a fake original path.
if (found) {
return result;
}
console.warn('could not get path');
return null;
};
__decorate$6([
Autowired('columnUtils')
], DisplayedGroupCreator.prototype, "columnUtils", void 0);
__decorate$6([
Autowired('context')
], DisplayedGroupCreator.prototype, "context", void 0);
DisplayedGroupCreator = __decorate$6([
Bean('displayedGroupCreator')
], DisplayedGroupCreator);
return DisplayedGroupCreator;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __spreadArrays = (undefined && undefined.__spreadArrays) || function () {
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;
};
/**
* These keys are used for validating properties supplied on a gridOptions object, and for code generation.
* If you change the properties on the gridOptions interface, you *must* update this file as well to be consistent.
*/
var PropertyKeys = /** @class */ (function () {
function PropertyKeys() {
}
PropertyKeys.STRING_PROPERTIES = [
'sortingOrder', 'rowClass', 'rowSelection', 'overlayLoadingTemplate',
'overlayNoRowsTemplate', 'quickFilterText', 'rowModelType',
'editType', 'domLayout', 'clipboardDeliminator', 'rowGroupPanelShow',
'multiSortKey', 'pivotColumnGroupTotals', 'pivotRowTotals', 'pivotPanelShow'
];
PropertyKeys.OBJECT_PROPERTIES = [
'components', 'frameworkComponents', 'rowStyle', 'context', 'autoGroupColumnDef', 'groupColumnDef', 'localeText',
'icons', 'datasource', 'serverSideDatasource', 'viewportDatasource', 'groupRowRendererParams', 'aggFuncs',
'fullWidthCellRendererParams', 'defaultColGroupDef', 'defaultColDef', 'defaultExportParams', 'columnTypes',
'rowClassRules', 'detailGridOptions', 'detailCellRendererParams', 'loadingCellRendererParams', 'loadingOverlayComponentParams',
'noRowsOverlayComponentParams', 'popupParent', 'colResizeDefault', 'reduxStore', 'statusBar', 'sideBar'
];
PropertyKeys.ARRAY_PROPERTIES = [
'slaveGrids', 'alignedGrids', 'rowData', 'columnDefs', 'excelStyles', 'pinnedTopRowData', 'pinnedBottomRowData'
];
PropertyKeys.NUMBER_PROPERTIES = [
'rowHeight', 'detailRowHeight', 'rowBuffer', 'colWidth', 'headerHeight', 'groupHeaderHeight',
'floatingFiltersHeight', 'pivotHeaderHeight', 'pivotGroupHeaderHeight', 'groupDefaultExpanded',
'minColWidth', 'maxColWidth', 'viewportRowModelPageSize', 'viewportRowModelBufferSize',
'autoSizePadding', 'maxBlocksInCache', 'maxConcurrentDatasourceRequests',
'cacheOverflowSize', 'paginationPageSize', 'cacheBlockSize', 'infiniteInitialRowCount',
'scrollbarWidth', 'paginationStartPage', 'infiniteBlockSize', 'batchUpdateWaitMillis',
'blockLoadDebounceMillis', 'keepDetailRowsCount', 'undoRedoCellEditingLimit'
];
PropertyKeys.BOOLEAN_PROPERTIES = [
'toolPanelSuppressRowGroups', 'toolPanelSuppressValues', 'toolPanelSuppressPivots', 'toolPanelSuppressPivotMode',
'toolPanelSuppressSideButtons', 'toolPanelSuppressColumnFilter', 'toolPanelSuppressColumnSelectAll',
'toolPanelSuppressColumnExpandAll', 'suppressMakeColumnVisibleAfterUnGroup', 'suppressRowClickSelection',
'suppressCellSelection', 'suppressHorizontalScroll', 'alwaysShowVerticalScroll', 'debug', 'enableBrowserTooltips', 'enableColResize',
'enableCellExpressions', 'enableSorting', 'enableServerSideSorting', 'enableFilter', 'enableServerSideFilter',
'angularCompileRows', 'angularCompileFilters', 'angularCompileHeaders', 'groupSuppressAutoColumn', 'groupSelectsChildren',
'groupIncludeFooter', 'groupIncludeTotalFooter', 'groupUseEntireRow', 'groupSuppressRow', 'groupSuppressBlankHeader',
'forPrint', 'suppressMenuHide', 'rowDeselection', 'unSortIcon', 'suppressMultiSort', 'singleClickEdit',
'suppressLoadingOverlay', 'suppressNoRowsOverlay', 'suppressAutoSize', 'skipHeaderOnAutoSize', 'suppressParentsInRowNodes', 'showToolPanel',
'suppressColumnMoveAnimation', 'suppressMovableColumns', 'suppressFieldDotNotation', 'enableRangeSelection',
'enableRangeHandle', 'enableFillHandle', 'suppressClearOnFillReduction', 'deltaSort', 'suppressTouch', 'suppressAsyncEvents',
'allowContextMenuWithControlKey', 'suppressContextMenu', 'suppressMenuFilterPanel', 'suppressMenuMainPanel', 'suppressMenuColumnPanel',
'rememberGroupStateWhenNewData', 'enableCellChangeFlash', 'suppressDragLeaveHidesColumns', 'suppressMiddleClickScrolls',
'suppressPreventDefaultOnMouseWheel', 'suppressUseColIdForGroups', 'suppressCopyRowsToClipboard', 'copyHeadersToClipboard', 'pivotMode',
'suppressAggFuncInHeader', 'suppressColumnVirtualisation', 'suppressAggAtRootLevel', 'suppressFocusAfterRefresh', 'functionsPassive',
'functionsReadOnly', 'animateRows', 'groupSelectsFiltered', 'groupRemoveSingleChildren', 'groupRemoveLowestSingleChildren', 'enableRtl',
'suppressClickEdit', 'rowDragManaged', 'suppressRowDrag', 'enableGroupEdit', 'embedFullWidthRows', 'deprecatedEmbedFullWidthRows',
'suppressTabbing', 'suppressPaginationPanel', 'floatingFilter', 'groupHideOpenParents', 'groupMultiAutoColumn', 'pagination',
'stopEditingWhenGridLosesFocus', 'paginationAutoPageSize', 'suppressScrollOnNewData', 'purgeClosedRowNodes', 'cacheQuickFilter',
'deltaRowDataMode', 'ensureDomOrder', 'accentedSort', 'pivotTotals', 'suppressChangeDetection', 'valueCache', 'valueCacheNeverExpires',
'aggregateOnlyChangedColumns', 'suppressAnimationFrame', 'suppressExcelExport', 'suppressCsvExport', 'treeData', 'masterDetail',
'suppressMultiRangeSelection', 'enterMovesDownAfterEdit', 'enterMovesDown', 'suppressPropertyNamesCheck', 'rowMultiSelectWithClick',
'contractColumnSelection', 'suppressEnterpriseResetOnNewColumns', 'enableOldSetFilterModel', 'suppressRowHoverHighlight',
'gridAutoHeight', 'suppressRowTransform', 'suppressClipboardPaste', 'serverSideSortingAlwaysResets', 'reactNext',
'suppressSetColumnStateEvents', 'enableCharts', 'deltaColumnMode', 'suppressMaintainUnsortedOrder', 'enableCellTextSelection',
'suppressBrowserResizeObserver', 'suppressMaxRenderedRowRestriction', 'excludeChildrenWhenTreeDataFiltering',
'keepDetailRows', 'paginateChildRows', 'preventDefaultOnContextMenu', 'undoRedoCellEditing', 'allowDragFromColumnsToolPanel'
];
/** You do not need to include event callbacks in this list, as they are generated automatically. */
PropertyKeys.FUNCTION_PROPERTIES = [
'localeTextFunc', 'groupRowInnerRenderer', 'groupRowInnerRendererFramework',
'dateComponent', 'dateComponentFramework', 'groupRowRenderer', 'groupRowRendererFramework', 'isExternalFilterPresent',
'getRowHeight', 'doesExternalFilterPass', 'getRowClass', 'getRowStyle', 'getRowClassRules',
'traverseNode', 'getContextMenuItems', 'getMainMenuItems', 'processRowPostCreate', 'processCellForClipboard',
'getNodeChildDetails', 'groupRowAggNodes', 'getRowNodeId', 'isFullWidthCell', 'fullWidthCellRenderer',
'fullWidthCellRendererFramework', 'doesDataFlower', 'processSecondaryColDef', 'processSecondaryColGroupDef',
'getBusinessKeyForNode', 'sendToClipboard', 'navigateToNextCell', 'tabToNextCell', 'getDetailRowData',
'processCellFromClipboard', 'getDocument', 'postProcessPopup', 'getChildCount', 'getDataPath', 'loadingCellRenderer',
'loadingCellRendererFramework', 'loadingOverlayComponent', 'loadingOverlayComponentFramework', 'noRowsOverlayComponent',
'noRowsOverlayComponentFramework', 'detailCellRenderer', 'detailCellRendererFramework',
'defaultGroupSortComparator', 'isRowMaster', 'isRowSelectable', 'postSort', 'processHeaderForClipboard',
'paginationNumberFormatter', 'processDataFromClipboard', 'getServerSideGroupKey', 'isServerSideGroup',
'suppressKeyboardEvent', 'createChartContainer', 'processChartOptions', 'getChartToolbarItems', 'fillOperation'
];
PropertyKeys.ALL_PROPERTIES = __spreadArrays(PropertyKeys.ARRAY_PROPERTIES, PropertyKeys.OBJECT_PROPERTIES, PropertyKeys.STRING_PROPERTIES, PropertyKeys.NUMBER_PROPERTIES, PropertyKeys.FUNCTION_PROPERTIES, PropertyKeys.BOOLEAN_PROPERTIES);
/**
* Used when performing property checks. This avoids noise caused when using frameworks, which can add their own
* framework-specific properties to colDefs, gridOptions etc.
*/
PropertyKeys.FRAMEWORK_PROPERTIES = [
'__ob__', '__metadata__', 'mappedColumnProperties', 'hasChildColumns', 'toColDef', 'createColDefFromGridColumn'
];
return PropertyKeys;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var ColDefUtil = /** @class */ (function () {
function ColDefUtil() {
}
ColDefUtil.STRING_PROPERTIES = [
'headerName',
'columnGroupShow',
'headerClass',
'toolPanelClass',
'headerValueGetter',
'pivotKeys',
'groupId',
'colId',
'sort',
'field',
'type',
'tooltipComponent',
'tooltipField',
'headerTooltip',
'cellClass',
'showRowGroup',
'template',
'templateUrl',
'filter',
'aggFunc',
'cellRenderer',
'cellEditor',
'pinned',
'chartDataType'
];
ColDefUtil.OBJECT_PROPERTIES = [
'headerGroupComponent',
'headerGroupComponentFramework',
'headerGroupComponentParams',
'cellStyle',
'cellRendererParams',
'cellEditorFramework',
'cellEditorParams',
'pinnedRowCellRendererFramework',
'pinnedRowCellRendererParams',
'filterFramework',
'filterParams',
'pivotValueColumn',
'headerComponent',
'headerComponentFramework',
'headerComponentParams',
'floatingFilterComponent',
'floatingFilterComponentParams',
'floatingFilterComponentFramework',
'tooltipComponent',
'tooltipComponentParams',
'tooltipComponentFramework',
'refData'
];
ColDefUtil.ARRAY_PROPERTIES = [
'children',
'sortingOrder',
'allowedAggFuncs',
'menuTabs',
'pivotTotalColumnIds',
'cellClassRules',
'icons'
];
ColDefUtil.NUMBER_PROPERTIES = [
'sortedAt',
'flex',
'width',
'minWidth',
'maxWidth',
'rowGroupIndex',
'pivotIndex'
];
ColDefUtil.BOOLEAN_PROPERTIES = [
'suppressCellFlash',
'suppressColumnsToolPanel',
'suppressFiltersToolPanel',
'openByDefault',
'marryChildren',
'hide',
'rowGroup',
'pivot',
'checkboxSelection',
'headerCheckboxSelection',
'headerCheckboxSelectionFilteredOnly',
'suppressMenu',
'suppressSorting',
'suppressMovable',
'suppressFilter',
'lockPosition',
'lockVisible',
'lockPinned',
'unSortIcon',
'suppressSizeToFit',
'suppressResize',
'suppressAutoSize',
'enableRowGroup',
'enablePivot',
'enableValue',
'editable',
'suppressPaste',
'suppressNavigable',
'enableCellChangeFlash',
'rowDrag',
'dndSource',
'autoHeight',
'sortable',
'resizable',
'singleClickEdit'
];
ColDefUtil.FUNCTION_PROPERTIES = [
'dndSourceOnRowDrag',
'valueGetter',
'valueSetter',
'filterValueGetter',
'keyCreator',
'cellRenderer',
'cellRendererFramework',
'pinnedRowCellRenderer',
'valueFormatter',
'pinnedRowValueFormatter',
'valueParser',
'comparator',
'equals',
'pivotComparator',
'suppressKeyboardEvent',
'colSpan',
'rowSpan',
'getQuickFilterText',
'newValueHandler',
'onCellValueChanged',
'onCellClicked',
'onCellDoubleClicked',
'onCellContextMenu',
'tooltip',
'tooltipValueGetter',
'tooltipComponent',
'tooltipComponentFramework',
'cellRendererSelector',
'cellEditorSelector'
];
ColDefUtil.ALL_PROPERTIES = ColDefUtil.ARRAY_PROPERTIES
.concat(ColDefUtil.OBJECT_PROPERTIES)
.concat(ColDefUtil.STRING_PROPERTIES)
.concat(ColDefUtil.NUMBER_PROPERTIES)
.concat(ColDefUtil.FUNCTION_PROPERTIES)
.concat(ColDefUtil.BOOLEAN_PROPERTIES);
// used when doing property checks - this causes noise when using frameworks which can add their own fw specific
// properties to colDefs, gridOptions etc
ColDefUtil.FRAMEWORK_PROPERTIES = ['__ob__', '__metadata__', 'mappedColumnProperties', 'hasChildColumns',
'toColDef', 'createColDefFromGridColumn'];
return ColDefUtil;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var SideBarDefParser = /** @class */ (function () {
function SideBarDefParser() {
}
SideBarDefParser.parse = function (toParse) {
if (!toParse) {
return null;
}
if (toParse === true) {
return {
toolPanels: [
SideBarDefParser.DEFAULT_COLUMN_COMP,
SideBarDefParser.DEFAULT_FILTER_COMP,
],
defaultToolPanel: 'columns'
};
}
if (typeof toParse === 'string') {
return SideBarDefParser.parse([toParse]);
}
if (Array.isArray(toParse)) {
var comps_1 = [];
toParse.forEach(function (key) {
var lookupResult = SideBarDefParser.DEFAULT_BY_KEY[key];
if (!lookupResult) {
console.warn("ag-grid: the key " + key + " is not a valid key for specifying a tool panel, valid keys are: " + Object.keys(SideBarDefParser.DEFAULT_BY_KEY).join(','));
return;
}
comps_1.push(lookupResult);
});
if (comps_1.length === 0) {
return null;
}
return {
toolPanels: comps_1,
defaultToolPanel: comps_1[0].id
};
}
var result = {
toolPanels: SideBarDefParser.parseComponents(toParse.toolPanels),
defaultToolPanel: toParse.defaultToolPanel,
hiddenByDefault: toParse.hiddenByDefault,
position: toParse.position
};
return result;
};
SideBarDefParser.parseComponents = function (from) {
var result = [];
from.forEach(function (it) {
var toAdd = null;
if (typeof it === 'string') {
var lookupResult = SideBarDefParser.DEFAULT_BY_KEY[it];
if (!lookupResult) {
console.warn("ag-grid: the key " + it + " is not a valid key for specifying a tool panel, valid keys are: " + Object.keys(SideBarDefParser.DEFAULT_BY_KEY).join(','));
return;
}
toAdd = lookupResult;
}
else {
toAdd = it;
}
result.push(toAdd);
});
return result;
};
SideBarDefParser.DEFAULT_COLUMN_COMP = {
id: 'columns',
labelDefault: 'Columns',
labelKey: 'columns',
iconKey: 'columns',
toolPanel: 'agColumnsToolPanel',
};
SideBarDefParser.DEFAULT_FILTER_COMP = {
id: 'filters',
labelDefault: 'Filters',
labelKey: 'filters',
iconKey: 'filter',
toolPanel: 'agFiltersToolPanel',
};
SideBarDefParser.DEFAULT_BY_KEY = {
columns: SideBarDefParser.DEFAULT_COLUMN_COMP,
filters: SideBarDefParser.DEFAULT_FILTER_COMP
};
return SideBarDefParser;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate$7 = (undefined && undefined.__decorate) || function (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;
};
var __param$3 = (undefined && undefined.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __spreadArrays$1 = (undefined && undefined.__spreadArrays) || function () {
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;
};
var DEFAULT_ROW_HEIGHT = 25;
var DEFAULT_DETAIL_ROW_HEIGHT = 300;
var DEFAULT_VIEWPORT_ROW_MODEL_PAGE_SIZE = 5;
var DEFAULT_VIEWPORT_ROW_MODEL_BUFFER_SIZE = 5;
var DEFAULT_KEEP_DETAIL_ROW_COUNT = 10;
function isTrue(value) {
return value === true || value === 'true';
}
function zeroOrGreater(value, defaultValue) {
if (value >= 0) {
return value;
}
// zero gets returned if number is missing or the wrong type
return defaultValue;
}
function oneOrGreater(value, defaultValue) {
if (value > 0) {
return value;
}
// zero gets returned if number is missing or the wrong type
return defaultValue;
}
var GridOptionsWrapper = /** @class */ (function () {
function GridOptionsWrapper() {
this.propertyEventService = new EventService();
this.domDataKey = '__AG_' + Math.random().toString();
this.layoutElements = [];
}
GridOptionsWrapper_1 = GridOptionsWrapper;
GridOptionsWrapper.prototype.agWire = function (gridApi, columnApi) {
this.gridOptions.api = gridApi;
this.gridOptions.columnApi = columnApi;
this.checkForDeprecated();
this.checkForViolations();
};
GridOptionsWrapper.prototype.destroy = function () {
// need to remove these, as we don't own the lifecycle of the gridOptions, we need to
// remove the references in case the user keeps the grid options, we want the rest
// of the grid to be picked up by the garbage collector
this.gridOptions.api = null;
this.gridOptions.columnApi = null;
};
GridOptionsWrapper.prototype.init = function () {
if (!(this.gridOptions.suppressPropertyNamesCheck === true)) {
this.checkGridOptionsProperties();
this.checkColumnDefProperties();
}
var async = this.useAsyncEvents();
this.eventService.addGlobalListener(this.globalEventHandler.bind(this), async);
if (this.isGroupSelectsChildren() && this.isSuppressParentsInRowNodes()) {
console.warn("ag-Grid: 'groupSelectsChildren' does not work with 'suppressParentsInRowNodes', this selection method needs the part in rowNode to work");
}
if (this.isGroupSelectsChildren()) {
if (!this.isRowSelectionMulti()) {
console.warn("ag-Grid: rowSelection must be 'multiple' for groupSelectsChildren to make sense");
}
if (this.isRowModelServerSide()) {
console.warn('ag-Grid: group selects children is NOT support for Server Side Row Model. ' +
'This is because the rows are lazy loaded, so selecting a group is not possible as' +
'the grid has no way of knowing what the children are.');
}
}
if (this.isGroupRemoveSingleChildren() && this.isGroupHideOpenParents()) {
console.warn("ag-Grid: groupRemoveSingleChildren and groupHideOpenParents do not work with each other, you need to pick one. And don't ask us how to us these together on our support forum either you will get the same answer!");
}
if (this.isEnableRangeSelection()) {
ModuleRegistry.assertRegistered(ModuleNames.RangeSelectionModule, 'enableRangeSelection');
}
if (!this.isEnableRangeSelection() && (this.isEnableRangeHandle() || this.isEnableFillHandle())) {
console.warn("ag-Grid: 'enableRangeHandle' and 'enableFillHandle' will not work unless 'enableRangeSelection' is set to true");
}
this.addEventListener(GridOptionsWrapper_1.PROP_DOM_LAYOUT, this.updateLayoutClasses.bind(this));
};
GridOptionsWrapper.prototype.checkColumnDefProperties = function () {
var _this = this;
if (this.gridOptions.columnDefs == null) {
return;
}
this.gridOptions.columnDefs.forEach(function (colDef) {
var userProperties = Object.getOwnPropertyNames(colDef);
var validProperties = __spreadArrays$1(ColDefUtil.ALL_PROPERTIES, ColDefUtil.FRAMEWORK_PROPERTIES);
_this.checkProperties(userProperties, validProperties, validProperties, 'colDef', 'https://www.ag-grid.com/javascript-grid-column-properties/');
});
};
GridOptionsWrapper.prototype.checkGridOptionsProperties = function () {
var userProperties = Object.getOwnPropertyNames(this.gridOptions);
var validProperties = __spreadArrays$1(PropertyKeys.ALL_PROPERTIES, PropertyKeys.FRAMEWORK_PROPERTIES, _.values(Events).map(function (event) { return ComponentUtil.getCallbackForEvent(event); }));
var validPropertiesAndExceptions = __spreadArrays$1(validProperties, ['api', 'columnApi']);
this.checkProperties(userProperties, validPropertiesAndExceptions, validProperties, 'gridOptions', 'https://www.ag-grid.com/javascript-grid-properties/');
};
GridOptionsWrapper.prototype.checkProperties = function (userProperties, validPropertiesAndExceptions, validProperties, containerName, docsUrl) {
var invalidProperties = _.fuzzyCheckStrings(userProperties, validPropertiesAndExceptions, validProperties);
_.iterateObject(invalidProperties, function (key, value) {
console.warn("ag-grid: invalid " + containerName + " property '" + key + "' did you mean any of these: " + value.slice(0, 8).join(", "));
});
if (Object.keys(invalidProperties).length > 0) {
console.warn("ag-grid: to see all the valid " + containerName + " properties please check: " + docsUrl);
}
};
// returns the dom data, or undefined if not found
GridOptionsWrapper.prototype.getDomData = function (element, key) {
var domData = element[this.domDataKey];
return domData ? domData[key] : undefined;
};
GridOptionsWrapper.prototype.setDomData = function (element, key, value) {
var domData = element[this.domDataKey];
if (_.missing(domData)) {
domData = {};
element[this.domDataKey] = domData;
}
domData[key] = value;
};
GridOptionsWrapper.prototype.isRowSelection = function () {
return this.gridOptions.rowSelection === 'single' || this.gridOptions.rowSelection === 'multiple';
};
GridOptionsWrapper.prototype.isRowDeselection = function () {
return isTrue(this.gridOptions.rowDeselection);
};
GridOptionsWrapper.prototype.isRowSelectionMulti = function () {
return this.gridOptions.rowSelection === 'multiple';
};
GridOptionsWrapper.prototype.isRowMultiSelectWithClick = function () {
return isTrue(this.gridOptions.rowMultiSelectWithClick);
};
GridOptionsWrapper.prototype.getContext = function () {
return this.gridOptions.context;
};
GridOptionsWrapper.prototype.isPivotMode = function () {
return isTrue(this.gridOptions.pivotMode);
};
GridOptionsWrapper.prototype.isPivotTotals = function () {
return isTrue(this.gridOptions.pivotTotals);
};
GridOptionsWrapper.prototype.getPivotColumnGroupTotals = function () {
return this.gridOptions.pivotColumnGroupTotals;
};
GridOptionsWrapper.prototype.getPivotRowTotals = function () {
return this.gridOptions.pivotRowTotals;
};
GridOptionsWrapper.prototype.isRowModelInfinite = function () {
return this.gridOptions.rowModelType === Constants.ROW_MODEL_TYPE_INFINITE;
};
GridOptionsWrapper.prototype.isRowModelViewport = function () {
return this.gridOptions.rowModelType === Constants.ROW_MODEL_TYPE_VIEWPORT;
};
GridOptionsWrapper.prototype.isRowModelServerSide = function () {
return this.gridOptions.rowModelType === Constants.ROW_MODEL_TYPE_SERVER_SIDE;
};
GridOptionsWrapper.prototype.isRowModelDefault = function () {
return (_.missing(this.gridOptions.rowModelType) ||
this.gridOptions.rowModelType === Constants.ROW_MODEL_TYPE_CLIENT_SIDE ||
this.gridOptions.rowModelType === Constants.DEPRECATED_ROW_MODEL_TYPE_NORMAL);
};
GridOptionsWrapper.prototype.isFullRowEdit = function () {
return this.gridOptions.editType === 'fullRow';
};
GridOptionsWrapper.prototype.isSuppressFocusAfterRefresh = function () {
return isTrue(this.gridOptions.suppressFocusAfterRefresh);
};
GridOptionsWrapper.prototype.isSuppressBrowserResizeObserver = function () {
return isTrue(this.gridOptions.suppressBrowserResizeObserver);
};
GridOptionsWrapper.prototype.isSuppressMaintainUnsortedOrder = function () {
return isTrue(this.gridOptions.suppressMaintainUnsortedOrder);
};
GridOptionsWrapper.prototype.isSuppressClearOnFillReduction = function () {
return isTrue(this.gridOptions.suppressClearOnFillReduction);
};
GridOptionsWrapper.prototype.isShowToolPanel = function () {
return isTrue(this.gridOptions.sideBar && Array.isArray(this.getSideBar().toolPanels));
};
GridOptionsWrapper.prototype.getSideBar = function () {
return this.gridOptions.sideBar;
};
GridOptionsWrapper.prototype.isSuppressTouch = function () {
return isTrue(this.gridOptions.suppressTouch);
};
GridOptionsWrapper.prototype.isSuppressRowTransform = function () {
return isTrue(this.gridOptions.suppressRowTransform);
};
GridOptionsWrapper.prototype.isSuppressSetColumnStateEvents = function () {
return isTrue(this.gridOptions.suppressSetColumnStateEvents);
};
GridOptionsWrapper.prototype.isAllowDragFromColumnsToolPanel = function () {
return isTrue(this.gridOptions.allowDragFromColumnsToolPanel);
};
GridOptionsWrapper.prototype.useAsyncEvents = function () {
return !isTrue(this.gridOptions.suppressAsyncEvents);
};
GridOptionsWrapper.prototype.isEnableCellChangeFlash = function () {
return isTrue(this.gridOptions.enableCellChangeFlash);
};
GridOptionsWrapper.prototype.isGroupSelectsChildren = function () {
var result = isTrue(this.gridOptions.groupSelectsChildren);
if (result && this.isTreeData()) {
console.warn('ag-Grid: groupSelectsChildren does not work with tree data');
return false;
}
return result;
};
GridOptionsWrapper.prototype.isSuppressRowHoverHighlight = function () {
return isTrue(this.gridOptions.suppressRowHoverHighlight);
};
GridOptionsWrapper.prototype.isGroupSelectsFiltered = function () {
return isTrue(this.gridOptions.groupSelectsFiltered);
};
GridOptionsWrapper.prototype.isGroupHideOpenParents = function () {
return isTrue(this.gridOptions.groupHideOpenParents);
};
// if we are doing hideOpenParents, then we always have groupMultiAutoColumn, otherwise hideOpenParents would not work
GridOptionsWrapper.prototype.isGroupMultiAutoColumn = function () {
return isTrue(this.gridOptions.groupMultiAutoColumn) || isTrue(this.gridOptions.groupHideOpenParents);
};
GridOptionsWrapper.prototype.isGroupRemoveSingleChildren = function () {
return isTrue(this.gridOptions.groupRemoveSingleChildren);
};
GridOptionsWrapper.prototype.isGroupRemoveLowestSingleChildren = function () {
return isTrue(this.gridOptions.groupRemoveLowestSingleChildren);
};
GridOptionsWrapper.prototype.isGroupIncludeFooter = function () {
return isTrue(this.gridOptions.groupIncludeFooter);
};
GridOptionsWrapper.prototype.isGroupIncludeTotalFooter = function () {
return isTrue(this.gridOptions.groupIncludeTotalFooter);
};
GridOptionsWrapper.prototype.isGroupSuppressBlankHeader = function () {
return isTrue(this.gridOptions.groupSuppressBlankHeader);
};
GridOptionsWrapper.prototype.isSuppressRowClickSelection = function () {
return isTrue(this.gridOptions.suppressRowClickSelection);
};
GridOptionsWrapper.prototype.isSuppressCellSelection = function () {
return isTrue(this.gridOptions.suppressCellSelection);
};
GridOptionsWrapper.prototype.isSuppressMultiSort = function () {
return isTrue(this.gridOptions.suppressMultiSort);
};
GridOptionsWrapper.prototype.isMultiSortKeyCtrl = function () {
return this.gridOptions.multiSortKey === 'ctrl';
};
GridOptionsWrapper.prototype.isGroupSuppressAutoColumn = function () {
return isTrue(this.gridOptions.groupSuppressAutoColumn);
};
GridOptionsWrapper.prototype.isSuppressDragLeaveHidesColumns = function () {
return isTrue(this.gridOptions.suppressDragLeaveHidesColumns);
};
GridOptionsWrapper.prototype.isSuppressScrollOnNewData = function () {
return isTrue(this.gridOptions.suppressScrollOnNewData);
};
GridOptionsWrapper.prototype.isRowDragManaged = function () {
return isTrue(this.gridOptions.rowDragManaged);
};
GridOptionsWrapper.prototype.isSuppressRowDrag = function () {
return isTrue(this.gridOptions.suppressRowDrag);
};
// returns either 'print', 'autoHeight' or 'normal' (normal is the default)
GridOptionsWrapper.prototype.getDomLayout = function () {
var domLayout = this.gridOptions.domLayout || Constants.DOM_LAYOUT_NORMAL;
var validLayouts = [
Constants.DOM_LAYOUT_PRINT,
Constants.DOM_LAYOUT_AUTO_HEIGHT,
Constants.DOM_LAYOUT_NORMAL
];
if (validLayouts.indexOf(domLayout) === -1) {
_.doOnce(function () {
return console.warn("ag-Grid: " + domLayout + " is not valid for DOM Layout, valid values are " + Constants.DOM_LAYOUT_NORMAL + ", " + Constants.DOM_LAYOUT_AUTO_HEIGHT + " and " + Constants.DOM_LAYOUT_PRINT);
}, 'warn about dom layout values');
return Constants.DOM_LAYOUT_NORMAL;
}
return domLayout;
};
GridOptionsWrapper.prototype.isSuppressHorizontalScroll = function () {
return isTrue(this.gridOptions.suppressHorizontalScroll);
};
GridOptionsWrapper.prototype.isSuppressMaxRenderedRowRestriction = function () {
return isTrue(this.gridOptions.suppressMaxRenderedRowRestriction);
};
GridOptionsWrapper.prototype.isExcludeChildrenWhenTreeDataFiltering = function () {
return isTrue(this.gridOptions.excludeChildrenWhenTreeDataFiltering);
};
GridOptionsWrapper.prototype.isAlwaysShowVerticalScroll = function () {
return isTrue(this.gridOptions.alwaysShowVerticalScroll);
};
GridOptionsWrapper.prototype.isSuppressLoadingOverlay = function () {
return isTrue(this.gridOptions.suppressLoadingOverlay);
};
GridOptionsWrapper.prototype.isSuppressNoRowsOverlay = function () {
return isTrue(this.gridOptions.suppressNoRowsOverlay);
};
GridOptionsWrapper.prototype.isSuppressFieldDotNotation = function () {
return isTrue(this.gridOptions.suppressFieldDotNotation);
};
GridOptionsWrapper.prototype.getPinnedTopRowData = function () {
return this.gridOptions.pinnedTopRowData;
};
GridOptionsWrapper.prototype.getPinnedBottomRowData = function () {
return this.gridOptions.pinnedBottomRowData;
};
GridOptionsWrapper.prototype.isFunctionsPassive = function () {
return isTrue(this.gridOptions.functionsPassive);
};
GridOptionsWrapper.prototype.isSuppressTabbing = function () {
return isTrue(this.gridOptions.suppressTabbing);
};
GridOptionsWrapper.prototype.isSuppressChangeDetection = function () {
return isTrue(this.gridOptions.suppressChangeDetection);
};
GridOptionsWrapper.prototype.isSuppressAnimationFrame = function () {
return isTrue(this.gridOptions.suppressAnimationFrame);
};
GridOptionsWrapper.prototype.getQuickFilterText = function () {
return this.gridOptions.quickFilterText;
};
GridOptionsWrapper.prototype.isCacheQuickFilter = function () {
return isTrue(this.gridOptions.cacheQuickFilter);
};
GridOptionsWrapper.prototype.isUnSortIcon = function () {
return isTrue(this.gridOptions.unSortIcon);
};
GridOptionsWrapper.prototype.isSuppressMenuHide = function () {
return isTrue(this.gridOptions.suppressMenuHide);
};
GridOptionsWrapper.prototype.isEnterMovesDownAfterEdit = function () {
return isTrue(this.gridOptions.enterMovesDownAfterEdit);
};
GridOptionsWrapper.prototype.isEnterMovesDown = function () {
return isTrue(this.gridOptions.enterMovesDown);
};
GridOptionsWrapper.prototype.isUndoRedoCellEditing = function () {
return isTrue(this.gridOptions.undoRedoCellEditing);
};
GridOptionsWrapper.prototype.getUndoRedoCellEditingLimit = function () {
return this.gridOptions.undoRedoCellEditingLimit;
};
GridOptionsWrapper.prototype.getRowStyle = function () {
return this.gridOptions.rowStyle;
};
GridOptionsWrapper.prototype.getRowClass = function () {
return this.gridOptions.rowClass;
};
GridOptionsWrapper.prototype.getRowStyleFunc = function () {
return this.gridOptions.getRowStyle;
};
GridOptionsWrapper.prototype.getRowClassFunc = function () {
return this.gridOptions.getRowClass;
};
GridOptionsWrapper.prototype.rowClassRules = function () {
return this.gridOptions.rowClassRules;
};
GridOptionsWrapper.prototype.getCreateChartContainerFunc = function () {
return this.gridOptions.createChartContainer;
};
GridOptionsWrapper.prototype.getPopupParent = function () {
return this.gridOptions.popupParent;
};
GridOptionsWrapper.prototype.getBlockLoadDebounceMillis = function () {
return this.gridOptions.blockLoadDebounceMillis;
};
GridOptionsWrapper.prototype.getPostProcessPopupFunc = function () {
return this.gridOptions.postProcessPopup;
};
GridOptionsWrapper.prototype.getDoesDataFlowerFunc = function () {
return this.gridOptions.doesDataFlower;
};
GridOptionsWrapper.prototype.getPaginationNumberFormatterFunc = function () {
return this.gridOptions.paginationNumberFormatter;
};
GridOptionsWrapper.prototype.getChildCountFunc = function () {
return this.gridOptions.getChildCount;
};
GridOptionsWrapper.prototype.getDefaultGroupSortComparator = function () {
return this.gridOptions.defaultGroupSortComparator;
};
GridOptionsWrapper.prototype.getIsFullWidthCellFunc = function () {
return this.gridOptions.isFullWidthCell;
};
GridOptionsWrapper.prototype.getFullWidthCellRendererParams = function () {
return this.gridOptions.fullWidthCellRendererParams;
};
GridOptionsWrapper.prototype.isEmbedFullWidthRows = function () {
return isTrue(this.gridOptions.embedFullWidthRows) || isTrue(this.gridOptions.deprecatedEmbedFullWidthRows);
};
GridOptionsWrapper.prototype.getSuppressKeyboardEventFunc = function () {
return this.gridOptions.suppressKeyboardEvent;
};
GridOptionsWrapper.prototype.getBusinessKeyForNodeFunc = function () {
return this.gridOptions.getBusinessKeyForNode;
};
GridOptionsWrapper.prototype.getApi = function () {
return this.gridOptions.api;
};
GridOptionsWrapper.prototype.getColumnApi = function () {
return this.gridOptions.columnApi;
};
GridOptionsWrapper.prototype.isDeltaRowDataMode = function () {
return isTrue(this.gridOptions.deltaRowDataMode);
};
GridOptionsWrapper.prototype.isDeltaColumnMode = function () {
return isTrue(this.gridOptions.deltaColumnMode);
};
GridOptionsWrapper.prototype.isEnsureDomOrder = function () {
return isTrue(this.gridOptions.ensureDomOrder);
};
GridOptionsWrapper.prototype.isEnableCharts = function () {
if (isTrue(this.gridOptions.enableCharts)) {
return ModuleRegistry.assertRegistered(ModuleNames.GridChartsModule, 'enableCharts');
}
return false;
};
GridOptionsWrapper.prototype.getColResizeDefault = function () {
return this.gridOptions.colResizeDefault;
};
GridOptionsWrapper.prototype.isSingleClickEdit = function () {
return isTrue(this.gridOptions.singleClickEdit);
};
GridOptionsWrapper.prototype.isSuppressClickEdit = function () {
return isTrue(this.gridOptions.suppressClickEdit);
};
GridOptionsWrapper.prototype.isStopEditingWhenGridLosesFocus = function () {
return isTrue(this.gridOptions.stopEditingWhenGridLosesFocus);
};
GridOptionsWrapper.prototype.getGroupDefaultExpanded = function () {
return this.gridOptions.groupDefaultExpanded;
};
GridOptionsWrapper.prototype.getMaxConcurrentDatasourceRequests = function () {
return this.gridOptions.maxConcurrentDatasourceRequests;
};
GridOptionsWrapper.prototype.getMaxBlocksInCache = function () {
return this.gridOptions.maxBlocksInCache;
};
GridOptionsWrapper.prototype.getCacheOverflowSize = function () {
return this.gridOptions.cacheOverflowSize;
};
GridOptionsWrapper.prototype.getPaginationPageSize = function () {
return this.gridOptions.paginationPageSize;
};
GridOptionsWrapper.prototype.isPaginateChildRows = function () {
// if using groupSuppressRow, means we are not showing parent rows,
// so we always paginate on the child rows here as there are no parent rows
var shouldPaginate = this.isGroupSuppressRow() || this.isGroupRemoveSingleChildren() || this.isGroupRemoveLowestSingleChildren();
if (shouldPaginate) {
return true;
}
return isTrue(this.gridOptions.paginateChildRows);
};
GridOptionsWrapper.prototype.getCacheBlockSize = function () {
return this.gridOptions.cacheBlockSize;
};
GridOptionsWrapper.prototype.getInfiniteInitialRowCount = function () {
return this.gridOptions.infiniteInitialRowCount;
};
GridOptionsWrapper.prototype.isPurgeClosedRowNodes = function () {
return isTrue(this.gridOptions.purgeClosedRowNodes);
};
GridOptionsWrapper.prototype.isSuppressPaginationPanel = function () {
return isTrue(this.gridOptions.suppressPaginationPanel);
};
GridOptionsWrapper.prototype.getRowData = function () {
return this.gridOptions.rowData;
};
// this property is different - we never allow groupUseEntireRow if in pivot mode,
// as otherwise we don't see the pivot values.
GridOptionsWrapper.prototype.isGroupUseEntireRow = function (pivotMode) {
return pivotMode ? false : isTrue(this.gridOptions.groupUseEntireRow);
};
GridOptionsWrapper.prototype.isEnableRtl = function () {
return isTrue(this.gridOptions.enableRtl);
};
GridOptionsWrapper.prototype.getAutoGroupColumnDef = function () {
return this.gridOptions.autoGroupColumnDef;
};
GridOptionsWrapper.prototype.isGroupSuppressRow = function () {
return isTrue(this.gridOptions.groupSuppressRow);
};
GridOptionsWrapper.prototype.getRowGroupPanelShow = function () {
return this.gridOptions.rowGroupPanelShow;
};
GridOptionsWrapper.prototype.getPivotPanelShow = function () {
return this.gridOptions.pivotPanelShow;
};
GridOptionsWrapper.prototype.isAngularCompileRows = function () {
return isTrue(this.gridOptions.angularCompileRows);
};
GridOptionsWrapper.prototype.isAngularCompileFilters = function () {
return isTrue(this.gridOptions.angularCompileFilters);
};
GridOptionsWrapper.prototype.isAngularCompileHeaders = function () {
return isTrue(this.gridOptions.angularCompileHeaders);
};
GridOptionsWrapper.prototype.isDebug = function () {
return isTrue(this.gridOptions.debug);
};
GridOptionsWrapper.prototype.getColumnDefs = function () {
return this.gridOptions.columnDefs;
};
GridOptionsWrapper.prototype.getColumnTypes = function () {
return this.gridOptions.columnTypes;
};
GridOptionsWrapper.prototype.getDatasource = function () {
return this.gridOptions.datasource;
};
GridOptionsWrapper.prototype.getViewportDatasource = function () {
return this.gridOptions.viewportDatasource;
};
GridOptionsWrapper.prototype.getServerSideDatasource = function () {
return this.gridOptions.serverSideDatasource;
};
GridOptionsWrapper.prototype.isAccentedSort = function () {
return isTrue(this.gridOptions.accentedSort);
};
GridOptionsWrapper.prototype.isEnableBrowserTooltips = function () {
return isTrue(this.gridOptions.enableBrowserTooltips);
};
GridOptionsWrapper.prototype.isEnableCellExpressions = function () {
return isTrue(this.gridOptions.enableCellExpressions);
};
GridOptionsWrapper.prototype.isEnableGroupEdit = function () {
return isTrue(this.gridOptions.enableGroupEdit);
};
GridOptionsWrapper.prototype.isSuppressMiddleClickScrolls = function () {
return isTrue(this.gridOptions.suppressMiddleClickScrolls);
};
GridOptionsWrapper.prototype.isPreventDefaultOnContextMenu = function () {
return isTrue(this.gridOptions.preventDefaultOnContextMenu);
};
GridOptionsWrapper.prototype.isSuppressPreventDefaultOnMouseWheel = function () {
return isTrue(this.gridOptions.suppressPreventDefaultOnMouseWheel);
};
GridOptionsWrapper.prototype.isSuppressColumnVirtualisation = function () {
return isTrue(this.gridOptions.suppressColumnVirtualisation);
};
GridOptionsWrapper.prototype.isSuppressContextMenu = function () {
return isTrue(this.gridOptions.suppressContextMenu);
};
GridOptionsWrapper.prototype.isAllowContextMenuWithControlKey = function () {
return isTrue(this.gridOptions.allowContextMenuWithControlKey);
};
GridOptionsWrapper.prototype.isSuppressCopyRowsToClipboard = function () {
return isTrue(this.gridOptions.suppressCopyRowsToClipboard);
};
GridOptionsWrapper.prototype.isCopyHeadersToClipboard = function () {
return isTrue(this.gridOptions.copyHeadersToClipboard);
};
GridOptionsWrapper.prototype.isSuppressClipboardPaste = function () {
return isTrue(this.gridOptions.suppressClipboardPaste);
};
GridOptionsWrapper.prototype.isPagination = function () {
return isTrue(this.gridOptions.pagination);
};
GridOptionsWrapper.prototype.isSuppressEnterpriseResetOnNewColumns = function () {
return isTrue(this.gridOptions.suppressEnterpriseResetOnNewColumns);
};
GridOptionsWrapper.prototype.getProcessDataFromClipboardFunc = function () {
return this.gridOptions.processDataFromClipboard;
};
GridOptionsWrapper.prototype.getBatchUpdateWaitMillis = function () {
return _.exists(this.gridOptions.batchUpdateWaitMillis) ? this.gridOptions.batchUpdateWaitMillis : Constants.BATCH_WAIT_MILLIS;
};
GridOptionsWrapper.prototype.isSuppressMovableColumns = function () {
return isTrue(this.gridOptions.suppressMovableColumns);
};
GridOptionsWrapper.prototype.isAnimateRows = function () {
// never allow animating if enforcing the row order
if (this.isEnsureDomOrder()) {
return false;
}
return isTrue(this.gridOptions.animateRows);
};
GridOptionsWrapper.prototype.isSuppressColumnMoveAnimation = function () {
return isTrue(this.gridOptions.suppressColumnMoveAnimation);
};
GridOptionsWrapper.prototype.isSuppressAggFuncInHeader = function () {
return isTrue(this.gridOptions.suppressAggFuncInHeader);
};
GridOptionsWrapper.prototype.isSuppressAggAtRootLevel = function () {
return isTrue(this.gridOptions.suppressAggAtRootLevel);
};
GridOptionsWrapper.prototype.isEnableRangeSelection = function () {
return ModuleRegistry.isRegistered(ModuleNames.RangeSelectionModule) && isTrue(this.gridOptions.enableRangeSelection);
};
GridOptionsWrapper.prototype.isEnableRangeHandle = function () {
return isTrue(this.gridOptions.enableRangeHandle);
};
GridOptionsWrapper.prototype.isEnableFillHandle = function () {
return isTrue(this.gridOptions.enableFillHandle);
};
GridOptionsWrapper.prototype.getFillOperation = function () {
return this.gridOptions.fillOperation;
};
GridOptionsWrapper.prototype.isSuppressMultiRangeSelection = function () {
return isTrue(this.gridOptions.suppressMultiRangeSelection);
};
GridOptionsWrapper.prototype.isPaginationAutoPageSize = function () {
return isTrue(this.gridOptions.paginationAutoPageSize);
};
GridOptionsWrapper.prototype.isRememberGroupStateWhenNewData = function () {
return isTrue(this.gridOptions.rememberGroupStateWhenNewData);
};
GridOptionsWrapper.prototype.getIcons = function () {
return this.gridOptions.icons;
};
GridOptionsWrapper.prototype.getAggFuncs = function () {
return this.gridOptions.aggFuncs;
};
GridOptionsWrapper.prototype.getSortingOrder = function () {
return this.gridOptions.sortingOrder;
};
GridOptionsWrapper.prototype.getAlignedGrids = function () {
return this.gridOptions.alignedGrids;
};
GridOptionsWrapper.prototype.isMasterDetail = function () {
var masterDetail = isTrue(this.gridOptions.masterDetail);
if (masterDetail) {
return ModuleRegistry.assertRegistered(ModuleNames.MasterDetailModule, 'masterDetail');
}
else {
return false;
}
};
GridOptionsWrapper.prototype.isKeepDetailRows = function () {
return isTrue(this.gridOptions.keepDetailRows);
};
GridOptionsWrapper.prototype.getKeepDetailRowsCount = function () {
if (this.gridOptions.keepDetailRowsCount > 0) {
return this.gridOptions.keepDetailRowsCount;
}
return DEFAULT_KEEP_DETAIL_ROW_COUNT;
};
GridOptionsWrapper.prototype.getIsRowMasterFunc = function () {
return this.gridOptions.isRowMaster;
};
GridOptionsWrapper.prototype.getIsRowSelectableFunc = function () {
return this.gridOptions.isRowSelectable;
};
GridOptionsWrapper.prototype.getGroupRowRendererParams = function () {
return this.gridOptions.groupRowRendererParams;
};
GridOptionsWrapper.prototype.getOverlayLoadingTemplate = function () {
return this.gridOptions.overlayLoadingTemplate;
};
GridOptionsWrapper.prototype.getOverlayNoRowsTemplate = function () {
return this.gridOptions.overlayNoRowsTemplate;
};
GridOptionsWrapper.prototype.isSuppressAutoSize = function () {
return isTrue(this.gridOptions.suppressAutoSize);
};
GridOptionsWrapper.prototype.isEnableCellTextSelection = function () {
return isTrue(this.gridOptions.enableCellTextSelection);
};
GridOptionsWrapper.prototype.isSuppressParentsInRowNodes = function () {
return isTrue(this.gridOptions.suppressParentsInRowNodes);
};
GridOptionsWrapper.prototype.isFunctionsReadOnly = function () {
return isTrue(this.gridOptions.functionsReadOnly);
};
GridOptionsWrapper.prototype.isFloatingFilter = function () {
return this.gridOptions.floatingFilter;
};
GridOptionsWrapper.prototype.isEnableCellTextSelect = function () {
return isTrue(this.gridOptions.enableCellTextSelection);
};
GridOptionsWrapper.prototype.isEnableOldSetFilterModel = function () {
return isTrue(this.gridOptions.enableOldSetFilterModel);
};
GridOptionsWrapper.prototype.getDefaultColDef = function () {
return this.gridOptions.defaultColDef;
};
GridOptionsWrapper.prototype.getDefaultColGroupDef = function () {
return this.gridOptions.defaultColGroupDef;
};
GridOptionsWrapper.prototype.getDefaultExportParams = function () {
return this.gridOptions.defaultExportParams;
};
GridOptionsWrapper.prototype.isSuppressCsvExport = function () {
return isTrue(this.gridOptions.suppressCsvExport);
};
GridOptionsWrapper.prototype.isAllowShowChangeAfterFilter = function () {
return isTrue(this.gridOptions.allowShowChangeAfterFilter);
};
GridOptionsWrapper.prototype.isSuppressExcelExport = function () {
return isTrue(this.gridOptions.suppressExcelExport);
};
GridOptionsWrapper.prototype.isSuppressMakeColumnVisibleAfterUnGroup = function () {
return isTrue(this.gridOptions.suppressMakeColumnVisibleAfterUnGroup);
};
GridOptionsWrapper.prototype.getNodeChildDetailsFunc = function () {
return this.gridOptions.getNodeChildDetails;
};
GridOptionsWrapper.prototype.getDataPathFunc = function () {
return this.gridOptions.getDataPath;
};
GridOptionsWrapper.prototype.getIsServerSideGroupFunc = function () {
return this.gridOptions.isServerSideGroup;
};
GridOptionsWrapper.prototype.getServerSideGroupKeyFunc = function () {
return this.gridOptions.getServerSideGroupKey;
};
GridOptionsWrapper.prototype.getGroupRowAggNodesFunc = function () {
return this.gridOptions.groupRowAggNodes;
};
GridOptionsWrapper.prototype.getContextMenuItemsFunc = function () {
return this.gridOptions.getContextMenuItems;
};
GridOptionsWrapper.prototype.getMainMenuItemsFunc = function () {
return this.gridOptions.getMainMenuItems;
};
GridOptionsWrapper.prototype.getChartToolbarItemsFunc = function () {
return this.gridOptions.getChartToolbarItems;
};
GridOptionsWrapper.prototype.getRowNodeIdFunc = function () {
return this.gridOptions.getRowNodeId;
};
GridOptionsWrapper.prototype.getNavigateToNextCellFunc = function () {
return this.gridOptions.navigateToNextCell;
};
GridOptionsWrapper.prototype.getTabToNextCellFunc = function () {
return this.gridOptions.tabToNextCell;
};
GridOptionsWrapper.prototype.isTreeData = function () {
var usingTreeData = isTrue(this.gridOptions.treeData);
if (usingTreeData) {
return ModuleRegistry.assertRegistered(ModuleNames.RowGroupingModule, 'Tree Data');
}
else {
return false;
}
};
GridOptionsWrapper.prototype.isValueCache = function () {
return isTrue(this.gridOptions.valueCache);
};
GridOptionsWrapper.prototype.isValueCacheNeverExpires = function () {
return isTrue(this.gridOptions.valueCacheNeverExpires);
};
GridOptionsWrapper.prototype.isDeltaSort = function () {
return isTrue(this.gridOptions.deltaSort);
};
GridOptionsWrapper.prototype.isAggregateOnlyChangedColumns = function () {
return isTrue(this.gridOptions.aggregateOnlyChangedColumns);
};
GridOptionsWrapper.prototype.getProcessSecondaryColDefFunc = function () {
return this.gridOptions.processSecondaryColDef;
};
GridOptionsWrapper.prototype.getProcessSecondaryColGroupDefFunc = function () {
return this.gridOptions.processSecondaryColGroupDef;
};
GridOptionsWrapper.prototype.getSendToClipboardFunc = function () {
return this.gridOptions.sendToClipboard;
};
GridOptionsWrapper.prototype.getProcessRowPostCreateFunc = function () {
return this.gridOptions.processRowPostCreate;
};
GridOptionsWrapper.prototype.getProcessCellForClipboardFunc = function () {
return this.gridOptions.processCellForClipboard;
};
GridOptionsWrapper.prototype.getProcessHeaderForClipboardFunc = function () {
return this.gridOptions.processHeaderForClipboard;
};
GridOptionsWrapper.prototype.getProcessCellFromClipboardFunc = function () {
return this.gridOptions.processCellFromClipboard;
};
GridOptionsWrapper.prototype.getViewportRowModelPageSize = function () {
return oneOrGreater(this.gridOptions.viewportRowModelPageSize, DEFAULT_VIEWPORT_ROW_MODEL_PAGE_SIZE);
};
GridOptionsWrapper.prototype.getViewportRowModelBufferSize = function () {
return zeroOrGreater(this.gridOptions.viewportRowModelBufferSize, DEFAULT_VIEWPORT_ROW_MODEL_BUFFER_SIZE);
};
// public getCellRenderers(): {[key: string]: {new(): ICellRenderer} | ICellRendererFunc} { return this.gridOptions.cellRenderers; }
// public getCellEditors(): {[key: string]: {new(): ICellEditor}} { return this.gridOptions.cellEditors; }
GridOptionsWrapper.prototype.isServerSideSortingAlwaysResets = function () {
return isTrue(this.gridOptions.serverSideSortingAlwaysResets);
};
GridOptionsWrapper.prototype.getPostSortFunc = function () {
return this.gridOptions.postSort;
};
GridOptionsWrapper.prototype.getProcessChartOptionsFunc = function () {
return this.gridOptions.processChartOptions;
};
GridOptionsWrapper.prototype.getClipboardDeliminator = function () {
return _.exists(this.gridOptions.clipboardDeliminator) ? this.gridOptions.clipboardDeliminator : '\t';
};
GridOptionsWrapper.prototype.setProperty = function (key, value) {
var gridOptionsNoType = this.gridOptions;
var previousValue = gridOptionsNoType[key];
if (previousValue !== value) {
gridOptionsNoType[key] = value;
var event_1 = {
type: key,
currentValue: value,
previousValue: previousValue
};
this.propertyEventService.dispatchEvent(event_1);
}
};
// this logic is repeated in lots of places. any element that had different CSS
// dependent on the layout needs to have the layout class added ot it.
GridOptionsWrapper.prototype.addLayoutElement = function (element) {
this.layoutElements.push(element);
this.updateLayoutClasses();
};
GridOptionsWrapper.prototype.updateLayoutClasses = function () {
var domLayout = this.getDomLayout();
var domLayoutAutoHeight = domLayout === Constants.DOM_LAYOUT_AUTO_HEIGHT;
var domLayoutPrint = domLayout === Constants.DOM_LAYOUT_PRINT;
var domLayoutNormal = domLayout === Constants.DOM_LAYOUT_NORMAL;
this.layoutElements.forEach(function (e) {
_.addOrRemoveCssClass(e, 'ag-layout-auto-height', domLayoutAutoHeight);
_.addOrRemoveCssClass(e, 'ag-layout-normal', domLayoutNormal);
_.addOrRemoveCssClass(e, 'ag-layout-print', domLayoutPrint);
});
};
GridOptionsWrapper.prototype.addEventListener = function (key, listener) {
GridOptionsWrapper_1.checkEventDeprecation(key);
this.propertyEventService.addEventListener(key, listener);
};
GridOptionsWrapper.checkEventDeprecation = function (eventName) {
if (eventName === 'floatingRowDataChanged') {
console.warn('ag-Grid: floatingRowDataChanged is now called pinnedRowDataChanged');
}
};
GridOptionsWrapper.prototype.removeEventListener = function (key, listener) {
this.propertyEventService.removeEventListener(key, listener);
};
GridOptionsWrapper.prototype.isSkipHeaderOnAutoSize = function () {
return !!this.gridOptions.skipHeaderOnAutoSize;
};
GridOptionsWrapper.prototype.getAutoSizePadding = function () {
return this.gridOptions.autoSizePadding && this.gridOptions.autoSizePadding > 0 ? this.gridOptions.autoSizePadding : 20;
};
// properties
GridOptionsWrapper.prototype.getHeaderHeight = function () {
if (typeof this.gridOptions.headerHeight === 'number') {
return this.gridOptions.headerHeight;
}
return this.specialForNewMaterial(25, 'headerHeight');
};
GridOptionsWrapper.prototype.getFloatingFiltersHeight = function () {
if (typeof this.gridOptions.floatingFiltersHeight === 'number') {
return this.gridOptions.floatingFiltersHeight;
}
return this.specialForNewMaterial(25, 'headerHeight');
};
GridOptionsWrapper.prototype.getGroupHeaderHeight = function () {
if (typeof this.gridOptions.groupHeaderHeight === 'number') {
return this.gridOptions.groupHeaderHeight;
}
return this.getHeaderHeight();
};
GridOptionsWrapper.prototype.getPivotHeaderHeight = function () {
if (typeof this.gridOptions.pivotHeaderHeight === 'number') {
return this.gridOptions.pivotHeaderHeight;
}
return this.getHeaderHeight();
};
GridOptionsWrapper.prototype.getPivotGroupHeaderHeight = function () {
if (typeof this.gridOptions.pivotGroupHeaderHeight === 'number') {
return this.gridOptions.pivotGroupHeaderHeight;
}
return this.getGroupHeaderHeight();
};
GridOptionsWrapper.prototype.isExternalFilterPresent = function () {
if (typeof this.gridOptions.isExternalFilterPresent === 'function') {
return this.gridOptions.isExternalFilterPresent();
}
return false;
};
GridOptionsWrapper.prototype.doesExternalFilterPass = function (node) {
if (typeof this.gridOptions.doesExternalFilterPass === 'function') {
return this.gridOptions.doesExternalFilterPass(node);
}
return false;
};
GridOptionsWrapper.prototype.getDocument = function () {
// if user is providing document, we use the users one,
// otherwise we use the document on the global namespace.
var result = null;
if (this.gridOptions.getDocument && _.exists(this.gridOptions.getDocument)) {
result = this.gridOptions.getDocument();
}
if (result && _.exists(result)) {
return result;
}
return document;
};
GridOptionsWrapper.prototype.getMinColWidth = function () {
if (this.gridOptions.minColWidth && this.gridOptions.minColWidth > GridOptionsWrapper_1.MIN_COL_WIDTH) {
return this.gridOptions.minColWidth;
}
return GridOptionsWrapper_1.MIN_COL_WIDTH;
};
GridOptionsWrapper.prototype.getMaxColWidth = function () {
if (this.gridOptions.maxColWidth && this.gridOptions.maxColWidth > GridOptionsWrapper_1.MIN_COL_WIDTH) {
return this.gridOptions.maxColWidth;
}
return null;
};
GridOptionsWrapper.prototype.getColWidth = function () {
if (typeof this.gridOptions.colWidth !== 'number' || this.gridOptions.colWidth < GridOptionsWrapper_1.MIN_COL_WIDTH) {
return 200;
}
return this.gridOptions.colWidth;
};
GridOptionsWrapper.prototype.getRowBuffer = function () {
var rowBuffer = this.gridOptions.rowBuffer;
if (typeof rowBuffer === 'number') {
if (rowBuffer < 0) {
_.doOnce(function () { return console.warn("ag-Grid: rowBuffer should not be negative"); }, 'warn rowBuffer negative');
this.gridOptions.rowBuffer = rowBuffer = 0;
}
}
else {
rowBuffer = Constants.ROW_BUFFER_SIZE;
}
return rowBuffer;
};
GridOptionsWrapper.prototype.getRowBufferInPixels = function () {
var rowsToBuffer = this.getRowBuffer();
var defaultRowHeight = this.getRowHeightAsNumber();
return rowsToBuffer * defaultRowHeight;
};
// the user might be using some non-standard scrollbar, eg a scrollbar that has zero
// width and overlays (like the Safari scrollbar, but presented in Chrome). so we
// allow the user to provide the scroll width before we work it out.
GridOptionsWrapper.prototype.getScrollbarWidth = function () {
if (this.scrollWidth == null) {
var useGridOptions = typeof this.gridOptions.scrollbarWidth === 'number' && this.gridOptions.scrollbarWidth >= 0;
this.scrollWidth = useGridOptions ? this.gridOptions.scrollbarWidth : _.getScrollbarWidth();
}
return this.scrollWidth;
};
GridOptionsWrapper.prototype.checkForDeprecated = function () {
var _this = this;
// casting to generic object, so typescript compiles even though
// we are looking for attributes that don't exist
var options = this.gridOptions;
if (options.suppressUnSort) {
console.warn('ag-grid: as of v1.12.4 suppressUnSort is not used. Please use sortingOrder instead.');
}
if (options.suppressDescSort) {
console.warn('ag-grid: as of v1.12.4 suppressDescSort is not used. Please use sortingOrder instead.');
}
if (options.groupAggFields) {
console.warn('ag-grid: as of v3 groupAggFields is not used. Please add appropriate agg fields to your columns.');
}
if (options.groupHidePivotColumns) {
console.warn('ag-grid: as of v3 groupHidePivotColumns is not used as pivot columns are now called rowGroup columns. Please refer to the documentation');
}
if (options.groupKeys) {
console.warn('ag-grid: as of v3 groupKeys is not used. You need to set rowGroupIndex on the columns to group. Please refer to the documentation');
}
if (typeof options.groupDefaultExpanded === 'boolean') {
console.warn('ag-grid: groupDefaultExpanded can no longer be boolean. for groupDefaultExpanded=true, use groupDefaultExpanded=9999 instead, to expand all the groups');
}
if (options.onRowDeselected || options.rowDeselected) {
console.warn('ag-grid: since version 3.4 event rowDeselected no longer exists, please check the docs');
}
if (options.rowsAlreadyGrouped) {
console.warn('ag-grid: since version 3.4 rowsAlreadyGrouped no longer exists, please use getNodeChildDetails() instead');
}
if (options.groupAggFunction) {
console.warn('ag-grid: since version 4.3.x groupAggFunction is now called groupRowAggNodes');
}
if (options.checkboxSelection) {
console.warn('ag-grid: since version 8.0.x checkboxSelection is not supported as a grid option. ' + 'If you want this on all columns, use defaultColDef instead and set it there');
}
if (options.paginationInitialRowCount) {
console.warn('ag-grid: since version 9.0.x paginationInitialRowCount is now called infiniteInitialRowCount');
}
if (options.infinitePageSize) {
console.warn('ag-grid: since version 9.0.x infinitePageSize is now called cacheBlockSize');
}
if (options.infiniteBlockSize) {
console.warn('ag-grid: since version 10.0.x infiniteBlockSize is now called cacheBlockSize');
}
if (options.maxPagesInCache) {
console.warn('ag-grid: since version 10.0.x maxPagesInCache is now called maxBlocksInCache');
}
if (options.paginationOverflowSize) {
console.warn('ag-grid: since version 10.0.x paginationOverflowSize is now called cacheOverflowSize');
}
// if (options.forPrint) {
// console.warn('ag-grid: since version 10.1.x, use property domLayout="forPrint" instead of forPrint=true');
// }
if (options.suppressMenuFilterPanel) {
console.warn("ag-grid: since version 11.0.x, use property colDef.menuTabs=['generalMenuTab','columnsMenuTab'] instead of suppressMenuFilterPanel=true");
}
if (options.suppressMenuMainPanel) {
console.warn("ag-grid: since version 11.0.x, use property colDef.menuTabs=['filterMenuTab','columnsMenuTab'] instead of suppressMenuMainPanel=true");
}
if (options.suppressMenuColumnPanel) {
console.warn("ag-grid: since version 11.0.x, use property colDef.menuTabs=['generalMenuTab','filterMenuTab'] instead of suppressMenuColumnPanel=true");
}
if (options.suppressUseColIdForGroups) {
console.warn("ag-grid: since version 11.0.x, this is not in use anymore. You should be able to remove it from your definition");
}
if (options.groupSuppressRow) {
console.warn("ag-grid: since version 18.2.x, 'groupSuppressRow' should not be used anymore. Instead remove row groups and perform custom sorting.");
}
if (options.groupColumnDef) {
console.warn("ag-grid: since version 11.0.x, groupColumnDef has been renamed, this property is now called autoGroupColumnDef. Please change your configuration accordingly");
}
if (options.slaveGrids) {
console.warn("ag-grid: since version 12.x, slaveGrids has been renamed, this property is now called alignedGrids. Please change your configuration accordingly");
}
if (options.floatingTopRowData) {
console.warn("ag-grid: since version 12.x, floatingTopRowData is now called pinnedTopRowData");
}
if (options.floatingBottomRowData) {
console.warn("ag-grid: since version 12.x, floatingBottomRowData is now called pinnedBottomRowData");
}
if (options.paginationStartPage) {
console.warn("ag-grid: since version 12.x, paginationStartPage is gone, please call api.paginationGoToPage(" + options.paginationStartPage + ") instead.");
}
if (options.getHeaderCellTemplate) {
console.warn("ag-grid: since version 15.x, getHeaderCellTemplate is gone, please check the header documentation on how to set header templates.");
}
if (options.headerCellTemplate) {
console.warn("ag-grid: since version 15.x, headerCellTemplate is gone, please check the header documentation on how to set header templates.");
}
if (options.headerCellRenderer) {
console.warn("ag-grid: since version 15.x, headerCellRenderer is gone, please check the header documentation on how to set header templates.");
}
if (options.angularCompileHeaders) {
console.warn("ag-grid: since version 15.x, angularCompileHeaders is gone, please see the getting started for Angular 1 docs to see how to do headers in Angular 1.x.");
}
if (options.pivotTotals) {
console.warn("ag-grid: since version 18.x, pivotTotals has been removed, instead if using pivotTotals, set pivotColumnGroupTotals='before'|'after'.");
options.pivotColumnGroupTotals = 'before';
}
if (options.rowModelType === 'inMemory') {
console.warn("ag-grid: since version 18.x, The In Memory Row Model has been renamed to the Client Side Row Model, set rowModelType='clientSide' instead.");
options.rowModelType = 'clientSide';
}
if (options.rowModelType === 'enterprise') {
console.warn("ag-grid: since version 18.x, The Enterprise Row Model has been renamed to the Server Side Row Model, set rowModelType='serverSide' instead.");
options.rowModelType = 'serverSide';
}
if (options.layoutInterval) {
console.warn("ag-grid: since version 18.x, layoutInterval is no longer a property. This is because the grid now uses CSS Flex for layout.");
}
if (options.gridAutoHeight) {
console.warn("ag-grid: since version 19.x, gridAutoHeight is gone, please use domLayout=autoHeight instead");
options.domLayout = 'autoHeight';
}
if (options.showToolPanel === true) {
console.warn("ag-grid: since version 19.x, showToolPanel is gone, please specify toolPanel components. See https://www.ag-grid.com/javascript-grid-tool-panel/");
options.showToolPanel = undefined;
options.sideBar = options.sideBar || true;
}
if (options.showToolPanel === false) {
console.warn("ag-grid: since version 19.x, showToolPanel is gone, please specify toolPanel components. See https://www.ag-grid.com/javascript-grid-tool-panel/");
options.showToolPanel = undefined;
options.sideBar = options.sideBar || false;
}
var oldToolPanelProperties = {
toolPanelSuppressRowGroups: 'suppressRowGroups',
toolPanelSuppressValues: 'suppressValues',
toolPanelSuppressPivots: 'suppressPivots',
toolPanelSuppressPivotMode: 'suppressPivotMode',
toolPanelSuppressColumnFilter: 'suppressColumnFilter',
toolPanelSuppressColumnSelectAll: 'suppressColumnSelectAll',
toolPanelSuppressSideButtons: 'suppressSideButtons',
toolPanelSuppressColumnExpandAll: 'suppressColumnExpandAll',
contractColumnSelection: 'contractColumnSelection'
};
var toolPanelColumnsCompProps = {};
Object.keys(oldToolPanelProperties).forEach(function (key) {
var translation = oldToolPanelProperties[key];
var value = _this.gridOptions[key];
if (value !== undefined) {
if (key === 'toolPanelSuppressSideButtons') {
console.warn('ag-grid: since v19.0 toolPanelSuppressSideButtons has been completely removed. See https://www.ag-grid.com/javascript-grid-tool-panel/');
return;
}
console.warn("ag-grid: since v19.0 gridOptions." + key + " is deprecated, please use gridOptions.sideBar.toolPanel[columnsIndex].componentParams." + translation);
toolPanelColumnsCompProps[translation] = value;
}
});
if (Object.keys(toolPanelColumnsCompProps).length > 0 && !_.exists(options.sideBar)) {
console.warn("ag-grid: since version 19.x, sideBar is mandatory if using toolPanel related properties. See https://www.ag-grid.com/javascript-grid-tool-panel/");
options.sideBar = true;
}
if (options.sideBar != null) {
options.sideBar = SideBarDefParser.parse(options.sideBar);
}
var sideBarDef = this.gridOptions.sideBar;
if (Object.keys(toolPanelColumnsCompProps).length > 0 && sideBarDef && sideBarDef.toolPanels) {
var columnsDef = sideBarDef.toolPanels.filter(function (it) { return it.id === 'columns'; });
if (columnsDef.length === 1) {
_.mergeDeep(columnsDef[0], {
componentParams: toolPanelColumnsCompProps
});
}
}
if (options.enableStatusBar) {
console.warn("ag-grid: since version 19.x, enableStatusBar is gone, please specify statusBar components");
options.statusBar = options.statusBar || {
components: [{ component: 'agAggregationComponent' }]
};
}
if (options.alwaysShowStatusBar) {
console.warn("ag-grid: since version 19.x, alwaysShowStatusBar is gone. Please specify a min-height on the ag-status-bar css class, eg .ag-status-bar {min-height: 35px; }");
}
if (options.enableServerSideSorting || options.enableSorting) {
console.warn("ag-Grid: since v20, grid options enableSorting and enableServerSideSorting are gone. Instead set sortable=true on the column definition for the columns sorting are allowed on. To migrate from gridOption.enableSorting=true, set gridOptions.defaultColDef.sortable=true");
if (!options.defaultColDef) {
options.defaultColDef = {};
}
if (!options.defaultColDef.sortable) {
options.defaultColDef.sortable = true;
}
}
if (options.enableFilter || options.enableServerSideFilter) {
console.warn("ag-Grid: since v20, grid options enableFilter and enableServerSideFilter are gone. Instead set filter=true (if not already specifying a specific filter) on the column definition for the columns filtering is allowed on. To migrate from gridOptions.enableFilter=true, set gridOptions.defaultColDef.filter=true. If you are explicitly setting specific filters for each column (ie colDef.filter is already set) the you don't need to do anything.");
if (!options.defaultColDef) {
options.defaultColDef = {};
}
if (!options.defaultColDef.filter) {
options.defaultColDef.filter = true;
}
}
if (options.enableColResize) {
console.warn("ag-Grid: since v20, grid options enableColResize is gone. Instead set resizable=true on the column definition for the columns resizing are allowed on. To migrate from gridOption.enableColResize=true, set gridOptions.defaultColDef.resizable=true");
if (!options.defaultColDef) {
options.defaultColDef = {};
}
if (!options.defaultColDef.resizable) {
options.defaultColDef.resizable = true;
}
}
if (options.deprecatedEmbedFullWidthRows) {
console.warn("ag-Grid: since v21.2, deprecatedEmbedFullWidthRows has been replaced with embedFullWidthRows.");
}
if (options.suppressTabbing) {
console.warn("ag-Grid: since v20.1, suppressTabbing is replaced with the more powerful grid callback suppressKeyboardEvent(params) which can suppress any keyboard event including tabbing.");
}
if (options.doesDataFlower) {
console.warn('ag-Grid: since v21.1, doesDataFlower is deprecated. Master/Detail is the new way for showing child data for a row and was introduced over a year ago. Please migrate your code to use master/detail instead.');
}
if (options.enableOldSetFilterModel) {
console.warn('ag-Grid: since v22.x, enableOldSetFilterModel is deprecated. Please move to the new Set Filter Model as the old one may not be supported in v23 onwards.');
}
};
GridOptionsWrapper.prototype.checkForViolations = function () {
if (this.isTreeData()) {
this.treeDataViolations();
}
};
GridOptionsWrapper.prototype.treeDataViolations = function () {
if (this.isRowModelDefault()) {
if (_.missing(this.getDataPathFunc())) {
console.warn('ag-Grid: property usingTreeData=true with rowModel=clientSide, but you did not ' +
'provide getDataPath function, please provide getDataPath function if using tree data.');
}
}
if (this.isRowModelServerSide()) {
if (_.missing(this.getIsServerSideGroupFunc())) {
console.warn('ag-Grid: property usingTreeData=true with rowModel=serverSide, but you did not ' +
'provide isServerSideGroup function, please provide isServerSideGroup function if using tree data.');
}
if (_.missing(this.getServerSideGroupKeyFunc())) {
console.warn('ag-Grid: property usingTreeData=true with rowModel=serverSide, but you did not ' +
'provide getServerSideGroupKey function, please provide getServerSideGroupKey function if using tree data.');
}
}
};
GridOptionsWrapper.prototype.getLocaleTextFunc = function () {
if (this.gridOptions.localeTextFunc) {
return this.gridOptions.localeTextFunc;
}
var that = this;
return function (key, defaultValue) {
var localeText = that.gridOptions.localeText;
if (localeText && localeText[key]) {
return localeText[key];
}
return defaultValue;
};
};
// responsible for calling the onXXX functions on gridOptions
GridOptionsWrapper.prototype.globalEventHandler = function (eventName, event) {
var callbackMethodName = ComponentUtil.getCallbackForEvent(eventName);
if (typeof this.gridOptions[callbackMethodName] === 'function') {
this.gridOptions[callbackMethodName](event);
}
};
// we don't allow dynamic row height for virtual paging
GridOptionsWrapper.prototype.getRowHeightAsNumber = function () {
if (!this.gridOptions.rowHeight || _.missing(this.gridOptions.rowHeight)) {
return this.getDefaultRowHeight();
}
else if (this.gridOptions.rowHeight && this.isNumeric(this.gridOptions.rowHeight)) {
return this.gridOptions.rowHeight;
}
console.warn('ag-Grid row height must be a number if not using standard row model');
return this.getDefaultRowHeight();
};
GridOptionsWrapper.prototype.getRowHeightForNode = function (rowNode, allowEstimate) {
// check the function first, in case use set both function and
// number, when using virtual pagination then function can be
// used for pinned rows and the number for the body rows.
if (allowEstimate === void 0) { allowEstimate = false; }
if (typeof this.gridOptions.getRowHeight === 'function') {
if (allowEstimate) {
return { height: this.getDefaultRowHeight(), estimated: true };
}
var params = {
node: rowNode,
data: rowNode.data,
api: this.gridOptions.api,
context: this.gridOptions.context
};
return { height: this.gridOptions.getRowHeight(params), estimated: false };
}
else if (rowNode.detail && this.isMasterDetail()) {
if (this.isNumeric(this.gridOptions.detailRowHeight)) {
return { height: this.gridOptions.detailRowHeight, estimated: false };
}
return { height: DEFAULT_DETAIL_ROW_HEIGHT, estimated: false };
}
var defaultRowHeight = this.getDefaultRowHeight();
var rowHeight = this.gridOptions.rowHeight && this.isNumeric(this.gridOptions.rowHeight) ? this.gridOptions.rowHeight : defaultRowHeight;
var minRowHeight = Math.min(defaultRowHeight, rowHeight);
if (this.columnController.isAutoRowHeightActive()) {
if (allowEstimate) {
return { height: rowHeight, estimated: true };
}
var autoHeight = this.autoHeightCalculator.getPreferredHeightForRow(rowNode);
// never return less than the default row height - covers when auto height
// cells are blank.
return { height: Math.max(autoHeight, minRowHeight), estimated: false };
}
return { height: rowHeight, estimated: false };
};
GridOptionsWrapper.prototype.isDynamicRowHeight = function () {
return typeof this.gridOptions.getRowHeight === 'function';
};
GridOptionsWrapper.prototype.getVirtualItemHeight = function () {
return this.specialForNewMaterial(20, 'virtualItemHeight');
};
GridOptionsWrapper.prototype.useNativeCheckboxes = function () {
return this.environment.useNativeCheckboxes();
};
GridOptionsWrapper.prototype.chartMenuPanelWidth = function () {
return this.environment.chartMenuPanelWidth();
};
GridOptionsWrapper.prototype.isNumeric = function (value) {
return !isNaN(value) && typeof value === 'number';
};
// Material data table has strict guidelines about whitespace, and these values are different than the ones
// ag-grid uses by default. We override the default ones for the sake of making it better out of the box
GridOptionsWrapper.prototype.specialForNewMaterial = function (defaultValue, sassVariableName) {
var theme = this.environment.getTheme().theme;
if (theme && theme.indexOf('ag-theme') === 0) {
return this.environment.getSassVariable(theme, sassVariableName);
}
return defaultValue;
};
GridOptionsWrapper.prototype.getDefaultRowHeight = function () {
return this.specialForNewMaterial(DEFAULT_ROW_HEIGHT, 'rowHeight');
};
var GridOptionsWrapper_1;
GridOptionsWrapper.MIN_COL_WIDTH = 10;
GridOptionsWrapper.PROP_HEADER_HEIGHT = 'headerHeight';
GridOptionsWrapper.PROP_GROUP_REMOVE_SINGLE_CHILDREN = 'groupRemoveSingleChildren';
GridOptionsWrapper.PROP_GROUP_REMOVE_LOWEST_SINGLE_CHILDREN = 'groupRemoveLowestSingleChildren';
GridOptionsWrapper.PROP_PIVOT_HEADER_HEIGHT = 'pivotHeaderHeight';
GridOptionsWrapper.PROP_SUPPRESS_CLIPBOARD_PASTE = 'suppressClipboardPaste';
GridOptionsWrapper.PROP_GROUP_HEADER_HEIGHT = 'groupHeaderHeight';
GridOptionsWrapper.PROP_PIVOT_GROUP_HEADER_HEIGHT = 'pivotGroupHeaderHeight';
GridOptionsWrapper.PROP_FLOATING_FILTERS_HEIGHT = 'floatingFiltersHeight';
GridOptionsWrapper.PROP_SUPPRESS_ROW_DRAG = 'suppressRowDrag';
GridOptionsWrapper.PROP_POPUP_PARENT = 'popupParent';
GridOptionsWrapper.PROP_DOM_LAYOUT = 'domLayout';
__decorate$7([
Autowired('gridOptions')
], GridOptionsWrapper.prototype, "gridOptions", void 0);
__decorate$7([
Autowired('columnController')
], GridOptionsWrapper.prototype, "columnController", void 0);
__decorate$7([
Autowired('eventService')
], GridOptionsWrapper.prototype, "eventService", void 0);
__decorate$7([
Autowired('gridApi')
], GridOptionsWrapper.prototype, "gridApi", void 0);
__decorate$7([
Autowired('columnApi')
], GridOptionsWrapper.prototype, "columnApi", void 0);
__decorate$7([
Autowired('environment')
], GridOptionsWrapper.prototype, "environment", void 0);
__decorate$7([
Autowired('autoHeightCalculator')
], GridOptionsWrapper.prototype, "autoHeightCalculator", void 0);
__decorate$7([
Autowired('context')
], GridOptionsWrapper.prototype, "context", void 0);
__decorate$7([
__param$3(0, Qualifier('gridApi')), __param$3(1, Qualifier('columnApi'))
], GridOptionsWrapper.prototype, "agWire", null);
__decorate$7([
PreDestroy
], GridOptionsWrapper.prototype, "destroy", null);
__decorate$7([
PostConstruct
], GridOptionsWrapper.prototype, "init", null);
GridOptionsWrapper = GridOptionsWrapper_1 = __decorate$7([
Bean('gridOptionsWrapper')
], GridOptionsWrapper);
return GridOptionsWrapper;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __spreadArrays$2 = (undefined && undefined.__spreadArrays) || function () {
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;
};
var ComponentUtil = /** @class */ (function () {
function ComponentUtil() {
}
ComponentUtil.getEventCallbacks = function () {
if (!ComponentUtil.EVENT_CALLBACKS) {
ComponentUtil.EVENT_CALLBACKS = ComponentUtil.EVENTS.map(function (event) { return ComponentUtil.getCallbackForEvent(event); });
}
return ComponentUtil.EVENT_CALLBACKS;
};
ComponentUtil.copyAttributesToGridOptions = function (gridOptions, component, skipEventDeprecationCheck) {
if (skipEventDeprecationCheck === void 0) { skipEventDeprecationCheck = false; }
checkForDeprecated(component);
// create empty grid options if none were passed
if (typeof gridOptions !== 'object') {
gridOptions = {};
}
// to allow array style lookup in TypeScript, take type away from 'this' and 'gridOptions'
var pGridOptions = gridOptions;
var keyExists = function (key) { return typeof component[key] !== 'undefined'; };
// add in all the simple properties
__spreadArrays$2(ComponentUtil.ARRAY_PROPERTIES, ComponentUtil.STRING_PROPERTIES, ComponentUtil.OBJECT_PROPERTIES, ComponentUtil.FUNCTION_PROPERTIES, ComponentUtil.getEventCallbacks()).filter(keyExists)
.forEach(function (key) { return pGridOptions[key] = component[key]; });
ComponentUtil.BOOLEAN_PROPERTIES
.filter(keyExists)
.forEach(function (key) { return pGridOptions[key] = ComponentUtil.toBoolean(component[key]); });
ComponentUtil.NUMBER_PROPERTIES
.filter(keyExists)
.forEach(function (key) { return pGridOptions[key] = ComponentUtil.toNumber(component[key]); });
// purely for event deprecation checks (for frameworks - wouldn't apply for non-fw versions)
if (!skipEventDeprecationCheck) {
ComponentUtil.EVENTS
// React uses onXXX, not sure why this is different to the other frameworks
.filter(function (event) { return keyExists(event) || keyExists(ComponentUtil.getCallbackForEvent(event)); })
.forEach(function (event) { return GridOptionsWrapper.checkEventDeprecation(event); });
}
return gridOptions;
};
ComponentUtil.getCallbackForEvent = function (eventName) {
if (!eventName || eventName.length < 2) {
return eventName;
}
else {
return 'on' + eventName[0].toUpperCase() + eventName.substr(1);
}
};
ComponentUtil.processOnChange = function (changes, gridOptions, api, columnApi) {
if (!changes) {
return;
}
checkForDeprecated(changes);
// to allow array style lookup in TypeScript, take type away from 'this' and 'gridOptions'
var pGridOptions = gridOptions;
var keyExists = function (key) { return changes[key]; };
// check if any change for the simple types, and if so, then just copy in the new value
__spreadArrays$2(ComponentUtil.ARRAY_PROPERTIES, ComponentUtil.OBJECT_PROPERTIES, ComponentUtil.STRING_PROPERTIES, ComponentUtil.getEventCallbacks()).filter(keyExists)
.forEach(function (key) { return pGridOptions[key] = changes[key].currentValue; });
ComponentUtil.BOOLEAN_PROPERTIES
.filter(keyExists)
.forEach(function (key) { return pGridOptions[key] = ComponentUtil.toBoolean(changes[key].currentValue); });
ComponentUtil.NUMBER_PROPERTIES
.filter(keyExists)
.forEach(function (key) { return pGridOptions[key] = ComponentUtil.toNumber(changes[key].currentValue); });
if (changes.enableCellTextSelection) {
api.setEnableCellTextSelection(ComponentUtil.toBoolean(changes.enableCellTextSelection.currentValue));
}
if (changes.showToolPanel) {
api.showToolPanel(ComponentUtil.toBoolean(changes.showToolPanel.currentValue));
}
if (changes.quickFilterText) {
api.setQuickFilter(changes.quickFilterText.currentValue);
}
if (changes.rowData) {
api.setRowData(changes.rowData.currentValue);
}
if (changes.pinnedTopRowData) {
api.setPinnedTopRowData(changes.pinnedTopRowData.currentValue);
}
if (changes.pinnedBottomRowData) {
api.setPinnedBottomRowData(changes.pinnedBottomRowData.currentValue);
}
if (changes.columnDefs) {
api.setColumnDefs(changes.columnDefs.currentValue, "gridOptionsChanged");
}
if (changes.datasource) {
api.setDatasource(changes.datasource.currentValue);
}
if (changes.headerHeight) {
api.setHeaderHeight(ComponentUtil.toNumber(changes.headerHeight.currentValue));
}
if (changes.paginationPageSize) {
api.paginationSetPageSize(ComponentUtil.toNumber(changes.paginationPageSize.currentValue));
}
if (changes.pivotMode) {
columnApi.setPivotMode(ComponentUtil.toBoolean(changes.pivotMode.currentValue));
}
if (changes.groupRemoveSingleChildren) {
api.setGroupRemoveSingleChildren(ComponentUtil.toBoolean(changes.groupRemoveSingleChildren.currentValue));
}
if (changes.suppressRowDrag) {
api.setSuppressRowDrag(ComponentUtil.toBoolean(changes.suppressRowDrag.currentValue));
}
if (changes.gridAutoHeight) {
api.setGridAutoHeight(ComponentUtil.toBoolean(changes.gridAutoHeight.currentValue));
}
if (changes.suppressClipboardPaste) {
api.setSuppressClipboardPaste(ComponentUtil.toBoolean(changes.suppressClipboardPaste.currentValue));
}
if (changes.sideBar) {
api.setSideBar(changes.sideBar.currentValue);
}
// copy changes into an event for dispatch
var event = {
type: Events.EVENT_COMPONENT_STATE_CHANGED,
api: gridOptions.api,
columnApi: gridOptions.columnApi
};
_.iterateObject(changes, function (key, value) {
event[key] = value;
});
api.dispatchEvent(event);
};
ComponentUtil.toBoolean = function (value) {
if (typeof value === 'boolean') {
return value;
}
else if (typeof value === 'string') {
// for boolean, compare to empty String to allow attributes appearing with
// no value to be treated as 'true'
return value.toUpperCase() === 'TRUE' || value == '';
}
else {
return false;
}
};
ComponentUtil.toNumber = function (value) {
if (typeof value === 'number') {
return value;
}
else if (typeof value === 'string') {
return Number(value);
}
else {
return undefined;
}
};
// all the events are populated in here AFTER this class (at the bottom of the file).
ComponentUtil.EVENTS = [];
ComponentUtil.STRING_PROPERTIES = PropertyKeys.STRING_PROPERTIES;
ComponentUtil.OBJECT_PROPERTIES = PropertyKeys.OBJECT_PROPERTIES;
ComponentUtil.ARRAY_PROPERTIES = PropertyKeys.ARRAY_PROPERTIES;
ComponentUtil.NUMBER_PROPERTIES = PropertyKeys.NUMBER_PROPERTIES;
ComponentUtil.BOOLEAN_PROPERTIES = PropertyKeys.BOOLEAN_PROPERTIES;
ComponentUtil.FUNCTION_PROPERTIES = PropertyKeys.FUNCTION_PROPERTIES;
ComponentUtil.ALL_PROPERTIES = PropertyKeys.ALL_PROPERTIES;
return ComponentUtil;
}());
ComponentUtil.EVENTS = _.values(Events);
function checkForDeprecated(changes) {
if (changes.rowDeselected || changes.onRowDeselected) {
console.warn('ag-grid: as of v3.4 rowDeselected no longer exists. Please check the docs.');
}
}
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate$8 = (undefined && undefined.__decorate) || function (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;
};
var BeanStub = /** @class */ (function () {
function BeanStub() {
var _this = this;
this.destroyFunctions = [];
this.destroyed = false;
this.getContext = function () { return _this.context; };
this.isAlive = function () { return !_this.destroyed; };
}
// this was a test constructor niall built, when active, it prints after 5 seconds all beans/components that are
// not destroyed. to use, create a new grid, then api.destroy() before 5 seconds. then anything that gets printed
// points to a bean or component that was not properly disposed of.
// constructor() {
// setTimeout(()=> {
// if (this.isAlive()) {
// let prototype: any = Object.getPrototypeOf(this);
// const constructor: any = prototype.constructor;
// const constructorString = constructor.toString();
// const beanName = constructorString.substring(9, constructorString.indexOf("("));
// console.log('is alive ' + beanName);
// }
// }, 5000);
// }
// CellComp and GridComp and override this because they get the FrameworkOverrides from the Beans bean
BeanStub.prototype.getFrameworkOverrides = function () {
return this.frameworkOverrides;
};
BeanStub.prototype.destroy = function () {
// let prototype: any = Object.getPrototypeOf(this);
// const constructor: any = prototype.constructor;
// const constructorString = constructor.toString();
// const beanName = constructorString.substring(9, constructorString.indexOf("("));
this.destroyFunctions.forEach(function (func) { return func(); });
this.destroyFunctions.length = 0;
this.destroyed = true;
this.dispatchEvent({ type: BeanStub.EVENT_DESTROYED });
};
BeanStub.prototype.addEventListener = function (eventType, listener) {
if (!this.localEventService) {
this.localEventService = new EventService();
}
this.localEventService.addEventListener(eventType, listener);
};
BeanStub.prototype.removeEventListener = function (eventType, listener) {
if (this.localEventService) {
this.localEventService.removeEventListener(eventType, listener);
}
};
BeanStub.prototype.dispatchEventAsync = function (event) {
var _this = this;
window.setTimeout(function () { return _this.dispatchEvent(event); }, 0);
};
BeanStub.prototype.dispatchEvent = function (event) {
if (this.localEventService) {
this.localEventService.dispatchEvent(event);
}
};
BeanStub.prototype.addDestroyableEventListener = function (object, event, listener) {
var _this = this;
if (this.destroyed) {
return;
}
if (object instanceof HTMLElement) {
_.addSafePassiveEventListener(this.getFrameworkOverrides(), object, event, listener);
}
else {
object.addEventListener(event, listener);
}
var destroyFunc = function () {
object.removeEventListener(event, listener);
_this.destroyFunctions = _this.destroyFunctions.filter(function (fn) { return fn !== destroyFunc; });
};
this.destroyFunctions.push(destroyFunc);
return destroyFunc;
};
BeanStub.prototype.addDestroyFunc = function (func) {
// if we are already destroyed, we execute the func now
if (this.isAlive()) {
this.destroyFunctions.push(func);
}
else {
func();
}
};
BeanStub.prototype.wireDependentBean = function (bean, context) {
if (bean.destroy) {
this.addDestroyFunc(bean.destroy.bind(bean));
}
return this.wireBean(bean, context);
};
BeanStub.prototype.wireBean = function (bean, context) {
(context || this.getContext()).wireBean(bean);
return bean;
};
BeanStub.EVENT_DESTROYED = 'destroyed';
__decorate$8([
Autowired('context')
], BeanStub.prototype, "context", void 0);
__decorate$8([
Autowired('frameworkOverrides')
], BeanStub.prototype, "frameworkOverrides", void 0);
__decorate$8([
PreDestroy
], BeanStub.prototype, "destroy", null);
return BeanStub;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate$9 = (undefined && undefined.__decorate) || function (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;
};
var compIdSequence = new NumberSequence();
var Component = /** @class */ (function (_super) {
__extends(Component, _super);
function Component(template) {
var _this = _super.call(this) || this;
_this.childComponents = [];
_this.annotatedEventListeners = [];
// if false, then CSS class "ag-hidden" is applied, which sets "display: none"
_this.displayed = true;
// if false, then CSS class "ag-invisible" is applied, which sets "visibility: hidden"
_this.visible = true;
// unique id for this row component. this is used for getting a reference to the HTML dom.
// we cannot use the RowNode id as this is not unique (due to animation, old rows can be lying
// around as we create a new rowComp instance for the same row node).
_this.compId = compIdSequence.next();
if (template) {
_this.setTemplate(template);
}
return _this;
}
Component.prototype.getCompId = function () {
return this.compId;
};
// for registered components only, eg creates AgCheckbox instance from ag-checkbox HTML tag
Component.prototype.createChildComponentsFromTags = function (parentNode) {
var _this = this;
// we MUST take a copy of the list first, as the 'swapComponentForNode' adds comments into the DOM
// which messes up the traversal order of the children.
var childNodeList = _.copyNodeList(parentNode.childNodes);
childNodeList.forEach(function (childNode) {
var childComp = _this.getContext().createComponentFromElement(childNode, function (childComp) {
// copy over all attributes, including css classes, so any attributes user put on the tag
// wll be carried across
_this.copyAttributesFromNode(childNode, childComp.getGui());
});
if (childComp) {
if (childComp.addItems && childNode.children.length) {
_this.createChildComponentsFromTags(childNode);
// converting from HTMLCollection to Array
var items = Array.prototype.slice.call(childNode.children);
childComp.addItems(items);
}
// replace the tag (eg ag-checkbox) with the proper HTMLElement (eg 'div') in the dom
_this.swapComponentForNode(childComp, parentNode, childNode);
}
else if (childNode.childNodes) {
_this.createChildComponentsFromTags(childNode);
}
});
};
Component.prototype.copyAttributesFromNode = function (source, dest) {
_.iterateNamedNodeMap(source.attributes, function (name, value) {
dest.setAttribute(name, value);
});
};
Component.prototype.swapComponentForNode = function (newComponent, parentNode, childNode) {
var eComponent = newComponent.getGui();
parentNode.replaceChild(eComponent, childNode);
parentNode.insertBefore(document.createComment(childNode.nodeName), eComponent);
this.childComponents.push(newComponent);
this.swapInComponentForQuerySelectors(newComponent, childNode);
};
Component.prototype.swapInComponentForQuerySelectors = function (newComponent, childNode) {
var thisProto = Object.getPrototypeOf(this);
var thisNoType = this;
while (thisProto != null) {
var metaData = thisProto.__agComponentMetaData;
var currentProtoName = (thisProto.constructor).name;
if (metaData && metaData[currentProtoName] && metaData[currentProtoName].querySelectors) {
metaData[currentProtoName].querySelectors.forEach(function (querySelector) {
if (thisNoType[querySelector.attributeName] === childNode) {
thisNoType[querySelector.attributeName] = newComponent;
}
});
}
thisProto = Object.getPrototypeOf(thisProto);
}
};
Component.prototype.setTemplate = function (template) {
var eGui = _.loadTemplate(template);
this.setTemplateFromElement(eGui);
};
Component.prototype.setTemplateFromElement = function (element) {
this.eGui = element;
this.eGui.__agComponent = this;
this.addAnnotatedEventListeners();
this.wireQuerySelectors();
// context will not be available when user sets template in constructor
var contextIsAvailable = !!this.getContext();
if (contextIsAvailable) {
this.createChildComponentsFromTags(this.getGui());
}
};
Component.prototype.createChildComponentsPreConstruct = function () {
// ui exists if user sets template in constructor. when this happens, we have to wait for the context
// to be autoWired first before we can create child components.
var uiExists = !!this.getGui();
if (uiExists) {
this.createChildComponentsFromTags(this.getGui());
}
};
Component.prototype.wireQuerySelectors = function () {
var _this = this;
if (!this.eGui) {
return;
}
var thisProto = Object.getPrototypeOf(this);
var _loop_1 = function () {
var metaData = thisProto.__agComponentMetaData;
var currentProtoName = (thisProto.constructor).name;
if (metaData && metaData[currentProtoName] && metaData[currentProtoName].querySelectors) {
var thisNoType_1 = this_1;
metaData[currentProtoName].querySelectors.forEach(function (querySelector) {
var resultOfQuery = _this.eGui.querySelector(querySelector.querySelector);
if (resultOfQuery) {
var backingComponent = resultOfQuery.__agComponent;
if (backingComponent) {
thisNoType_1[querySelector.attributeName] = backingComponent;
}
else {
thisNoType_1[querySelector.attributeName] = resultOfQuery;
}
}
});
}
thisProto = Object.getPrototypeOf(thisProto);
};
var this_1 = this;
while (thisProto != null) {
_loop_1();
}
};
Component.prototype.addAnnotatedEventListeners = function () {
var _this = this;
this.removeAnnotatedEventListeners();
if (!this.eGui) {
return;
}
var listenerMethods = this.getAgComponentMetaData('listenerMethods');
if (_.missingOrEmpty(listenerMethods)) {
return;
}
if (!this.annotatedEventListeners) {
this.annotatedEventListeners = [];
}
listenerMethods.forEach(function (eventListener) {
var listener = _this[eventListener.methodName].bind(_this);
_this.eGui.addEventListener(eventListener.eventName, listener);
_this.annotatedEventListeners.push({ eventName: eventListener.eventName, listener: listener });
});
};
Component.prototype.getAgComponentMetaData = function (key) {
var res = [];
var thisProto = Object.getPrototypeOf(this);
while (thisProto != null) {
var metaData = thisProto.__agComponentMetaData;
var currentProtoName = (thisProto.constructor).name;
// IE does not support Function.prototype.name, so we need to extract
// the name using a RegEx
// from: https://matt.scharley.me/2012/03/monkey-patch-name-ie.html
if (currentProtoName === undefined) {
var funcNameRegex = /function\s([^(]{1,})\(/;
var results = funcNameRegex.exec(thisProto.constructor.toString());
if (results && results.length > 1) {
currentProtoName = results[1].trim();
}
}
if (metaData && metaData[currentProtoName] && metaData[currentProtoName][key]) {
res = res.concat(metaData[currentProtoName][key]);
}
thisProto = Object.getPrototypeOf(thisProto);
}
return res;
};
Component.prototype.removeAnnotatedEventListeners = function () {
var _this = this;
if (!this.annotatedEventListeners || !this.eGui) {
return;
}
this.annotatedEventListeners.forEach(function (eventListener) {
_this.eGui.removeEventListener(eventListener.eventName, eventListener.listener);
});
this.annotatedEventListeners = [];
};
Component.prototype.getGui = function () {
return this.eGui;
};
Component.prototype.setParentComponent = function (component) {
this.parentComponent = component;
};
Component.prototype.getParentComponent = function () {
return this.parentComponent;
};
// this method is for older code, that wants to provide the gui element,
// it is not intended for this to be in ag-Stack
Component.prototype.setGui = function (eGui) {
this.eGui = eGui;
};
Component.prototype.queryForHtmlElement = function (cssSelector) {
return this.eGui.querySelector(cssSelector);
};
Component.prototype.queryForHtmlInputElement = function (cssSelector) {
return this.eGui.querySelector(cssSelector);
};
Component.prototype.appendChild = function (newChild) {
if (_.isNodeOrElement(newChild)) {
this.eGui.appendChild(newChild);
}
else {
var childComponent = newChild;
this.eGui.appendChild(childComponent.getGui());
this.childComponents.push(childComponent);
}
};
Component.prototype.addFeature = function (feature, context) {
this.wireDependentBean(feature, context);
};
Component.prototype.isDisplayed = function () {
return this.displayed;
};
Component.prototype.setVisible = function (visible) {
if (visible !== this.visible) {
this.visible = visible;
_.setVisible(this.eGui, visible);
}
};
Component.prototype.setDisplayed = function (displayed) {
if (displayed !== this.displayed) {
this.displayed = displayed;
_.setDisplayed(this.eGui, displayed);
var event_1 = {
type: Component.EVENT_DISPLAYED_CHANGED,
visible: this.displayed
};
this.dispatchEvent(event_1);
}
};
Component.prototype.addOrRemoveCssClass = function (className, addOrRemove) {
_.addOrRemoveCssClass(this.eGui, className, addOrRemove);
};
Component.prototype.destroy = function () {
_super.prototype.destroy.call(this);
this.childComponents.forEach(function (childComponent) {
if (childComponent && childComponent.destroy) {
childComponent.destroy();
}
});
this.childComponents.length = 0;
this.removeAnnotatedEventListeners();
};
Component.prototype.addGuiEventListener = function (event, listener) {
var _this = this;
this.getGui().addEventListener(event, listener);
this.addDestroyFunc(function () { return _this.getGui().removeEventListener(event, listener); });
};
Component.prototype.addCssClass = function (className) {
_.addCssClass(this.getGui(), className);
};
Component.prototype.removeCssClass = function (className) {
_.removeCssClass(this.getGui(), className);
};
Component.prototype.getAttribute = function (key) {
var eGui = this.getGui();
return eGui ? eGui.getAttribute(key) : null;
};
Component.prototype.getRefElement = function (refName) {
return this.queryForHtmlElement('[ref="' + refName + '"]');
};
Component.EVENT_DISPLAYED_CHANGED = 'displayedChanged';
__decorate$9([
PreConstruct
], Component.prototype, "createChildComponentsPreConstruct", null);
return Component;
}(BeanStub));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends$1 = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var PopupComponent = /** @class */ (function (_super) {
__extends$1(PopupComponent, _super);
function PopupComponent() {
return _super !== null && _super.apply(this, arguments) || this;
}
PopupComponent.prototype.isPopup = function () {
return true;
};
PopupComponent.prototype.setParentComponent = function (container) {
_.addCssClass(container.getGui(), 'ag-has-popup');
_super.prototype.setParentComponent.call(this, container);
};
PopupComponent.prototype.destroy = function () {
var parentComp = this.parentComponent;
var hasParent = parentComp && parentComp.isAlive();
if (hasParent) {
_.removeCssClass(parentComp.getGui(), 'ag-has-popup');
}
_super.prototype.destroy.call(this);
};
return PopupComponent;
}(Component));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends$2 = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var TextCellEditor = /** @class */ (function (_super) {
__extends$2(TextCellEditor, _super);
function TextCellEditor() {
var _this = _super.call(this, TextCellEditor.TEMPLATE) || this;
_this.eInput = _this.getGui().querySelector('input');
return _this;
}
TextCellEditor.prototype.init = function (params) {
this.params = params;
var eInput = this.eInput;
var startValue;
// cellStartedEdit is only false if we are doing fullRow editing
if (params.cellStartedEdit) {
this.focusAfterAttached = true;
var keyPressBackspaceOrDelete = params.keyPress === Constants.KEY_BACKSPACE
|| params.keyPress === Constants.KEY_DELETE;
if (keyPressBackspaceOrDelete) {
startValue = '';
}
else if (params.charPress) {
startValue = params.charPress;
}
else {
startValue = this.getStartValue(params);
if (params.keyPress !== Constants.KEY_F2) {
this.highlightAllOnFocus = true;
}
}
}
else {
this.focusAfterAttached = false;
startValue = this.getStartValue(params);
}
if (_.exists(startValue)) {
eInput.value = startValue;
}
this.addDestroyableEventListener(eInput, 'keydown', function (event) {
var pageUp = event.keyCode === Constants.KEY_PAGE_UP;
var pageDown = event.keyCode === Constants.KEY_PAGE_DOWN;
if (pageUp || pageDown) {
event.preventDefault();
}
});
};
TextCellEditor.prototype.afterGuiAttached = function () {
if (!this.focusAfterAttached) {
return;
}
var eInput = this.eInput;
// Added for AG-3238. We can't remove this explicit focus() because Chrome requires an input
// to be focussed before setSelectionRange will work. But it triggers a bug in Safari where
// explicitly focussing then blurring an empty field will cause the parent container to scroll.
if (!_.isBrowserSafari()) {
eInput.focus();
}
if (this.highlightAllOnFocus) {
eInput.select();
}
else {
// when we started editing, we want the caret at the end, not the start.
// this comes into play in two scenarios: a) when user hits F2 and b)
// when user hits a printable character, then on IE (and only IE) the caret
// was placed after the first character, thus 'apply' would end up as 'pplea'
var length_1 = eInput.value ? eInput.value.length : 0;
if (length_1 > 0) {
eInput.setSelectionRange(length_1, length_1);
}
}
};
// gets called when tabbing trough cells and in full row edit mode
TextCellEditor.prototype.focusIn = function () {
var eInput = this.eInput;
eInput.focus();
eInput.select();
};
TextCellEditor.prototype.getValue = function () {
var eInput = this.eInput;
return this.params.parseValue(eInput.value);
};
TextCellEditor.prototype.getStartValue = function (params) {
var formatValue = params.useFormatter || params.column.getColDef().refData;
return formatValue ? params.formatValue(params.value) : params.value;
};
TextCellEditor.prototype.isPopup = function () {
return false;
};
TextCellEditor.TEMPLATE = '';
return TextCellEditor;
}(PopupComponent));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
function QuerySelector(selector) {
return querySelectorFunc.bind(this, selector);
}
function RefSelector(ref) {
return querySelectorFunc.bind(this, "[ref=" + ref + "]");
}
function querySelectorFunc(selector, classPrototype, methodOrAttributeName, index) {
if (selector === null) {
console.error("ag-Grid: QuerySelector selector should not be null");
return;
}
if (typeof index === "number") {
console.error("ag-Grid: QuerySelector should be on an attribute");
return;
}
addToObjectProps(classPrototype, 'querySelectors', {
attributeName: methodOrAttributeName,
querySelector: selector
});
}
// think we should take this out, put property bindings on the
function Listener(eventName) {
return listenerFunc.bind(this, eventName);
}
function listenerFunc(eventName, target, methodName) {
if (eventName === null) {
console.error("ag-Grid: EventListener eventName should not be null");
return;
}
addToObjectProps(target, 'listenerMethods', {
methodName: methodName,
eventName: eventName
});
}
function addToObjectProps(target, key, value) {
// it's an attribute on the class
var props = getOrCreateProps$1(target, target.constructor.name);
if (!props[key]) {
props[key] = [];
}
props[key].push(value);
}
function getOrCreateProps$1(target, instanceName) {
if (!target.__agComponentMetaData) {
target.__agComponentMetaData = {};
}
if (!target.__agComponentMetaData[instanceName]) {
target.__agComponentMetaData[instanceName] = {};
}
return target.__agComponentMetaData[instanceName];
}
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
/** Provides sync access to async component. Date component can be lazy created - this class encapsulates
* this by keeping value locally until DateComp has loaded, then passing DateComp the value. */
var DateCompWrapper = /** @class */ (function () {
function DateCompWrapper(userComponentFactory, dateComponentParams, eParent) {
var _this = this;
this.alive = true;
userComponentFactory.newDateComponent(dateComponentParams).then(function (dateComp) {
// because async, check the filter still exists after component comes back
if (!_this.alive) {
if (dateComp.destroy) {
dateComp.destroy();
}
return;
}
_this.dateComp = dateComp;
eParent.appendChild(dateComp.getGui());
if (dateComp.afterGuiAttached) {
dateComp.afterGuiAttached();
}
if (_this.tempValue) {
dateComp.setDate(_this.tempValue);
}
});
}
DateCompWrapper.prototype.destroy = function () {
this.alive = false;
if (this.dateComp && this.dateComp.destroy) {
this.dateComp.destroy();
}
};
DateCompWrapper.prototype.getDate = function () {
if (this.dateComp) {
return this.dateComp.getDate();
}
else {
return this.tempValue;
}
};
DateCompWrapper.prototype.setDate = function (value) {
if (this.dateComp) {
this.dateComp.setDate(value);
}
else {
this.tempValue = value;
}
};
return DateCompWrapper;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
/* Common logic for options, used by both filters and floating filters. */
var OptionsFactory = /** @class */ (function () {
function OptionsFactory() {
this.customFilterOptions = {};
}
OptionsFactory.prototype.init = function (params, defaultOptions) {
this.filterOptions = params.filterOptions ? params.filterOptions : defaultOptions;
this.mapCustomOptions();
this.selectDefaultItem(params);
};
OptionsFactory.prototype.getFilterOptions = function () {
return this.filterOptions;
};
OptionsFactory.prototype.mapCustomOptions = function () {
var _this = this;
if (!this.filterOptions) {
return;
}
this.filterOptions.forEach(function (filterOption) {
if (typeof filterOption === 'string') {
return;
}
if (!filterOption.displayKey) {
console.warn("ag-Grid: ignoring FilterOptionDef as it doesn't contain a 'displayKey'");
return;
}
if (!filterOption.displayName) {
console.warn("ag-Grid: ignoring FilterOptionDef as it doesn't contain a 'displayName'");
return;
}
if (!filterOption.test) {
console.warn("ag-Grid: ignoring FilterOptionDef as it doesn't contain a 'test'");
return;
}
_this.customFilterOptions[filterOption.displayKey] = filterOption;
});
};
OptionsFactory.prototype.selectDefaultItem = function (params) {
if (params.defaultOption) {
this.defaultOption = params.defaultOption;
}
else if (this.filterOptions.length >= 1) {
var firstFilterOption = this.filterOptions[0];
if (typeof firstFilterOption === 'string') {
this.defaultOption = firstFilterOption;
}
else if (firstFilterOption.displayKey) {
this.defaultOption = firstFilterOption.displayKey;
}
else {
console.warn("ag-Grid: invalid FilterOptionDef supplied as it doesn't contain a 'displayKey'");
}
}
else {
console.warn('ag-Grid: no filter options for filter');
}
};
OptionsFactory.prototype.getDefaultOption = function () {
return this.defaultOption;
};
OptionsFactory.prototype.getCustomOption = function (name) {
return this.customFilterOptions[name];
};
return OptionsFactory;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends$3 = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate$a = (undefined && undefined.__decorate) || function (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;
};
/**
* Contains common logic to all provided filters (apply button, clear button, etc).
* All the filters that come with ag-Grid extend this class. User filters do not
* extend this class.
*/
var ProvidedFilter = /** @class */ (function (_super) {
__extends$3(ProvidedFilter, _super);
function ProvidedFilter() {
return _super !== null && _super.apply(this, arguments) || this;
}
/** @deprecated */
ProvidedFilter.prototype.onFilterChanged = function () {
console.warn("ag-Grid: you should not call onFilterChanged() directly on the filter, please call\n gridApi.onFilterChanged() instead. onFilterChanged is not part of the exposed filter interface (it was\n a method that existed on an old version of the filters that was not intended for public use.");
this.providedFilterParams.filterChangedCallback();
};
ProvidedFilter.prototype.isFilterActive = function () {
// filter is active if we have a valid applied model
return !!this.appliedModel;
};
ProvidedFilter.prototype.postConstruct = function () {
var templateString = this.createTemplate();
this.setTemplate(templateString);
};
ProvidedFilter.prototype.init = function (params) {
this.setParams(params);
this.resetUiToDefaults();
this.updateUiVisibility();
this.setupOnBtApplyDebounce();
};
ProvidedFilter.prototype.setParams = function (params) {
var _this = this;
this.providedFilterParams = params;
this.applyActive = ProvidedFilter.isUseApplyButton(params);
if (params.newRowsAction === ProvidedFilter.NEW_ROWS_ACTION_KEEP) {
this.newRowsActionKeep = true;
}
else if (params.newRowsAction === ProvidedFilter.NEW_ROWS_ACTION_CLEAR) {
this.newRowsActionKeep = false;
}
else {
// the default for SSRM and IRM is 'keep', for CSRM and VRM teh default is 'clear'
var rowModelType = this.rowModel.getType();
var modelsForKeep = [Constants.ROW_MODEL_TYPE_SERVER_SIDE, Constants.ROW_MODEL_TYPE_INFINITE];
this.newRowsActionKeep = modelsForKeep.indexOf(rowModelType) >= 0;
}
_.setDisplayed(this.eApplyButton, this.applyActive);
// we do not bind onBtApply here because onBtApply() has a parameter, and it is not the event. if we
// just applied, the event would get passed as the second parameter, which we do not want.
this.addDestroyableEventListener(this.eApplyButton, "click", function () { return _this.onBtApply(); });
var clearActive = params.clearButton === true;
_.setDisplayed(this.eClearButton, clearActive);
this.addDestroyableEventListener(this.eClearButton, "click", function () { return _this.onBtClear(); });
var resetActive = params.resetButton === true;
_.setDisplayed(this.eResetButton, resetActive);
this.addDestroyableEventListener(this.eResetButton, "click", function () { return _this.onBtReset(); });
var anyButtonVisible = this.applyActive || clearActive || resetActive;
_.setDisplayed(this.eButtonsPanel, anyButtonVisible);
};
// subclasses can override this to provide alternative debounce defaults
ProvidedFilter.prototype.getDefaultDebounceMs = function () {
return 0;
};
ProvidedFilter.prototype.setupOnBtApplyDebounce = function () {
var debounceMs = ProvidedFilter.getDebounceMs(this.providedFilterParams, this.getDefaultDebounceMs());
this.onBtApplyDebounce = _.debounce(this.onBtApply.bind(this), debounceMs);
};
ProvidedFilter.prototype.getModel = function () {
return this.appliedModel;
};
ProvidedFilter.prototype.setModel = function (model) {
if (model) {
this.setModelIntoUi(model);
}
else {
this.resetUiToDefaults();
}
this.updateUiVisibility();
// we set the model from the gui, rather than the provided model,
// so the model is consistent. eg handling of null/undefined will be the same,
// of if model is case insensitive, then casing is removed.
this.applyModel();
};
ProvidedFilter.prototype.onBtClear = function () {
this.resetUiToDefaults();
this.updateUiVisibility();
this.onUiChanged();
};
ProvidedFilter.prototype.onBtReset = function () {
this.onBtClear();
this.onBtApply();
};
// returns true if the new model is different to the old model
ProvidedFilter.prototype.applyModel = function () {
var oldAppliedModel = this.appliedModel;
this.appliedModel = this.getModelFromUi();
// models can be same if user pasted same content into text field, or maybe just changed the case
// and it's a case insensitive filter
var newModelDifferent = !this.areModelsEqual(this.appliedModel, oldAppliedModel);
return newModelDifferent;
};
ProvidedFilter.prototype.onBtApply = function (afterFloatingFilter) {
if (afterFloatingFilter === void 0) { afterFloatingFilter = false; }
var newModelDifferent = this.applyModel();
if (newModelDifferent) {
// the floating filter uses 'afterFloatingFilter' info, so it doesn't refresh after filter changed if change
// came from floating filter
this.providedFilterParams.filterChangedCallback({ afterFloatingFilter: afterFloatingFilter });
}
};
ProvidedFilter.prototype.onNewRowsLoaded = function () {
if (!this.newRowsActionKeep) {
this.resetUiToDefaults();
this.appliedModel = null;
}
};
// called by set filter
ProvidedFilter.prototype.isNewRowsActionKeep = function () {
return this.newRowsActionKeep;
};
ProvidedFilter.prototype.onUiChanged = function (afterFloatingFilter) {
if (afterFloatingFilter === void 0) { afterFloatingFilter = false; }
this.updateUiVisibility();
this.providedFilterParams.filterModifiedCallback();
// applyNow=true for floating filter changes, we always act on these immediately
if (afterFloatingFilter) {
this.onBtApply(true);
// otherwise if no apply button, we apply (but debounce for time delay)
}
else if (!this.applyActive) {
this.onBtApplyDebounce();
}
};
ProvidedFilter.prototype.createTemplate = function () {
var body = this.createBodyTemplate();
var translate = this.gridOptionsWrapper.getLocaleTextFunc();
return "
\n
" + body + "
\n
\n \n \n \n
\n
";
};
// static, as used by floating filter also
ProvidedFilter.getDebounceMs = function (params, debounceDefault) {
var applyActive = ProvidedFilter.isUseApplyButton(params);
if (applyActive) {
if (params.debounceMs != null) {
console.warn('ag-Grid: debounceMs is ignored when applyButton = true');
}
return 0;
}
return params.debounceMs != null ? params.debounceMs : debounceDefault;
};
// static, as used by floating filter also
ProvidedFilter.isUseApplyButton = function (params) {
if (params.apply && !params.applyButton) {
console.warn('ag-Grid: as of ag-Grid v21, filterParams.apply is now filterParams.applyButton, please change to applyButton');
params.applyButton = true;
}
return params.applyButton === true;
};
ProvidedFilter.NEW_ROWS_ACTION_KEEP = 'keep';
ProvidedFilter.NEW_ROWS_ACTION_CLEAR = 'clear';
__decorate$a([
RefSelector('eButtonsPanel')
], ProvidedFilter.prototype, "eButtonsPanel", void 0);
__decorate$a([
RefSelector('eFilterBodyWrapper')
], ProvidedFilter.prototype, "eFilterBodyWrapper", void 0);
__decorate$a([
RefSelector('eClearButton')
], ProvidedFilter.prototype, "eClearButton", void 0);
__decorate$a([
RefSelector('eResetButton')
], ProvidedFilter.prototype, "eResetButton", void 0);
__decorate$a([
RefSelector('eApplyButton')
], ProvidedFilter.prototype, "eApplyButton", void 0);
__decorate$a([
Autowired('gridOptionsWrapper')
], ProvidedFilter.prototype, "gridOptionsWrapper", void 0);
__decorate$a([
Autowired('rowModel')
], ProvidedFilter.prototype, "rowModel", void 0);
__decorate$a([
PostConstruct
], ProvidedFilter.prototype, "postConstruct", null);
return ProvidedFilter;
}(Component));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends$4 = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate$b = (undefined && undefined.__decorate) || function (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;
};
var ConditionPosition;
(function (ConditionPosition) {
ConditionPosition[ConditionPosition["One"] = 0] = "One";
ConditionPosition[ConditionPosition["Two"] = 1] = "Two";
})(ConditionPosition || (ConditionPosition = {}));
var DEFAULT_TRANSLATIONS = {
loadingOoo: 'Loading...',
empty: 'Choose One',
equals: 'Equals',
notEqual: 'Not equal',
lessThan: 'Less than',
greaterThan: 'Greater than',
inRange: 'In range',
lessThanOrEqual: 'Less than or equals',
greaterThanOrEqual: 'Greater than or equals',
filterOoo: 'Filter...',
contains: 'Contains',
notContains: 'Not contains',
startsWith: 'Starts with',
endsWith: 'Ends with',
searchOoo: 'Search...',
selectAll: 'Select All',
applyFilter: 'Apply Filter',
clearFilter: 'Clear Filter',
andCondition: 'AND',
orCondition: 'OR'
};
/**
* Every filter with a dropdown where the user can specify a comparing type against the filter values
*/
var SimpleFilter = /** @class */ (function (_super) {
__extends$4(SimpleFilter, _super);
function SimpleFilter() {
return _super !== null && _super.apply(this, arguments) || this;
}
// returns true if this type requires a 'from' field, eg any filter that requires at least one text value
SimpleFilter.prototype.showValueFrom = function (type) {
return !this.doesFilterHaveHiddenInput(type) && type !== SimpleFilter.EMPTY;
};
// returns true if this type requires a 'to' field, currently only 'range' returns true
SimpleFilter.prototype.showValueTo = function (type) {
return type === SimpleFilter.IN_RANGE;
};
// floating filter calls this when user applies filter from floating filter
SimpleFilter.prototype.onFloatingFilterChanged = function (type, value) {
this.setValueFromFloatingFilter(value);
this.setTypeFromFloatingFilter(type);
this.onUiChanged(true);
};
SimpleFilter.prototype.setTypeFromFloatingFilter = function (type) {
this.eType1.value = type;
this.eType2.value = null;
this.eJoinOperatorAnd.checked = true;
};
SimpleFilter.prototype.getModelFromUi = function () {
if (!this.isConditionUiComplete(ConditionPosition.One)) {
return null;
}
if (this.isAllowTwoConditions() && this.isConditionUiComplete(ConditionPosition.Two)) {
var res = {
filterType: this.getFilterType(),
operator: this.getJoinOperator(),
condition1: this.createCondition(ConditionPosition.One),
condition2: this.createCondition(ConditionPosition.Two)
};
return res;
}
else {
var res = this.createCondition(ConditionPosition.One);
return res;
}
};
SimpleFilter.prototype.getCondition1Type = function () {
return this.eType1.value;
};
SimpleFilter.prototype.getCondition2Type = function () {
return this.eType2.value;
};
SimpleFilter.prototype.getJoinOperator = function () {
return this.eJoinOperatorOr.checked ? 'OR' : 'AND';
};
SimpleFilter.prototype.areModelsEqual = function (a, b) {
// both are missing
if (!a && !b) {
return true;
}
// one is missing, other present
if ((!a && b) || (a && !b)) {
return false;
}
// one is combined, the other is not
var aIsSimple = !a.operator;
var bIsSimple = !b.operator;
var oneSimpleOneCombined = (!aIsSimple && bIsSimple) || (aIsSimple && !bIsSimple);
if (oneSimpleOneCombined) {
return false;
}
var res;
// otherwise both present, so compare
if (aIsSimple) {
var aSimple = a;
var bSimple = b;
res = this.areSimpleModelsEqual(aSimple, bSimple);
}
else {
var aCombined = a;
var bCombined = b;
res = aCombined.operator === bCombined.operator
&& this.areSimpleModelsEqual(aCombined.condition1, bCombined.condition1)
&& this.areSimpleModelsEqual(aCombined.condition2, bCombined.condition2);
}
return res;
};
SimpleFilter.prototype.setModelIntoUi = function (model) {
var isCombined = model.operator;
if (isCombined) {
var combinedModel = model;
var orChecked = combinedModel.operator === 'OR';
this.eJoinOperatorAnd.checked = !orChecked;
this.eJoinOperatorOr.checked = orChecked;
this.eType1.value = combinedModel.condition1.type;
this.eType2.value = combinedModel.condition2.type;
this.setConditionIntoUi(combinedModel.condition1, ConditionPosition.One);
this.setConditionIntoUi(combinedModel.condition2, ConditionPosition.Two);
}
else {
var simpleModel = model;
this.eJoinOperatorAnd.checked = true;
this.eJoinOperatorOr.checked = false;
this.eType1.value = simpleModel.type;
this.eType2.value = this.optionsFactory.getDefaultOption();
this.setConditionIntoUi(simpleModel, ConditionPosition.One);
this.setConditionIntoUi(null, ConditionPosition.Two);
}
};
SimpleFilter.prototype.doesFilterPass = function (params) {
var model = this.getModel();
var isCombined = model.operator;
if (isCombined) {
var combinedModel = model;
var firstResult = this.individualConditionPasses(params, combinedModel.condition1);
var secondResult = this.individualConditionPasses(params, combinedModel.condition2);
if (combinedModel.operator === 'AND') {
return firstResult && secondResult;
}
else {
return firstResult || secondResult;
}
}
else {
var simpleModel = model;
var result = this.individualConditionPasses(params, simpleModel);
return result;
}
};
SimpleFilter.prototype.setParams = function (params) {
_super.prototype.setParams.call(this, params);
this.simpleFilterParams = params;
this.optionsFactory = new OptionsFactory();
this.optionsFactory.init(params, this.getDefaultFilterOptions());
this.allowTwoConditions = !params.suppressAndOrCondition;
this.putOptionsIntoDropdown();
this.addChangedListeners();
};
SimpleFilter.prototype.putOptionsIntoDropdown = function () {
var _this = this;
var filterOptions = this.optionsFactory.getFilterOptions();
filterOptions.forEach(function (option) {
var createOption = function () {
var key = (typeof option === 'string') ? option : option.displayKey;
var localName = _this.translate(key);
var eOption = document.createElement("option");
eOption.text = localName;
eOption.value = key;
return eOption;
};
_this.eType1.add(createOption());
_this.eType2.add(createOption());
});
var readOnly = filterOptions.length <= 1;
this.eType1.disabled = readOnly;
this.eType2.disabled = readOnly;
};
SimpleFilter.prototype.isAllowTwoConditions = function () {
return this.allowTwoConditions;
};
SimpleFilter.prototype.createBodyTemplate = function () {
var optionsTemplate1 = "";
var valueTemplate1 = this.createValueTemplate(ConditionPosition.One);
var optionsTemplate2 = "";
var valueTemplate2 = this.createValueTemplate(ConditionPosition.Two);
var uniqueGroupId = 'ag-simple-filter-and-or-' + this.getCompId();
var translate = this.gridOptionsWrapper.getLocaleTextFunc();
var andOrTemplate = "
\n \n \n
";
var template = optionsTemplate1 + "\n " + valueTemplate1 + "\n " + andOrTemplate + "\n " + optionsTemplate2 + "\n " + valueTemplate2;
return template;
};
SimpleFilter.prototype.updateUiVisibility = function () {
var firstConditionComplete = this.isConditionUiComplete(ConditionPosition.One);
var showSecondFilter = this.allowTwoConditions && firstConditionComplete;
_.setDisplayed(this.eCondition2Body, showSecondFilter);
_.setDisplayed(this.eType2, showSecondFilter);
_.setDisplayed(this.eJoinOperatorPanel, showSecondFilter);
};
SimpleFilter.prototype.resetUiToDefaults = function () {
this.eJoinOperatorAnd.checked = true;
var defaultOption = this.optionsFactory.getDefaultOption();
this.eType1.value = defaultOption;
this.eType2.value = defaultOption;
};
SimpleFilter.prototype.translate = function (toTranslate) {
var translate = this.gridOptionsWrapper.getLocaleTextFunc();
var defaultTranslation = DEFAULT_TRANSLATIONS[toTranslate];
if (!defaultTranslation && this.optionsFactory.getCustomOption(toTranslate)) {
defaultTranslation = this.optionsFactory.getCustomOption(toTranslate).displayName;
}
return translate(toTranslate, defaultTranslation);
};
SimpleFilter.prototype.addChangedListeners = function () {
var _this = this;
var listener = function () { return _this.onUiChanged(); };
this.addDestroyableEventListener(this.eType1, "change", listener);
this.addDestroyableEventListener(this.eType2, "change", listener);
this.addDestroyableEventListener(this.eJoinOperatorOr, "change", listener);
this.addDestroyableEventListener(this.eJoinOperatorAnd, "change", listener);
};
SimpleFilter.prototype.doesFilterHaveHiddenInput = function (filterType) {
var customFilterOption = this.optionsFactory.getCustomOption(filterType);
return customFilterOption && customFilterOption.hideFilterInput;
};
SimpleFilter.EMPTY = 'empty';
SimpleFilter.EQUALS = 'equals';
SimpleFilter.NOT_EQUAL = 'notEqual';
SimpleFilter.LESS_THAN = 'lessThan';
SimpleFilter.LESS_THAN_OR_EQUAL = 'lessThanOrEqual';
SimpleFilter.GREATER_THAN = 'greaterThan';
SimpleFilter.GREATER_THAN_OR_EQUAL = 'greaterThanOrEqual';
SimpleFilter.IN_RANGE = 'inRange';
SimpleFilter.CONTAINS = 'contains';
SimpleFilter.NOT_CONTAINS = 'notContains';
SimpleFilter.STARTS_WITH = 'startsWith';
SimpleFilter.ENDS_WITH = 'endsWith';
__decorate$b([
RefSelector('eOptions1')
], SimpleFilter.prototype, "eType1", void 0);
__decorate$b([
RefSelector('eOptions2')
], SimpleFilter.prototype, "eType2", void 0);
__decorate$b([
RefSelector('eJoinOperatorAnd')
], SimpleFilter.prototype, "eJoinOperatorAnd", void 0);
__decorate$b([
RefSelector('eJoinOperatorOr')
], SimpleFilter.prototype, "eJoinOperatorOr", void 0);
__decorate$b([
RefSelector('eCondition2Body')
], SimpleFilter.prototype, "eCondition2Body", void 0);
__decorate$b([
RefSelector('eJoinOperatorPanel')
], SimpleFilter.prototype, "eJoinOperatorPanel", void 0);
return SimpleFilter;
}(ProvidedFilter));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends$5 = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var ScalerFilter = /** @class */ (function (_super) {
__extends$5(ScalerFilter, _super);
function ScalerFilter() {
return _super !== null && _super.apply(this, arguments) || this;
}
ScalerFilter.prototype.setParams = function (params) {
_super.prototype.setParams.call(this, params);
this.scalarFilterParams = params;
this.checkDeprecatedParams();
};
ScalerFilter.prototype.checkDeprecatedParams = function () {
if (this.scalarFilterParams.nullComparator) {
console.warn('ag-Grid: Since v21.0, the property filterParams.nullComparator is deprecated. ' +
'Please use filterParams.includeBlanksInEquals, filterParams.includeBlanksInLessThan and ' +
'filterParams.includeBlanksInGreaterThan instead.');
this.scalarFilterParams.includeBlanksInEquals = this.scalarFilterParams.nullComparator.equals;
this.scalarFilterParams.includeBlanksInLessThan = this.scalarFilterParams.nullComparator.lessThan;
this.scalarFilterParams.includeBlanksInGreaterThan = this.scalarFilterParams.nullComparator.greaterThan;
}
};
ScalerFilter.prototype.nullComparator = function (selectedOption, filterValue, gridValue) {
if (gridValue == null) {
var nullValue = this.canNullsPassFilter(selectedOption);
if (selectedOption === ScalerFilter.EMPTY) {
return 0;
}
if (selectedOption === ScalerFilter.EQUALS) {
return nullValue ? 0 : 1;
}
if (selectedOption === ScalerFilter.GREATER_THAN) {
return nullValue ? 1 : -1;
}
if (selectedOption === ScalerFilter.GREATER_THAN_OR_EQUAL) {
return nullValue ? 1 : -1;
}
if (selectedOption === ScalerFilter.LESS_THAN_OR_EQUAL) {
return nullValue ? -1 : 1;
}
if (selectedOption === ScalerFilter.LESS_THAN) {
return nullValue ? -1 : 1;
}
if (selectedOption === ScalerFilter.NOT_EQUAL) {
return nullValue ? 1 : 0;
}
}
var actualComparator = this.comparator();
return actualComparator(filterValue, gridValue);
};
ScalerFilter.prototype.canNullsPassFilter = function (type) {
switch (type) {
case SimpleFilter.GREATER_THAN:
case SimpleFilter.GREATER_THAN_OR_EQUAL:
return this.scalarFilterParams.includeBlanksInGreaterThan;
case SimpleFilter.LESS_THAN:
case SimpleFilter.LESS_THAN_OR_EQUAL:
return this.scalarFilterParams.includeBlanksInLessThan;
case SimpleFilter.EQUALS:
return this.scalarFilterParams.includeBlanksInEquals;
}
};
ScalerFilter.prototype.individualConditionPasses = function (params, filterModel) {
var cellValue = this.scalarFilterParams.valueGetter(params.node);
var range = this.mapRangeFromModel(filterModel);
var filterValue = range.from;
var filterValueTo = range.to;
var filterType = filterModel.type;
var customFilterOption = this.optionsFactory.getCustomOption(filterType);
if (customFilterOption) {
// only execute the custom filter if a value exists or a value isn't required, i.e. input is hidden
if (filterValue != null || customFilterOption.hideFilterInput) {
return customFilterOption.test(filterValue, cellValue);
}
}
// why this? looks like logic that should be in parent class????
// if (filterValue == null) {
// return type === FilterConditionType.MAIN ? true : this.conditionValue === 'AND';
// }
var compareResult = this.nullComparator(filterType, filterValue, cellValue);
if (filterType === ScalerFilter.EQUALS) {
return compareResult === 0;
}
if (filterType === ScalerFilter.GREATER_THAN) {
return compareResult > 0;
}
if (filterType === ScalerFilter.GREATER_THAN_OR_EQUAL) {
return compareResult >= 0;
}
if (filterType === ScalerFilter.LESS_THAN_OR_EQUAL) {
return compareResult <= 0;
}
if (filterType === ScalerFilter.LESS_THAN) {
return compareResult < 0;
}
if (filterType === ScalerFilter.NOT_EQUAL) {
return compareResult != 0;
}
// From now on the type is a range and rawFilterValues must be an array!
var compareToResult = this.nullComparator(filterType, filterValueTo, cellValue);
if (filterType === ScalerFilter.IN_RANGE) {
if (!this.scalarFilterParams.inRangeInclusive) {
return compareResult > 0 && compareToResult < 0;
}
else {
return compareResult >= 0 && compareToResult <= 0;
}
}
throw new Error('Unexpected type of filter: ' + filterType);
};
ScalerFilter.DEFAULT_NULL_COMPARATOR = {
equals: false,
lessThan: false,
greaterThan: false
};
return ScalerFilter;
}(SimpleFilter));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends$6 = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate$c = (undefined && undefined.__decorate) || function (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;
};
var DateFilter = /** @class */ (function (_super) {
__extends$6(DateFilter, _super);
function DateFilter() {
return _super !== null && _super.apply(this, arguments) || this;
}
DateFilter.prototype.mapRangeFromModel = function (filterModel) {
// unlike the other filters, we do two things here:
// 1) allow for different attribute names (same as done for other filters) (eg the 'from' and 'to'
// are in different locations in Date and Number filter models)
// 2) convert the type (cos Date filter uses Dates, however model is 'string')
//
// NOTE: The conversion of string to date also removes the timezone - ie when user picks
// a date form the UI, it will have timezone info in it. This is lost when creating
// the model. Then when we recreate the date again here, it's without timezone.
return {
from: _.parseYyyyMmDdToDate(filterModel.dateFrom, "-"),
to: _.parseYyyyMmDdToDate(filterModel.dateTo, "-")
};
};
DateFilter.prototype.setValueFromFloatingFilter = function (value) {
if (value != null) {
var dateFrom = _.parseYyyyMmDdToDate(value, "-");
this.dateCompFrom1.setDate(dateFrom);
}
else {
this.dateCompFrom1.setDate(null);
}
this.dateCompTo1.setDate(null);
this.dateCompFrom2.setDate(null);
this.dateCompTo2.setDate(null);
};
DateFilter.prototype.setConditionIntoUi = function (model, position) {
var positionOne = position === ConditionPosition.One;
var dateFromString = model ? model.dateFrom : null;
var dateToString = model ? model.dateTo : null;
var dateFrom = _.parseYyyyMmDdToDate(dateFromString, "-");
var dateTo = _.parseYyyyMmDdToDate(dateToString, "-");
var compFrom = positionOne ? this.dateCompFrom1 : this.dateCompFrom2;
var compTo = positionOne ? this.dateCompTo1 : this.dateCompTo2;
compFrom.setDate(dateFrom);
compTo.setDate(dateTo);
};
DateFilter.prototype.resetUiToDefaults = function () {
_super.prototype.resetUiToDefaults.call(this);
this.dateCompTo1.setDate(null);
this.dateCompTo2.setDate(null);
this.dateCompFrom1.setDate(null);
this.dateCompFrom2.setDate(null);
};
DateFilter.prototype.comparator = function () {
return this.dateFilterParams.comparator ? this.dateFilterParams.comparator : this.defaultComparator.bind(this);
};
DateFilter.prototype.defaultComparator = function (filterDate, cellValue) {
//The default comparator assumes that the cellValue is a date
var cellAsDate = cellValue;
if (cellAsDate < filterDate) {
return -1;
}
if (cellAsDate > filterDate) {
return 1;
}
return cellValue != null ? 0 : -1;
};
DateFilter.prototype.setParams = function (params) {
_super.prototype.setParams.call(this, params);
this.dateFilterParams = params;
this.createDateComponents();
};
DateFilter.prototype.createDateComponents = function () {
var _this = this;
// params to pass to all four date comps
var dateComponentParams = {
onDateChanged: function () { return _this.onUiChanged(); },
filterParams: this.dateFilterParams
};
this.dateCompFrom1 = new DateCompWrapper(this.userComponentFactory, dateComponentParams, this.ePanelFrom1);
this.dateCompFrom2 = new DateCompWrapper(this.userComponentFactory, dateComponentParams, this.ePanelFrom2);
this.dateCompTo1 = new DateCompWrapper(this.userComponentFactory, dateComponentParams, this.ePanelTo1);
this.dateCompTo2 = new DateCompWrapper(this.userComponentFactory, dateComponentParams, this.ePanelTo2);
this.addDestroyFunc(function () {
_this.dateCompFrom1.destroy();
_this.dateCompFrom2.destroy();
_this.dateCompTo1.destroy();
_this.dateCompTo2.destroy();
});
};
DateFilter.prototype.getDefaultFilterOptions = function () {
return DateFilter.DEFAULT_FILTER_OPTIONS;
};
DateFilter.prototype.createValueTemplate = function (position) {
var positionOne = position === ConditionPosition.One;
var pos = positionOne ? '1' : '2';
return "
\n
\n
\n
\n
\n
";
};
DateFilter.prototype.isConditionUiComplete = function (position) {
var positionOne = position === ConditionPosition.One;
var option = positionOne ? this.getCondition1Type() : this.getCondition2Type();
var compFrom = positionOne ? this.dateCompFrom1 : this.dateCompFrom2;
var compTo = positionOne ? this.dateCompTo1 : this.dateCompTo2;
var valueFrom = compFrom.getDate();
var valueTo = compTo.getDate();
if (option === SimpleFilter.EMPTY) {
return false;
}
if (this.doesFilterHaveHiddenInput(option)) {
return true;
}
if (option === SimpleFilter.IN_RANGE) {
return valueFrom != null && valueTo != null;
}
else {
return valueFrom != null;
}
};
DateFilter.prototype.areSimpleModelsEqual = function (aSimple, bSimple) {
return aSimple.dateFrom === bSimple.dateFrom
&& aSimple.dateTo === bSimple.dateTo
&& aSimple.type === bSimple.type;
};
// needed for creating filter model
DateFilter.prototype.getFilterType = function () {
return DateFilter.FILTER_TYPE;
};
DateFilter.prototype.createCondition = function (position) {
var positionOne = position === ConditionPosition.One;
var type = positionOne ? this.getCondition1Type() : this.getCondition2Type();
var dateCompTo = positionOne ? this.dateCompTo1 : this.dateCompTo2;
var dateCompFrom = positionOne ? this.dateCompFrom1 : this.dateCompFrom2;
return {
dateTo: _.serializeDateToYyyyMmDd(dateCompTo.getDate(), "-"),
dateFrom: _.serializeDateToYyyyMmDd(dateCompFrom.getDate(), "-"),
type: type,
filterType: DateFilter.FILTER_TYPE
};
};
DateFilter.prototype.updateUiVisibility = function () {
_super.prototype.updateUiVisibility.call(this);
var showFrom1 = this.showValueFrom(this.getCondition1Type());
_.setDisplayed(this.ePanelFrom1, showFrom1);
var showTo1 = this.showValueTo(this.getCondition1Type());
_.setDisplayed(this.ePanelTo1, showTo1);
var showFrom2 = this.showValueFrom(this.getCondition2Type());
_.setDisplayed(this.ePanelFrom2, showFrom2);
var showTo2 = this.showValueTo(this.getCondition2Type());
_.setDisplayed(this.ePanelTo2, showTo2);
};
DateFilter.FILTER_TYPE = 'date';
DateFilter.DEFAULT_FILTER_OPTIONS = [ScalerFilter.EQUALS, ScalerFilter.GREATER_THAN,
ScalerFilter.LESS_THAN, ScalerFilter.NOT_EQUAL, ScalerFilter.IN_RANGE];
__decorate$c([
RefSelector('ePanelFrom1')
], DateFilter.prototype, "ePanelFrom1", void 0);
__decorate$c([
RefSelector('ePanelFrom2')
], DateFilter.prototype, "ePanelFrom2", void 0);
__decorate$c([
RefSelector('ePanelTo1')
], DateFilter.prototype, "ePanelTo1", void 0);
__decorate$c([
RefSelector('ePanelTo2')
], DateFilter.prototype, "ePanelTo2", void 0);
__decorate$c([
Autowired('userComponentFactory')
], DateFilter.prototype, "userComponentFactory", void 0);
return DateFilter;
}(ScalerFilter));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var TouchListener = /** @class */ (function () {
function TouchListener(eElement, preventMouseClick) {
var _this = this;
if (preventMouseClick === void 0) { preventMouseClick = false; }
this.destroyFuncs = [];
this.touching = false;
this.eventService = new EventService();
this.eElement = eElement;
this.preventMouseClick = preventMouseClick;
var startListener = this.onTouchStart.bind(this);
var moveListener = this.onTouchMove.bind(this);
var endListener = this.onTouchEnd.bind(this);
this.eElement.addEventListener("touchstart", startListener, { passive: true });
this.eElement.addEventListener("touchmove", moveListener, { passive: true });
// we set passive=false, as we want to prevent default on this event
this.eElement.addEventListener("touchend", endListener, { passive: false });
this.destroyFuncs.push(function () {
_this.eElement.removeEventListener("touchstart", startListener, { passive: true });
_this.eElement.removeEventListener("touchmove", moveListener, { passive: true });
_this.eElement.removeEventListener("touchend", endListener, { passive: false });
});
}
TouchListener.prototype.getActiveTouch = function (touchList) {
for (var i = 0; i < touchList.length; i++) {
var matches = touchList[i].identifier === this.touchStart.identifier;
if (matches) {
return touchList[i];
}
}
return null;
};
TouchListener.prototype.addEventListener = function (eventType, listener) {
this.eventService.addEventListener(eventType, listener);
};
TouchListener.prototype.removeEventListener = function (eventType, listener) {
this.eventService.removeEventListener(eventType, listener);
};
TouchListener.prototype.onTouchStart = function (touchEvent) {
var _this = this;
// only looking at one touch point at any time
if (this.touching) {
return;
}
this.touchStart = touchEvent.touches[0];
this.touching = true;
this.moved = false;
var touchStartCopy = this.touchStart;
window.setTimeout(function () {
var touchesMatch = _this.touchStart === touchStartCopy;
if (_this.touching && touchesMatch && !_this.moved) {
_this.moved = true;
var event_1 = {
type: TouchListener.EVENT_LONG_TAP,
touchStart: _this.touchStart,
touchEvent: touchEvent
};
_this.eventService.dispatchEvent(event_1);
}
}, 500);
};
TouchListener.prototype.onTouchMove = function (touchEvent) {
if (!this.touching) {
return;
}
var touch = this.getActiveTouch(touchEvent.touches);
if (!touch) {
return;
}
var eventIsFarAway = !_.areEventsNear(touch, this.touchStart, 4);
if (eventIsFarAway) {
this.moved = true;
}
};
TouchListener.prototype.onTouchEnd = function (touchEvent) {
if (!this.touching) {
return;
}
if (!this.moved) {
var event_2 = {
type: TouchListener.EVENT_TAP,
touchStart: this.touchStart
};
this.eventService.dispatchEvent(event_2);
this.checkForDoubleTap();
}
// stops the tap from also been processed as a mouse click
if (this.preventMouseClick) {
touchEvent.preventDefault();
}
this.touching = false;
};
TouchListener.prototype.checkForDoubleTap = function () {
var now = new Date().getTime();
if (this.lastTapTime && this.lastTapTime > 0) {
// if previous tap, see if duration is short enough to be considered double tap
var interval = now - this.lastTapTime;
if (interval > TouchListener.DOUBLE_TAP_MILLIS) {
// dispatch double tap event
var event_3 = {
type: TouchListener.EVENT_DOUBLE_TAP,
touchStart: this.touchStart
};
this.eventService.dispatchEvent(event_3);
// this stops a tripple tap ending up as two double taps
this.lastTapTime = null;
}
else {
this.lastTapTime = now;
}
}
else {
this.lastTapTime = now;
}
};
TouchListener.prototype.destroy = function () {
this.destroyFuncs.forEach(function (func) { return func(); });
};
TouchListener.EVENT_TAP = "tap";
TouchListener.EVENT_DOUBLE_TAP = "doubleTap";
TouchListener.EVENT_LONG_TAP = "longTap";
TouchListener.DOUBLE_TAP_MILLIS = 500;
return TouchListener;
}());
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends$7 = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate$d = (undefined && undefined.__decorate) || function (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;
};
var HeaderComp = /** @class */ (function (_super) {
__extends$7(HeaderComp, _super);
function HeaderComp() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.lastMovingChanged = 0;
return _this;
}
HeaderComp.prototype.init = function (params) {
var template = _.firstExistingValue(params.template, HeaderComp.TEMPLATE);
// take account of any newlines & whitespace before/after the actual template
template = template && template.trim ? template.trim() : template;
this.setTemplate(template);
this.params = params;
this.setupTap();
this.setupIcons(params.column);
this.setupMenu();
this.setupSort();
this.setupFilterIcon();
this.setupText(params.displayName);
};
HeaderComp.prototype.setupText = function (displayName) {
var displayNameSanitised = _.escape(displayName);
if (this.eText) {
this.eText.innerHTML = displayNameSanitised;
}
};
HeaderComp.prototype.setupIcons = function (column) {
this.addInIcon('sortAscending', this.eSortAsc, column);
this.addInIcon('sortDescending', this.eSortDesc, column);
this.addInIcon('sortUnSort', this.eSortNone, column);
this.addInIcon('menu', this.eMenu, column);
this.addInIcon('filter', this.eFilter, column);
};
HeaderComp.prototype.addInIcon = function (iconName, eParent, column) {
if (eParent == null) {
return;
}
var eIcon = _.createIconNoSpan(iconName, this.gridOptionsWrapper, column);
eParent.appendChild(eIcon);
};
HeaderComp.prototype.setupTap = function () {
var _this = this;
var options = this.gridOptionsWrapper;
if (options.isSuppressTouch()) {
return;
}
var touchListener = new TouchListener(this.getGui(), true);
var suppressMenuHide = options.isSuppressMenuHide();
var tapMenuButton = suppressMenuHide && _.exists(this.eMenu);
var menuTouchListener = tapMenuButton ? new TouchListener(this.eMenu, true) : touchListener;
if (this.params.enableMenu) {
var eventType = tapMenuButton ? 'EVENT_TAP' : 'EVENT_LONG_TAP';
var showMenuFn = function (event) {
options.getApi().showColumnMenuAfterMouseClick(_this.params.column, event.touchStart);
};
this.addDestroyableEventListener(menuTouchListener, TouchListener[eventType], showMenuFn);
}
if (this.params.enableSorting) {
var tapListener = function (event) {
var target = event.touchStart.target;
// When suppressMenuHide is true, a tap on the menu icon will bubble up
// to the header container, in that case we should not sort
if (suppressMenuHide && _this.eMenu.contains(target)) {
return;
}
_this.sortController.progressSort(_this.params.column, false, "uiColumnSorted");
};
this.addDestroyableEventListener(touchListener, TouchListener.EVENT_TAP, tapListener);
}
// if tapMenuButton is true `touchListener` and `menuTouchListener` are different
// so we need to make sure to destroy both listeners here
this.addDestroyFunc(function () { return touchListener.destroy(); });
if (tapMenuButton) {
this.addDestroyFunc(function () { return menuTouchListener.destroy(); });
}
};
HeaderComp.prototype.setupMenu = function () {
var _this = this;
// if no menu provided in template, do nothing
if (!this.eMenu) {
return;
}
// we don't show the menu if on an iPad/iPhone, as the user cannot have a pointer device
// Note: If suppressMenuHide is set to true the menu will be displayed, and if suppressMenuHide
// is false (default) user will need to use longpress to display the menu.
var suppressMenuHide = this.gridOptionsWrapper.isSuppressMenuHide();
var hideShowMenu = !this.params.enableMenu || (_.isIOSUserAgent() && !suppressMenuHide);
if (hideShowMenu) {
_.removeFromParent(this.eMenu);
return;
}
this.addDestroyableEventListener(this.eMenu, 'click', function () { return _this.showMenu(_this.eMenu); });
if (!suppressMenuHide) {
this.eMenu.style.opacity = '0';
this.addGuiEventListener('mouseover', function () {
_this.eMenu.style.opacity = '1';
});
this.addGuiEventListener('mouseout', function () {
_this.eMenu.style.opacity = '0';
});
}
var style = this.eMenu.style;
style.transition = 'opacity 0.2s, border 0.2s';
style['-webkit-transition'] = 'opacity 0.2s, border 0.2s';
};
HeaderComp.prototype.showMenu = function (eventSource) {
this.menuFactory.showMenuAfterButtonClick(this.params.column, eventSource);
};
HeaderComp.prototype.removeSortIcons = function () {
_.removeFromParent(this.eSortAsc);
_.removeFromParent(this.eSortDesc);
_.removeFromParent(this.eSortNone);
_.removeFromParent(this.eSortOrder);
};
HeaderComp.prototype.setupSort = function () {
var _this = this;
var enableSorting = this.params.enableSorting;
if (!enableSorting) {
this.removeSortIcons();
return;
}
var sortUsingCtrl = this.gridOptionsWrapper.isMultiSortKeyCtrl();
// keep track of last time the moving changed flag was set
this.addDestroyableEventListener(this.params.column, Column.EVENT_MOVING_CHANGED, function () {
_this.lastMovingChanged = new Date().getTime();
});
// add the event on the header, so when clicked, we do sorting
if (this.eLabel) {
this.addDestroyableEventListener(this.eLabel, 'click', function (event) {
// sometimes when moving a column via dragging, this was also firing a clicked event.
// here is issue raised by user: https://ag-grid.zendesk.com/agent/tickets/1076
// this check stops sort if a) column is moving or b) column moved less than 200ms ago (so caters for race condition)
var moving = _this.params.column.isMoving();
var nowTime = new Date().getTime();
// typically there is <2ms if moving flag was set recently, as it would be done in same VM turn
var movedRecently = (nowTime - _this.lastMovingChanged) < 50;
var columnMoving = moving || movedRecently;
if (!columnMoving) {
var multiSort = sortUsingCtrl ? (event.ctrlKey || event.metaKey) : event.shiftKey;
_this.params.progressSort(multiSort);
}
});
}
this.addDestroyableEventListener(this.params.column, Column.EVENT_SORT_CHANGED, this.onSortChanged.bind(this));
this.onSortChanged();
this.addDestroyableEventListener(this.eventService, Events.EVENT_SORT_CHANGED, this.setMultiSortOrder.bind(this));
this.setMultiSortOrder();
};
HeaderComp.prototype.onSortChanged = function () {
_.addOrRemoveCssClass(this.getGui(), 'ag-header-cell-sorted-asc', this.params.column.isSortAscending());
_.addOrRemoveCssClass(this.getGui(), 'ag-header-cell-sorted-desc', this.params.column.isSortDescending());
_.addOrRemoveCssClass(this.getGui(), 'ag-header-cell-sorted-none', this.params.column.isSortNone());
if (this.eSortAsc) {
_.addOrRemoveCssClass(this.eSortAsc, 'ag-hidden', !this.params.column.isSortAscending());
}
if (this.eSortDesc) {
_.addOrRemoveCssClass(this.eSortDesc, 'ag-hidden', !this.params.column.isSortDescending());
}
if (this.eSortNone) {
var alwaysHideNoSort = !this.params.column.getColDef().unSortIcon && !this.gridOptionsWrapper.isUnSortIcon();
_.addOrRemoveCssClass(this.eSortNone, 'ag-hidden', alwaysHideNoSort || !this.params.column.isSortNone());
}
};
// we listen here for global sort events, NOT column sort events, as we want to do this
// when sorting has been set on all column (if we listened just for our col (where we
// set the asc / desc icons) then it's possible other cols are yet to get their sorting state.
HeaderComp.prototype.setMultiSortOrder = function () {
if (!this.eSortOrder) {
return;
}
var col = this.params.column;
var allColumnsWithSorting = this.sortController.getColumnsWithSortingOrdered();
var indexThisCol = allColumnsWithSorting.indexOf(col);
var moreThanOneColSorting = allColumnsWithSorting.length > 1;
var showIndex = col.isSorting() && moreThanOneColSorting;
_.setDisplayed(this.eSortOrder, showIndex);
if (indexThisCol >= 0) {
this.eSortOrder.innerHTML = (indexThisCol + 1).toString();
}
else {
_.clearElement(this.eSortOrder);
}
};
HeaderComp.prototype.setupFilterIcon = function () {
if (!this.eFilter) {
return;
}
this.addDestroyableEventListener(this.params.column, Column.EVENT_FILTER_CHANGED, this.onFilterChanged.bind(this));
this.onFilterChanged();
};
HeaderComp.prototype.onFilterChanged = function () {
var filterPresent = this.params.column.isFilterActive();
_.addOrRemoveCssClass(this.eFilter, 'ag-hidden', !filterPresent);
};
HeaderComp.TEMPLATE = '
' +
' ' +
'
' +
' ' +
' ' +
' ' +
' ' +
' ' +
' ' +
'
' +
'
';
__decorate$d([
Autowired('gridOptionsWrapper')
], HeaderComp.prototype, "gridOptionsWrapper", void 0);
__decorate$d([
Autowired('sortController')
], HeaderComp.prototype, "sortController", void 0);
__decorate$d([
Autowired('menuFactory')
], HeaderComp.prototype, "menuFactory", void 0);
__decorate$d([
Autowired('eventService')
], HeaderComp.prototype, "eventService", void 0);
__decorate$d([
RefSelector('eFilter')
], HeaderComp.prototype, "eFilter", void 0);
__decorate$d([
RefSelector('eSortAsc')
], HeaderComp.prototype, "eSortAsc", void 0);
__decorate$d([
RefSelector('eSortDesc')
], HeaderComp.prototype, "eSortDesc", void 0);
__decorate$d([
RefSelector('eSortNone')
], HeaderComp.prototype, "eSortNone", void 0);
__decorate$d([
RefSelector('eSortOrder')
], HeaderComp.prototype, "eSortOrder", void 0);
__decorate$d([
RefSelector('eMenu')
], HeaderComp.prototype, "eMenu", void 0);
__decorate$d([
RefSelector('eLabel')
], HeaderComp.prototype, "eLabel", void 0);
__decorate$d([
RefSelector('eText')
], HeaderComp.prototype, "eText", void 0);
return HeaderComp;
}(Component));
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v22.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __extends$8 = (undefined && undefined.__extends) || (function () {
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);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate$e = (undefined && undefined.__decorate) || function (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;
};
var HeaderGroupComp = /** @class */ (function (_super) {
__extends$8(HeaderGroupComp, _super);
function HeaderGroupComp() {
return _super.call(this, HeaderGroupComp.TEMPLATE) || this;
}
HeaderGroupComp.prototype.init = function (params) {
this.params = params;
this.setupLabel();
this.addGroupExpandIcon();
this.setupExpandIcons();
};
HeaderGroupComp.prototype.setupExpandIcons = function () {
var _this = this;
this.addInIcon("columnGroupOpened", "agOpened");
this.addInIcon("columnGroupClosed", "agClosed");
var expandAction = function (event) {
if (_.isStopPropagationForAgGrid(event)) {
return;
}
var newExpandedValue = !_this.params.columnGroup.isExpanded();
_this.columnController.setColumnGroupOpened(_this.params.columnGroup.getOriginalColumnGroup(), newExpandedValue, "uiColumnExpanded");
};
this.addTouchAndClickListeners(this.eCloseIcon, expandAction);
this.addTouchAndClickListeners(this.eOpenIcon, expandAction);
var stopPropagationAction = function (event) {
_.stopPropagationForAgGrid(event);
};
// adding stopPropagation to the double click for the icons prevents double click action happening
// when the icons are clicked. if the icons are double clicked, then the groups should open and
// then close again straight away. if we also listened to double click, then the group would open,
// close, then open, which is not what we want. double click should only action if the user double
// clicks outside of the icons.
this.addDestroyableEventListener(this.eCloseIcon, "dblclick", stopPropagationAction);
this.addDestroyableEventListener(this.eOpenIcon, "dblclick", stopPropagationAction);
this.addDestroyableEventListener(this.getGui(), "dblclick", expandAction);
this.updateIconVisibility();
var originalColumnGroup = this.params.columnGroup.getOriginalColumnGroup();
this.addDestroyableEventListener(originalColumnGroup, OriginalColumnGroup.EVENT_EXPANDED_CHANGED, this.updateIconVisibility.bind(this));
this.addDestroyableEventListener(originalColumnGroup, OriginalColumnGroup.EVENT_EXPANDABLE_CHANGED, this.updateIconVisibility.bind(this));
};
HeaderGroupComp.prototype.addTouchAndClickListeners = function (eElement, action) {
var touchListener = new TouchListener(eElement);
this.addDestroyableEventListener(touchListener, TouchListener.EVENT_TAP, action);
this.addDestroyFunc(function () { return touchListener.destroy(); });
this.addDestroyableEventListener(eElement, "click", action);
};
HeaderGroupComp.prototype.updateIconVisibility = function () {
var columnGroup = this.params.columnGroup;
if (columnGroup.isExpandable()) {
var expanded = this.params.columnGroup.isExpanded();
_.setDisplayed(this.eOpenIcon, expanded);
_.setDisplayed(this.eCloseIcon, !expanded);
}
else {
_.setDisplayed(this.eOpenIcon, false);
_.setDisplayed(this.eCloseIcon, false);
}
};
HeaderGroupComp.prototype.addInIcon = function (iconName, refName) {
var eIcon = _.createIconNoSpan(iconName, this.gridOptionsWrapper, null);
this.getRefElement(refName).appendChild(eIcon);
};
HeaderGroupComp.prototype.addGroupExpandIcon = function () {
if (!this.params.columnGroup.isExpandable()) {
_.setDisplayed(this.eOpenIcon, false);
_.setDisplayed(this.eCloseIcon, false);
return;
}
};
HeaderGroupComp.prototype.setupLabel = function () {
// no renderer, default text render
if (this.params.displayName && this.params.displayName !== "") {
var eInnerText = this.getRefElement("agLabel");
eInnerText.innerHTML = this.params.displayName;
}
};
HeaderGroupComp.TEMPLATE = "