ag-grid-enterprise
Version:
Advanced Data Grid / Data Table supporting Javascript / Typescript / React / Angular / Vue
54,017 lines • 1.94 MB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// packages/ag-grid-enterprise/src/main.ts
var main_exports = {};
__export(main_exports, {
AdvancedFilterModule: () => AdvancedFilterModule,
AggregationModule: () => AggregationModule,
AllEnterpriseModule: () => AllEnterpriseModule,
BatchEditModule: () => BatchEditModule,
CellSelectionModule: () => CellSelectionModule,
ClipboardModule: () => ClipboardModule,
ColumnMenuModule: () => ColumnMenuModule,
ColumnsToolPanelModule: () => ColumnsToolPanelModule,
ContextMenuModule: () => ContextMenuModule,
ExcelExportModule: () => ExcelExportModule,
FiltersToolPanelModule: () => FiltersToolPanelModule,
FindModule: () => FindModule,
GridChartsModule: () => GridChartsModule,
GroupFilterModule: () => GroupFilterModule,
IntegratedChartsModule: () => IntegratedChartsModule,
LicenseManager: () => GridLicenseManager,
MasterDetailModule: () => MasterDetailModule,
MenuModule: () => MenuModule,
MultiFilterModule: () => MultiFilterModule,
NewFiltersToolPanelModule: () => NewFiltersToolPanelModule,
PivotModule: () => PivotModule,
RangeSelectionModule: () => RangeSelectionModule,
RichSelectModule: () => RichSelectModule,
RowGroupingModule: () => RowGroupingModule,
RowGroupingPanelModule: () => RowGroupingPanelModule,
RowNumbersModule: () => RowNumbersModule,
ServerSideRowModelApiModule: () => ServerSideRowModelApiModule,
ServerSideRowModelModule: () => ServerSideRowModelModule,
SetFilterModule: () => SetFilterModule,
SideBarModule: () => SideBarModule,
SparklinesModule: () => SparklinesModule,
StatusBarModule: () => StatusBarModule,
TreeDataModule: () => TreeDataModule,
ViewportRowModelModule: () => ViewportRowModelModule,
exportMultipleSheetsAsExcel: () => exportMultipleSheetsAsExcel,
getMultipleSheetsAsExcel: () => getMultipleSheetsAsExcel
});
module.exports = __toCommonJS(main_exports);
// packages/ag-grid-enterprise/src/license/gridLicenseManager.ts
var import_ag_grid_community2 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/license/shared/md5.ts
var MD5 = class {
constructor() {
this.ieCompatibility = false;
}
init() {
this.ieCompatibility = this.md5("hello") != "5d41402abc4b2a76b9719d911017c592";
}
md5cycle(x, k) {
let a = x[0], b = x[1], c = x[2], d = x[3];
a = this.ff(a, b, c, d, k[0], 7, -680876936);
d = this.ff(d, a, b, c, k[1], 12, -389564586);
c = this.ff(c, d, a, b, k[2], 17, 606105819);
b = this.ff(b, c, d, a, k[3], 22, -1044525330);
a = this.ff(a, b, c, d, k[4], 7, -176418897);
d = this.ff(d, a, b, c, k[5], 12, 1200080426);
c = this.ff(c, d, a, b, k[6], 17, -1473231341);
b = this.ff(b, c, d, a, k[7], 22, -45705983);
a = this.ff(a, b, c, d, k[8], 7, 1770035416);
d = this.ff(d, a, b, c, k[9], 12, -1958414417);
c = this.ff(c, d, a, b, k[10], 17, -42063);
b = this.ff(b, c, d, a, k[11], 22, -1990404162);
a = this.ff(a, b, c, d, k[12], 7, 1804603682);
d = this.ff(d, a, b, c, k[13], 12, -40341101);
c = this.ff(c, d, a, b, k[14], 17, -1502002290);
b = this.ff(b, c, d, a, k[15], 22, 1236535329);
a = this.gg(a, b, c, d, k[1], 5, -165796510);
d = this.gg(d, a, b, c, k[6], 9, -1069501632);
c = this.gg(c, d, a, b, k[11], 14, 643717713);
b = this.gg(b, c, d, a, k[0], 20, -373897302);
a = this.gg(a, b, c, d, k[5], 5, -701558691);
d = this.gg(d, a, b, c, k[10], 9, 38016083);
c = this.gg(c, d, a, b, k[15], 14, -660478335);
b = this.gg(b, c, d, a, k[4], 20, -405537848);
a = this.gg(a, b, c, d, k[9], 5, 568446438);
d = this.gg(d, a, b, c, k[14], 9, -1019803690);
c = this.gg(c, d, a, b, k[3], 14, -187363961);
b = this.gg(b, c, d, a, k[8], 20, 1163531501);
a = this.gg(a, b, c, d, k[13], 5, -1444681467);
d = this.gg(d, a, b, c, k[2], 9, -51403784);
c = this.gg(c, d, a, b, k[7], 14, 1735328473);
b = this.gg(b, c, d, a, k[12], 20, -1926607734);
a = this.hh(a, b, c, d, k[5], 4, -378558);
d = this.hh(d, a, b, c, k[8], 11, -2022574463);
c = this.hh(c, d, a, b, k[11], 16, 1839030562);
b = this.hh(b, c, d, a, k[14], 23, -35309556);
a = this.hh(a, b, c, d, k[1], 4, -1530992060);
d = this.hh(d, a, b, c, k[4], 11, 1272893353);
c = this.hh(c, d, a, b, k[7], 16, -155497632);
b = this.hh(b, c, d, a, k[10], 23, -1094730640);
a = this.hh(a, b, c, d, k[13], 4, 681279174);
d = this.hh(d, a, b, c, k[0], 11, -358537222);
c = this.hh(c, d, a, b, k[3], 16, -722521979);
b = this.hh(b, c, d, a, k[6], 23, 76029189);
a = this.hh(a, b, c, d, k[9], 4, -640364487);
d = this.hh(d, a, b, c, k[12], 11, -421815835);
c = this.hh(c, d, a, b, k[15], 16, 530742520);
b = this.hh(b, c, d, a, k[2], 23, -995338651);
a = this.ii(a, b, c, d, k[0], 6, -198630844);
d = this.ii(d, a, b, c, k[7], 10, 1126891415);
c = this.ii(c, d, a, b, k[14], 15, -1416354905);
b = this.ii(b, c, d, a, k[5], 21, -57434055);
a = this.ii(a, b, c, d, k[12], 6, 1700485571);
d = this.ii(d, a, b, c, k[3], 10, -1894986606);
c = this.ii(c, d, a, b, k[10], 15, -1051523);
b = this.ii(b, c, d, a, k[1], 21, -2054922799);
a = this.ii(a, b, c, d, k[8], 6, 1873313359);
d = this.ii(d, a, b, c, k[15], 10, -30611744);
c = this.ii(c, d, a, b, k[6], 15, -1560198380);
b = this.ii(b, c, d, a, k[13], 21, 1309151649);
a = this.ii(a, b, c, d, k[4], 6, -145523070);
d = this.ii(d, a, b, c, k[11], 10, -1120210379);
c = this.ii(c, d, a, b, k[2], 15, 718787259);
b = this.ii(b, c, d, a, k[9], 21, -343485551);
x[0] = this.add32(a, x[0]);
x[1] = this.add32(b, x[1]);
x[2] = this.add32(c, x[2]);
x[3] = this.add32(d, x[3]);
}
cmn(q, a, b, x, s, t) {
a = this.add32(this.add32(a, q), this.add32(x, t));
return this.add32(a << s | a >>> 32 - s, b);
}
ff(a, b, c, d, x, s, t) {
return this.cmn(b & c | ~b & d, a, b, x, s, t);
}
gg(a, b, c, d, x, s, t) {
return this.cmn(b & d | c & ~d, a, b, x, s, t);
}
hh(a, b, c, d, x, s, t) {
return this.cmn(b ^ c ^ d, a, b, x, s, t);
}
ii(a, b, c, d, x, s, t) {
return this.cmn(c ^ (b | ~d), a, b, x, s, t);
}
md51(s) {
const n = s.length;
const state = [1732584193, -271733879, -1732584194, 271733878];
let i;
for (i = 64; i <= s.length; i += 64) {
this.md5cycle(state, this.md5blk(s.substring(i - 64, i)));
}
s = s.substring(i - 64);
const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < s.length; i++) {
tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);
}
tail[i >> 2] |= 128 << (i % 4 << 3);
if (i > 55) {
this.md5cycle(state, tail);
for (i = 0; i < 16; i++) {
tail[i] = 0;
}
}
tail[14] = n * 8;
this.md5cycle(state, tail);
return state;
}
/* there needs to be support for Unicode here, * unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise I suthis.ggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard itself needs to look at this: it should start
* providing access to strings as preformed UTF-8 8-bit unsigned value arrays.
*/
md5blk(s) {
const md5blks = [];
for (let i = 0; i < 64; i += 4) {
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
}
return md5blks;
}
rhex(n) {
const hex_chr = "0123456789abcdef".split("");
let s = "", j = 0;
for (; j < 4; j++) {
s += hex_chr[n >> j * 8 + 4 & 15] + hex_chr[n >> j * 8 & 15];
}
return s;
}
hex(x) {
for (let i = 0; i < x.length; i++) {
x[i] = this.rhex(x[i]);
}
return x.join("");
}
md5(s) {
return this.hex(this.md51(s));
}
add32(a, b) {
return this.ieCompatibility ? this.add32Compat(a, b) : this.add32Std(a, b);
}
/* this function is much faster, so if possible we use it. Some IEs are the only ones I know of that
need the idiotic second function, generated by an if clause. */
add32Std(a, b) {
return a + b & 4294967295;
}
add32Compat(x, y) {
const lsw = (x & 65535) + (y & 65535), msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return msw << 16 | lsw & 65535;
}
};
// packages/ag-grid-enterprise/src/license/shared/licenseManager.ts
var LICENSE_TYPES = {
"01": "GRID",
"02": "CHARTS",
"0102": "BOTH"
};
var LICENSING_HELP_URL = "https://www.ag-grid.com/licensing/";
var _LicenseManager = class _LicenseManager {
constructor(document2) {
this.watermarkMessage = void 0;
this.totalMessageLength = 124;
this.document = document2;
this.md5 = new MD5();
this.md5.init();
}
validateLicense() {
const licenseDetails = this.getLicenseDetails(_LicenseManager.licenseKey);
const currentLicenseName = `AG Grid ${licenseDetails.currentLicenseType === "BOTH" ? "and AG Charts " : ""}Enterprise`;
const suppliedLicenseName = licenseDetails.suppliedLicenseType === void 0 ? "" : `AG ${licenseDetails.suppliedLicenseType === "BOTH" ? "Grid and AG Charts" : licenseDetails.suppliedLicenseType === "GRID" ? "Grid" : "Charts"} Enterprise`;
if (licenseDetails.missing) {
if (!this.isWebsiteUrl() || this.isForceWatermark()) {
this.outputMissingLicenseKey(currentLicenseName);
}
} else if (licenseDetails.expired) {
const gridReleaseDate = _LicenseManager.getGridReleaseDate();
const formattedReleaseDate = _LicenseManager.formatDate(gridReleaseDate);
this.outputExpiredKey(licenseDetails.expiry, formattedReleaseDate, currentLicenseName, suppliedLicenseName);
} else if (!licenseDetails.valid) {
this.outputInvalidLicenseKey(
!!licenseDetails.incorrectLicenseType,
currentLicenseName,
suppliedLicenseName
);
} else if (licenseDetails.isTrial && licenseDetails.trialExpired) {
this.outputExpiredTrialKey(licenseDetails.expiry, currentLicenseName, suppliedLicenseName);
}
}
static extractExpiry(license) {
const restrictionHashed = license.substring(license.lastIndexOf("_") + 1, license.length);
return new Date(parseInt(_LicenseManager.decode(restrictionHashed), 10));
}
static extractLicenseComponents(licenseKey) {
let cleanedLicenseKey = licenseKey.replace(/[\u200B-\u200D\uFEFF]/g, "");
cleanedLicenseKey = cleanedLicenseKey.replace(/\r?\n|\r/g, "");
if (licenseKey.length <= 32) {
return { md5: null, license: licenseKey, version: null, isTrial: null };
}
const hashStart = cleanedLicenseKey.length - 32;
const md5 = cleanedLicenseKey.substring(hashStart);
const license = cleanedLicenseKey.substring(0, hashStart);
const [version, isTrial, type] = _LicenseManager.extractBracketedInformation(cleanedLicenseKey);
return { md5, license, version, isTrial, type };
}
getLicenseDetails(licenseKey) {
const currentLicenseType = _LicenseManager.chartsLicenseManager ? "BOTH" : "GRID";
if (!licenseKey?.length) {
return {
licenseKey,
valid: false,
missing: true,
currentLicenseType
};
}
const gridReleaseDate = _LicenseManager.getGridReleaseDate();
const { md5, license, version, isTrial, type } = _LicenseManager.extractLicenseComponents(licenseKey);
let valid = md5 === this.md5.md5(license) && licenseKey.indexOf("For_Trialing_ag-Grid_Only") === -1;
let trialExpired = void 0;
let expired = void 0;
let expiry = null;
let incorrectLicenseType = false;
let suppliedLicenseType = void 0;
function handleTrial() {
const now = /* @__PURE__ */ new Date();
trialExpired = expiry < now;
expired = void 0;
}
if (valid) {
expiry = _LicenseManager.extractExpiry(license);
valid = !isNaN(expiry.getTime());
if (valid) {
expired = gridReleaseDate > expiry;
switch (version) {
case "legacy":
case "2": {
if (isTrial) {
handleTrial();
}
break;
}
case "3": {
if (!type?.length) {
valid = false;
} else {
suppliedLicenseType = type;
if (type !== LICENSE_TYPES["01"] && type !== LICENSE_TYPES["0102"] || currentLicenseType === "BOTH" && suppliedLicenseType !== "BOTH") {
valid = false;
incorrectLicenseType = true;
} else if (isTrial) {
handleTrial();
}
}
}
}
}
}
if (!valid) {
return {
licenseKey,
valid,
incorrectLicenseType,
currentLicenseType,
suppliedLicenseType
};
}
return {
licenseKey,
valid,
expiry: _LicenseManager.formatDate(expiry),
expired,
version,
isTrial,
trialExpired,
incorrectLicenseType,
currentLicenseType,
suppliedLicenseType
};
}
isDisplayWatermark() {
return this.isForceWatermark() || !this.isLocalhost() && !this.isWebsiteUrl() && !!this.watermarkMessage?.length;
}
getWatermarkMessage() {
return this.watermarkMessage || "";
}
getHostname() {
const win = this.document.defaultView || window;
const loc = win.location;
const { hostname = "" } = loc;
return hostname;
}
isForceWatermark() {
const win = this.document.defaultView || window;
const loc = win.location;
const { pathname } = loc;
return pathname ? pathname.indexOf("forceWatermark") !== -1 : false;
}
isWebsiteUrl() {
const hostname = this.getHostname();
return hostname.match(/^((?:[\w-]+\.)?ag-grid\.com)$/) !== null;
}
isLocalhost() {
const hostname = this.getHostname();
return hostname.match(/^(?:127\.0\.0\.1|localhost)$/) !== null;
}
static formatDate(date) {
const monthNames = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
const day = date.getDate();
const monthIndex = date.getMonth();
const year = date.getFullYear();
return day + " " + monthNames[monthIndex] + " " + year;
}
static getGridReleaseDate() {
return new Date(parseInt(_LicenseManager.decode(_LicenseManager.RELEASE_INFORMATION), 10));
}
static decode(input) {
const keystr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
let t = "";
let n, r, i;
let s, o, u, a;
let f = 0;
const e = input.replace(/[^A-Za-z0-9+/=]/g, "");
while (f < e.length) {
s = keystr.indexOf(e.charAt(f++));
o = keystr.indexOf(e.charAt(f++));
u = keystr.indexOf(e.charAt(f++));
a = keystr.indexOf(e.charAt(f++));
n = s << 2 | o >> 4;
r = (o & 15) << 4 | u >> 2;
i = (u & 3) << 6 | a;
t = t + String.fromCharCode(n);
if (u != 64) {
t = t + String.fromCharCode(r);
}
if (a != 64) {
t = t + String.fromCharCode(i);
}
}
t = _LicenseManager.utf8_decode(t);
return t;
}
static utf8_decode(input) {
input = input.replace(/rn/g, "n");
let t = "";
for (let n = 0; n < input.length; n++) {
const r = input.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r);
} else if (r > 127 && r < 2048) {
t += String.fromCharCode(r >> 6 | 192);
t += String.fromCharCode(r & 63 | 128);
} else {
t += String.fromCharCode(r >> 12 | 224);
t += String.fromCharCode(r >> 6 & 63 | 128);
t += String.fromCharCode(r & 63 | 128);
}
}
return t;
}
static setChartsLicenseManager(dependantLicenseManager) {
this.chartsLicenseManager = dependantLicenseManager;
this.chartsLicenseManager?.setLicenseKey(this.licenseKey, true);
}
static setLicenseKey(licenseKey) {
this.licenseKey = licenseKey;
this.chartsLicenseManager?.setLicenseKey(licenseKey, true);
}
static extractBracketedInformation(licenseKey) {
if (!licenseKey.includes("[")) {
return ["legacy", false, void 0];
}
const matches = licenseKey.match(/\[(.*?)\]/g).map((match) => match.replace("[", "").replace("]", ""));
if (!matches || matches.length === 0) {
return ["legacy", false, void 0];
}
const isTrial = matches.filter((match) => match === "TRIAL").length === 1;
const rawVersion = matches.filter((match) => match.indexOf("v") === 0)[0];
const version = rawVersion ? rawVersion.replace("v", "") : "legacy";
const type = LICENSE_TYPES[matches.filter((match) => LICENSE_TYPES[match])[0]];
return [version, isTrial, type];
}
centerPadAndOutput(input) {
const paddingRequired = this.totalMessageLength - input.length;
console.error(input.padStart(paddingRequired / 2 + input.length, "*").padEnd(this.totalMessageLength, "*"));
}
padAndOutput(input, padding = "*", terminateWithPadding = "") {
console.error(
input.padEnd(this.totalMessageLength - terminateWithPadding.length, padding) + terminateWithPadding
);
}
outputInvalidLicenseKey(incorrectLicenseType, currentLicenseName, suppliedLicenseName) {
if (incorrectLicenseType) {
this.centerPadAndOutput("");
this.centerPadAndOutput(` ${currentLicenseName} License `);
this.centerPadAndOutput(" Incompatible License Key ");
this.padAndOutput(
`* Your license key is for ${suppliedLicenseName} only and does not cover you for ${currentLicenseName}.`,
" ",
"*"
);
this.padAndOutput(`* To troubleshoot your license key visit ${LICENSING_HELP_URL}.`, " ", "*");
this.centerPadAndOutput("");
this.centerPadAndOutput("");
} else {
this.centerPadAndOutput("");
this.centerPadAndOutput(` ${currentLicenseName} License `);
this.centerPadAndOutput(" Invalid License Key ");
this.padAndOutput(`* Your license key is not valid.`, " ", "*");
this.padAndOutput(`* To troubleshoot your license key visit ${LICENSING_HELP_URL}.`, " ", "*");
this.centerPadAndOutput("");
this.centerPadAndOutput("");
}
this.watermarkMessage = "Invalid License";
}
outputExpiredTrialKey(formattedExpiryDate, currentLicenseName, suppliedLicenseName) {
this.centerPadAndOutput("");
this.centerPadAndOutput(` ${currentLicenseName} License `);
this.centerPadAndOutput(" Trial Period Expired. ");
this.padAndOutput(
`* Your trial only license for ${suppliedLicenseName} expired on ${formattedExpiryDate}.`,
" ",
"*"
);
this.padAndOutput("* Please email info@ag-grid.com to purchase a license.", " ", "*");
this.centerPadAndOutput("");
this.centerPadAndOutput("");
this.watermarkMessage = "Trial Period Expired";
}
outputMissingLicenseKey(currentLicenseName) {
this.centerPadAndOutput("");
this.centerPadAndOutput(` ${currentLicenseName} License `);
this.centerPadAndOutput(" License Key Not Found ");
this.padAndOutput(`* All ${currentLicenseName} features are unlocked for trial.`, " ", "*");
this.padAndOutput(
"* If you want to hide the watermark please email info@ag-grid.com for a trial license key.",
" ",
"*"
);
this.centerPadAndOutput("");
this.centerPadAndOutput("");
this.watermarkMessage = "For Trial Use Only";
}
outputExpiredKey(formattedExpiryDate, formattedReleaseDate, currentLicenseName, suppliedLicenseName) {
this.centerPadAndOutput("");
this.centerPadAndOutput(` ${currentLicenseName} License `);
this.centerPadAndOutput(" Incompatible Software Version ");
this.padAndOutput(
`* Your license key works with versions${suppliedLicenseName == "" ? "" : ` of ${suppliedLicenseName}`} released before ${formattedExpiryDate}.`,
" ",
"*"
);
this.padAndOutput(`* The version you are trying to use was released on ${formattedReleaseDate}.`, " ", "*");
this.padAndOutput("* Please contact info@ag-grid.com to renew your license key.", " ", "*");
this.centerPadAndOutput("");
this.centerPadAndOutput("");
this.watermarkMessage = "License Expired";
}
};
_LicenseManager.RELEASE_INFORMATION = "MTc1NTA5MjQ4MDczNA==";
var LicenseManager = _LicenseManager;
// packages/ag-grid-enterprise/src/license/watermark.ts
var import_ag_grid_community = require("ag-grid-community");
// packages/ag-grid-enterprise/src/license/watermark.css-GENERATED.ts
var watermarkCSS = (
/*css*/
`.ag-watermark{bottom:20px;color:#9b9b9b;opacity:.7;position:absolute;transition:opacity 1s ease-out 3s;&:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMDkiIGhlaWdodD0iMzYiIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyMDkgMzYiPjxwYXRoIGZpbGw9IiM5QjlCOUIiIGQ9Ik0xOTIuOTkzIDIzLjY1OHYtNy45NDZoLTEzLjU0MWwtNy45NDcgNy45NDZ6TTIwOC4yNSAzLjk1aC0xNi45NzRsLTguMDEgNy45NDdoMjQuOTg0ek0xNjMuNjIyIDMxLjYwNWw0LjA2OS00LjA2OWgxMy43MzJ2Ny45NDdoLTE3LjgwMXoiLz48cGF0aCBmaWxsPSIjOUI5QjlCIiBkPSJNMTY2LjYxIDE5Ljc4aDguNzczbDguMDEtNy45NDZIMTY2LjYxek0xNTcuMDExIDMxLjYwNWg2LjYxMWw3Ljg4My03Ljk0N2gtMTQuNDk0ek0xOTEuMjc2IDMuOTVsLTQuMDY4IDQuMDdIMTYxLjI3Vi4wNzJoMzAuMDA2ek0yMC44NCAzMC4yMDZIOC4zNzhsLTIuMTYyIDUuMzRILjc1TDEyLjI1NyA4LjU5Mmg0Ljc2OEwyOC41MyAzNS41NDZoLTUuNTN6bS0xLjcxNy00LjI2TDE0LjYwOSAxNC45NWwtNC41MTQgMTAuOTk4ek0xMDQuNDM3IDE4LjUwOWMxLjU4OS0yLjM1MiA1LjU5NC0yLjYwNyA3LjI0Ny0yLjYwN3Y0LjU3OGMtMi4wMzQgMC00LjA2OS4wNjMtNS4yNzcuOTUzLTEuMjA3Ljg5LTEuODQzIDIuMDk4LTEuODQzIDMuNTZ2MTAuNTUzaC00Ljk1OVYxNS45MDJoNC43Njh6TTExOS4zNzYgMTUuOTAyaC00Ljk1OHYxOS42NDRoNC45NTh6TTExOS4zNzYgNy4xM2gtNC45NTh2NS44NDhoNC45NTh6TTE0My45NzkgNy4xM3YyOC40MTZoLTQuNzY4bC0uMTI3LTIuOTg4YTguMyA4LjMgMCAwIDEtMi42NyAyLjQ4Yy0xLjA4MS41NzItMi40MTYuODktMy45NDIuODktMS4zMzUgMC0yLjYwNi0uMjU1LTMuNjg3LS43LTEuMTQ0LS41MDgtMi4xNjItMS4xNDQtMi45ODgtMi4wMzRhOS42IDkuNiAwIDAgMS0xLjk3MS0zLjE3OWMtLjUwOC0xLjIwNy0uNjk5LTIuNjA2LS42OTktNC4xMzJzLjI1NC0yLjkyNC42OTktNC4xOTZjLjUwOS0xLjI3MSAxLjE0NS0yLjM1MiAxLjk3MS0zLjI0MnMxLjg0NC0xLjU4OSAyLjk4OC0yLjA5OCAyLjM1Mi0uNzYzIDMuNjg3LS43NjNjMS41MjYgMCAyLjc5Ny4yNTUgMy44NzguODI3czEuOTcxIDEuMzM1IDIuNjcgMi40MTZWNy4xOTNoNC45NTl6bS0xMC40MjYgMjQuNTM4YzEuNjUzIDAgMi45MjQtLjU3MiAzLjk0MS0xLjY1M3MxLjUyNi0yLjU0MyAxLjUyNi00LjMyMy0uNTA5LTMuMTc4LTEuNTI2LTQuMzIyYy0xLjAxNy0xLjA4MS0yLjI4OC0xLjY1My0zLjk0MS0xLjY1My0xLjU5IDAtMi45MjUuNTcyLTMuODc4IDEuNjUzLTEuMDE3IDEuMDgtMS41MjYgMi41NDMtMS41MjYgNC4zMjIgMCAxLjc4LjUwOSAzLjE4IDEuNTI2IDQuMjYgMS4wMTcgMS4xNDQgMi4yODggMS43MTYgMy44NzggMS43MTZNNTcuMjAyIDIwLjM1M0g0NC45MzN2NC4yNTloNi45OTNjLS4xOSAyLjE2MS0xLjAxNyAzLjgxNC0yLjQxNiA1LjE1LTEuMzk4IDEuMjctMy4xNzggMS45MDYtNS40NjcgMS45MDYtMS4yNzEgMC0yLjQ4LS4yNTQtMy40OTYtLjY5OWE3IDcgMCAwIDEtMi43MzQtMS45N2MtLjc2My0uODI3LTEuMzM1LTEuODQ0LTEuNzgtMy4wNTJzLS42MzYtMi40OC0uNjM2LTMuOTQyLjE5LTIuNzMzLjYzNi0zLjk0MWMuMzgxLTEuMjA4IDEuMDE3LTIuMTYyIDEuNzgtMy4wNTIuNzYzLS44MjYgMS42NTMtMS40NjIgMi43MzMtMS45N2E5LjEgOS4xIDAgMCAxIDMuNTYtLjdxNC4wMDUgMCA2LjEwMyAxLjkwN2wzLjMwNi0zLjMwNWMtMi40OC0xLjkwNy01LjY1OC0yLjkyNS05LjQwOS0yLjkyNS0yLjA5NyAwLTQuMDA0LjMxOC01LjcyMSAxLjAxOC0xLjcxNi42OTktMy4xNzkgMS41ODktNC4zODYgMi43OTdBMTIuMSAxMi4xIDAgMCAwIDMxLjIgMTYuMjJjLS42MzUgMS43MTctLjk1MyAzLjYyNC0uOTUzIDUuNjU4cy4zMTggMy45NDIgMS4wMTcgNS42NThjLjcgMS43MTcgMS41OSAzLjE3OSAyLjc5NyA0LjM4N2ExMi4xIDEyLjEgMCAwIDAgNC4zODcgMi43OTdjMS43MTYuNyAzLjYyMyAxLjAxNyA1LjY1NyAxLjAxNyAyLjAzNSAwIDMuODc4LS4zMTggNS41MzEtMS4wMTcgMS42NTMtLjcgMy4wNTItMS41OSA0LjE5Ni0yLjc5N3ExLjcxNi0xLjgxMiAyLjY3LTQuMzg3Yy42MzYtMS43MTYuOTU0LTMuNjIzLjk1NC01LjY1OHYtLjgyNmMtLjE5MS0uMTI3LS4yNTUtLjQ0NS0uMjU1LS43TTk1Ljk4MiAyMC4zNTNoLTEyLjI3djQuMjU5aDYuOTkzYy0uMTkgMi4xNjEtMS4wMTcgMy44MTQtMi40MTYgNS4xNS0xLjM5OCAxLjI3LTMuMTc4IDEuOTA2LTUuNDY3IDEuOTA2LTEuMjcxIDAtMi40OC0uMjU0LTMuNDk2LS42OTlhNyA3IDAgMCAxLTIuNzM0LTEuOTdjLS43NjMtLjgyNy0xLjMzNS0xLjg0NC0xLjc4LTMuMDUycy0uNjM2LTIuNDgtLjYzNi0zLjk0Mi4xOS0yLjczMy42MzYtMy45NDFjLjM4MS0xLjIwOCAxLjAxNy0yLjE2MiAxLjc4LTMuMDUyLjc2My0uODI2IDEuNjUzLTEuNDYyIDIuNzM0LTEuOTdhOS4xIDkuMSAwIDAgMSAzLjU2LS43cTQuMDA1IDAgNi4xMDMgMS45MDdsMy4zMDUtMy4zMDVjLTIuNDc5LTEuOTA3LTUuNjU4LTIuOTI1LTkuNDA4LTIuOTI1LTIuMDk4IDAtNC4wMDUuMzE4LTUuNzIyIDEuMDE4LTEuNzE2LjY5OS0zLjE3OCAxLjU4OS00LjM4NiAyLjc5N2ExMi4xIDEyLjEgMCAwIDAtMi43OTcgNC4zODZjLS42MzYgMS43MTctLjk1NCAzLjYyNC0uOTU0IDUuNjU4cy4zMTggMy45NDIgMS4wMTcgNS42NThjLjcgMS43MTcgMS41OSAzLjE3OSAyLjc5NyA0LjM4N2ExMi4xIDEyLjEgMCAwIDAgNC4zODcgMi43OTdjMS43MTYuNyAzLjYyMyAxLjAxNyA1LjY1OCAxLjAxNyAyLjAzNCAwIDMuODc4LS4zMTggNS41My0xLjAxNyAxLjY1My0uNyAzLjA1Mi0xLjU5IDQuMTk2LTIuNzk3cTEuNzE4LTEuODEyIDIuNjctNC4zODdjLjYzNi0xLjcxNi45NTQtMy42MjMuOTU0LTUuNjU4di0uODI2Yy0uMTktLjEyNy0uMjU1LS40NDUtLjI1NS0uNyIvPjwvc3ZnPg==");background-repeat:no-repeat;background-size:170px 40px;content:"";display:block;height:40px;width:170px}}:where(.ag-ltr) .ag-watermark{right:25px}:where(.ag-rtl) .ag-watermark{left:25px}.ag-watermark-text{font-family:Impact,sans-serif;font-size:19px;font-weight:700;opacity:.5}:where(.ag-ltr) .ag-watermark-text{padding-left:.7rem}:where(.ag-rtl) .ag-watermark-text{padding-right:.7rem}`
);
// packages/ag-grid-enterprise/src/license/watermark.ts
var WatermarkElement = {
tag: "div",
cls: "ag-watermark",
children: [{ tag: "div", ref: "eLicenseTextRef", cls: "ag-watermark-text" }]
};
var AgWatermark = class extends import_ag_grid_community.Component {
constructor() {
super(WatermarkElement);
this.eLicenseTextRef = import_ag_grid_community.RefPlaceholder;
this.registerCSS(watermarkCSS);
}
wireBeans(beans) {
this.licenseManager = beans.licenseManager;
}
postConstruct() {
const show = this.shouldDisplayWatermark();
this.setDisplayed(show);
if (show) {
this.eLicenseTextRef.textContent = this.licenseManager.getWatermarkMessage();
window.setTimeout(() => this.addCss("ag-opacity-zero"), 0);
window.setTimeout(() => this.setDisplayed(false), 5e3);
}
}
shouldDisplayWatermark() {
return this.licenseManager.isDisplayWatermark();
}
};
var AgWatermarkSelector = {
selector: "AG-WATERMARK",
component: AgWatermark
};
// packages/ag-grid-enterprise/src/license/gridLicenseManager.ts
var GridLicenseManager = class extends import_ag_grid_community2.BeanStub {
constructor() {
super(...arguments);
this.beanName = "licenseManager";
}
postConstruct() {
this.validateLicense();
}
validateLicense() {
this.licenseManager = new LicenseManager((0, import_ag_grid_community2._getDocument)(this.beans));
this.licenseManager.validateLicense();
}
static getLicenseDetails(licenseKey) {
return new LicenseManager(null).getLicenseDetails(licenseKey);
}
getWatermarkSelector() {
return AgWatermarkSelector;
}
isDisplayWatermark() {
return this.licenseManager.isDisplayWatermark();
}
getWatermarkMessage() {
return this.licenseManager.getWatermarkMessage();
}
static setLicenseKey(licenseKey) {
LicenseManager.setLicenseKey(licenseKey);
}
static setChartsLicenseManager(chartsLicenseManager) {
LicenseManager.setChartsLicenseManager(chartsLicenseManager);
}
};
// packages/ag-grid-enterprise/src/excelExport/excelCreator.ts
var import_ag_grid_community11 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/excelExport/excelSerializingSession.ts
var import_ag_grid_community9 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/excelExport/assets/excelUtils.ts
var import_ag_grid_community3 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/excelExport/assets/excelConstants.ts
var INCH_TO_EMU = 9525;
var numberFormatMap = {
"0": 1,
"0.00": 2,
"#,##0": 3,
"#,##0.00": 4,
"0%": 9,
"0.00%": 10,
"0.00E+00": 11,
"# ?/?": 12,
"# ??/??": 13,
"mm-dd-yy": 14,
"d-mmm-yy": 15,
"d-mmm": 16,
"mmm-yy": 17,
"h:mm AM/PM": 18,
"h:mm:ss AM/PM": 19,
"h:mm": 20,
"h:mm:ss": 21,
"m/d/yy h:mm": 22,
"#,##0 ;(#,##0)": 37,
"#,##0 ;[Red](#,##0)": 38,
"#,##0.00;(#,##0.00)": 39,
"#,##0.00;[Red](#,##0.00)": 40,
"mm:ss": 45,
"[h]:mm:ss": 46,
"mmss.0": 47,
"##0.0E+0": 48,
"@": 49
};
// packages/ag-grid-enterprise/src/excelExport/assets/xmlFactory.ts
var LINE_SEPARATOR = "\r\n";
function returnAttributeIfPopulated(key, value, booleanTransformer) {
if (!value && value !== "" && value !== 0) {
return "";
}
let xmlValue = value;
if (typeof value === "boolean") {
if (booleanTransformer) {
xmlValue = booleanTransformer(value);
}
}
return ` ${key}="${xmlValue}"`;
}
function createXmlHeader(headerElement = {}) {
const headerStart = "<?";
const headerEnd = "?>";
const keys = ["version"];
if (!headerElement.version) {
headerElement.version = "1.0";
}
if (headerElement.encoding) {
keys.push("encoding");
}
if (headerElement.standalone) {
keys.push("standalone");
}
const att = keys.map((key) => `${key}="${headerElement[key]}"`).join(" ");
return `${headerStart}xml ${att} ${headerEnd}`;
}
function createXml(xmlElement, booleanTransformer) {
let props = "";
if (xmlElement.properties) {
if (xmlElement.properties.prefixedAttributes) {
xmlElement.properties.prefixedAttributes.forEach((prefixedSet) => {
Object.keys(prefixedSet.map).forEach((key) => {
props += returnAttributeIfPopulated(
prefixedSet.prefix + key,
prefixedSet.map[key],
booleanTransformer
);
});
});
}
if (xmlElement.properties.rawMap) {
Object.keys(xmlElement.properties.rawMap).forEach((key) => {
props += returnAttributeIfPopulated(key, xmlElement.properties.rawMap[key], booleanTransformer);
});
}
}
let result = "<" + xmlElement.name + props;
if (!xmlElement.children && xmlElement.textNode == null) {
return result + "/>" + LINE_SEPARATOR;
}
if (xmlElement.textNode != null) {
return result + ">" + xmlElement.textNode + "</" + xmlElement.name + ">" + LINE_SEPARATOR;
}
result += ">" + LINE_SEPARATOR;
if (xmlElement.children) {
xmlElement.children.forEach((it) => {
result += createXml(it, booleanTransformer);
});
}
return result + "</" + xmlElement.name + ">" + LINE_SEPARATOR;
}
// packages/ag-grid-enterprise/src/excelExport/assets/excelUtils.ts
var pointsToPixel = (points) => {
return Math.round(points * 96 / 72);
};
var pixelsToEMU = (value) => {
return Math.ceil(value * INCH_TO_EMU);
};
var getFontFamilyId = (name) => {
if (name === void 0) {
return;
}
const families = ["Automatic", "Roman", "Swiss", "Modern", "Script", "Decorative"];
const pos = families.indexOf(name || "Automatic");
return Math.max(pos, 0);
};
var getHeightFromProperty = (rowIndex, height) => {
if (!height) {
return;
}
let finalHeight;
if (typeof height === "number") {
finalHeight = height;
} else {
const heightFunc = height;
finalHeight = heightFunc({ rowIndex });
}
return finalHeight;
};
var setExcelImageTotalWidth = (image, columnsToExport) => {
const { colSpan, column } = image.position;
if (!image.width) {
return;
}
if (colSpan) {
const columnsInSpan = columnsToExport.slice(column - 1, column + colSpan - 1);
let totalWidth = 0;
for (let i = 0; i < columnsInSpan.length; i++) {
const colWidth = columnsInSpan[i].getActualWidth();
if (image.width < totalWidth + colWidth) {
image.position.colSpan = i + 1;
image.totalWidth = image.width;
image.width = image.totalWidth - totalWidth;
break;
}
totalWidth += colWidth;
}
} else {
image.totalWidth = image.width;
}
};
var setExcelImageTotalHeight = (image, rowHeight) => {
const { rowSpan, row } = image.position;
if (!image.height) {
return;
}
if (rowSpan) {
let totalHeight = 0;
let counter = 0;
for (let i = row; i < row + rowSpan; i++) {
const nextRowHeight = pointsToPixel(getHeightFromProperty(i, rowHeight) || 20);
if (image.height < totalHeight + nextRowHeight) {
image.position.rowSpan = counter + 1;
image.totalHeight = image.height;
image.height = image.totalHeight - totalHeight;
break;
}
totalHeight += nextRowHeight;
counter++;
}
} else {
image.totalHeight = image.height;
}
};
var createXmlPart = (body, skipHeader) => {
const header = createXmlHeader({
encoding: "UTF-8",
standalone: "yes"
});
const xmlBody = createXml(body);
if (skipHeader) {
return xmlBody;
}
return `${header}${xmlBody}`;
};
var getExcelColumnName = (colIdx) => {
const startCode = 65;
const tableWidth = 26;
const fromCharCode = String.fromCharCode;
const pos = Math.floor(colIdx / tableWidth);
const tableIdx = colIdx % tableWidth;
if (!pos || colIdx === tableWidth) {
return fromCharCode(startCode + colIdx - 1);
}
if (!tableIdx) {
return getExcelColumnName(pos - 1) + "Z";
}
if (pos < tableWidth) {
return fromCharCode(startCode + pos - 1) + fromCharCode(startCode + tableIdx - 1);
}
return getExcelColumnName(pos) + fromCharCode(startCode + tableIdx - 1);
};
var sanitizeTableName = (name) => {
return name.replaceAll("\n", "_x000a_");
};
var replaceInvisibleCharacters = (str) => {
if (str == null) {
return null;
}
let newString = "";
for (let i = 0; i < str.length; i++) {
const point = str.charCodeAt(i);
if (point >= 0 && point <= 31 && point !== 10) {
const convertedCode = point.toString(16).toUpperCase();
const paddedCode = convertedCode.padStart(4, "0");
const newValue = `_x${paddedCode}_`;
newString += newValue;
} else {
newString += str[i];
}
}
return newString;
};
var buildSharedString = (strMap) => {
const ret = [];
for (const key of strMap.keys()) {
const textNode = key.toString();
const child = {
name: "t",
textNode: (0, import_ag_grid_community3._escapeString)(replaceInvisibleCharacters(textNode))
};
const preserveSpaces = textNode.trim().length !== textNode.length;
if (preserveSpaces) {
child.properties = {
rawMap: {
"xml:space": "preserve"
}
};
}
ret.push({
name: "si",
children: [child]
});
}
return ret;
};
// packages/ag-grid-enterprise/src/excelExport/excelXlsxFactory.ts
var import_ag_grid_community8 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/contentType.ts
var contentTypeFactory = {
getTemplate(config) {
const { name, ContentType, Extension, PartName } = config;
return {
name,
properties: {
rawMap: {
Extension,
PartName,
ContentType
}
}
};
}
};
var contentType_default = contentTypeFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/contentTypes.ts
var _normaliseImageExtension = (ext) => ext === "jpg" ? "jpeg" : ext;
var contentTypesFactory = {
getTemplate(sheetLen) {
const worksheets = new Array(sheetLen).fill(void 0).map((v, i) => ({
name: "Override",
ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
PartName: `/xl/worksheets/sheet${i + 1}.xml`
}));
const sheetsWithImages = XLSX_WORKSHEET_IMAGES.size;
const headerFooterImages = XLSX_WORKSHEET_HEADER_FOOTER_IMAGES.size;
const imageTypesObject = {};
XLSX_WORKBOOK_IMAGE_IDS.forEach((v) => {
imageTypesObject[_normaliseImageExtension(v.type)] = true;
});
const imageDocs = new Array(sheetsWithImages).fill(void 0).map((v, i) => ({
name: "Override",
ContentType: "application/vnd.openxmlformats-officedocument.drawing+xml",
PartName: `/xl/drawings/drawing${i + 1}.xml`
}));
const tableDocs = [];
XLSX_WORKSHEET_DATA_TABLES.forEach(({ name }) => {
tableDocs.push({
name: "Override",
ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml",
PartName: `/xl/tables/${name}.xml`
});
});
const imageTypes = Object.keys(imageTypesObject).map((ext) => ({
name: "Default",
ContentType: `image/${ext}`,
Extension: ext
}));
if (headerFooterImages) {
imageTypes.push({
name: "Default",
Extension: "vml",
ContentType: "application/vnd.openxmlformats-officedocument.vmlDrawing"
});
}
const children = [
...imageTypes,
{
name: "Default",
Extension: "rels",
ContentType: "application/vnd.openxmlformats-package.relationships+xml"
},
{
name: "Default",
ContentType: "application/xml",
Extension: "xml"
},
{
name: "Override",
ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
PartName: "/xl/workbook.xml"
},
...worksheets,
{
name: "Override",
ContentType: "application/vnd.openxmlformats-officedocument.theme+xml",
PartName: "/xl/theme/theme1.xml"
},
{
name: "Override",
ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml",
PartName: "/xl/styles.xml"
},
{
name: "Override",
ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml",
PartName: "/xl/sharedStrings.xml"
},
...imageDocs,
...tableDocs,
{
name: "Override",
ContentType: "application/vnd.openxmlformats-package.core-properties+xml",
PartName: "/docProps/core.xml"
}
].map((contentType) => contentType_default.getTemplate(contentType));
return {
name: "Types",
properties: {
rawMap: {
xmlns: "http://schemas.openxmlformats.org/package/2006/content-types"
}
},
children
};
}
};
var contentTypes_default = contentTypesFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/core.ts
var coreFactory = {
getTemplate(author) {
const dt = /* @__PURE__ */ new Date();
const jsonDate = dt.toJSON();
return {
name: "cp:coreProperties",
properties: {
prefixedAttributes: [
{
prefix: "xmlns:",
map: {
cp: "http://schemas.openxmlformats.org/package/2006/metadata/core-properties",
dc: "http://purl.org/dc/elements/1.1/",
dcterms: "http://purl.org/dc/terms/",
dcmitype: "http://purl.org/dc/dcmitype/",
xsi: "http://www.w3.org/2001/XMLSchema-instance"
}
}
]
},
children: [
{
name: "dc:creator",
textNode: author
},
{
name: "dc:title",
textNode: "Workbook"
},
{
name: "dcterms:created",
properties: {
rawMap: {
"xsi:type": "dcterms:W3CDTF"
}
},
textNode: jsonDate
},
{
name: "dcterms:modified",
properties: {
rawMap: {
"xsi:type": "dcterms:W3CDTF"
}
},
textNode: jsonDate
}
]
};
}
};
var core_default = coreFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/drawing.ts
var getAnchor = (name, imageAnchor) => ({
name: `xdr:${name}`,
children: [
{
name: "xdr:col",
textNode: imageAnchor.col.toString()
},
{
name: "xdr:colOff",
textNode: imageAnchor.offsetX.toString()
},
{
name: "xdr:row",
textNode: imageAnchor.row.toString()
},
{
name: "xdr:rowOff",
textNode: imageAnchor.offsetY.toString()
}
]
});
var getExt = (image) => {
const children = [
{
name: "a:ext",
properties: {
rawMap: {
uri: "{FF2B5EF4-FFF2-40B4-BE49-F238E27FC236}"
}
},
children: [
{
name: "a16:creationId",
properties: {
rawMap: {
id: "{822E6D20-D7BC-2841-A643-D49A6EF008A2}",
"xmlns:a16": "http://schemas.microsoft.com/office/drawing/2014/main"
}
}
}
]
}
];
const recolor = image.recolor && image.recolor.toLowerCase();
switch (recolor) {
case "grayscale":
case "sepia":
case "washout":
children.push({
name: "a:ext",
properties: {
rawMap: {
uri: "{C183D7F6-B498-43B3-948B-1728B52AA6E4}"
}
},
children: [
{
name: "adec:decorative",
properties: {
rawMap: {
val: "0",
"xmlns:adec": "http://schemas.microsoft.com/office/drawing/2017/decorative"
}
}
}
]
});
}
return {
name: "a:extLst",
children
};
};
var getNvPicPr = (image, index) => ({
name: "xdr:nvPicPr",
children: [
{
name: "xdr:cNvPr",
properties: {
rawMap: {
id: index,
name: image.id,
descr: image.altText != null ? image.altText : void 0
}
},
children: [getExt(image)]
},
{
name: "xdr:cNvPicPr",
properties: {
rawMap: {
preferRelativeResize: "0"
}
},
children: [
{
name: "a:picLocks"
}
]
}
]
});
var getColorDetails = (color) => {
if (!color.saturation && !color.tint) {
return;
}
const ret = [];
if (color.saturation) {
ret.push({
name: "a:satMod",
properties: {
rawMap: {
val: color.saturation * 1e3
}
}
});
}
if (color.tint) {
ret.push({
name: "a:tint",
properties: {
rawMap: {
val: color.tint * 1e3
}
}
});
}
return ret;
};
var getDuoTone = (primaryColor, secondaryColor) => {
return {
name: "a:duotone",
children: [
{
name: "a:prstClr",
properties: {
rawMap: {
val: primaryColor.color
}
},
children: getColorDetails(primaryColor)
},
{
name: "a:srgbClr",
properties: {
rawMap: {
val: secondaryColor.color
}
},
children: getColorDetails(secondaryColor)
}
]
};
};
var getBlipFill = (image, index) => {
let blipChildren;
if (image.transparency) {
const transparency = Math.min(Math.max(image.transparency, 0), 100);
blipChildren = [
{
name: "a:alphaModFix",
properties: {
rawMap: {
amt: 1e5 - Math.round(transparency * 1e3)
}
}
}
];
}
if (image.recolor) {
if (!blipChildren) {
blipChildren = [];
}
switch (image.recolor.toLocaleLowerCase()) {
case "grayscale":
blipChildren.push({ name: "a:grayscl" });
break;
case "sepia":
blipChildren.push(getDuoTone({ color: "black" }, { color: "D9C3A5", tint: 50, saturation: 180 }));
break;
case "washout":
blipChildren.push({
name: "a:lum",
properties: {
rawMap: {
bright: "70000",
contrast: "-70000"
}
}
});
break;
default:
}
}
return {
name: "xdr:blipFill",
children: [
{
name: "a:blip",
properties: {
rawMap: {
cstate: "print",
"r:embed": `rId${index}`,
"xmlns:r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
}
},
children: blipChildren
},
{
name: "a:stretch",
children: [
{
name: "a:fillRect"
}
]
}
]
};
};
var getSpPr = (image, imageBoxSize) => {
const xfrm = {
name: "a:xfrm",
children: [
{
name: "a:off",
properties: {
rawMap: {
x: 0,
y: 0
}
}
},
{
name: "a:ext",
properties: {
rawMap: {
cx: imageBoxSize.width,
cy: imageBoxSize.height
}
}
}
]
};
if (image.rotation) {
const rotation = image.rotation;
xfrm.properties = {
rawMap: {
rot: Math.min(Math.max(rotation, 0), 360) * 6e4
}
};
}
const prstGeom = {
name: "a:prstGeom",
properties: {
rawMap: {
prst: "rect"
}
},
children: [{ name: "a:avLst" }]
};
const ret = {
name: "xdr:spPr",
children: [xfrm, prstGeom]
};
return ret;
};
var getImageBoxSize = (image) => {
image.fitCell = !!image.fitCell || !image.width || !image.height;
const { position = {}, fitCell, width = 0, height = 0, totalHeight, totalWidth } = image;
const { offsetX = 0, offsetY = 0, row = 1, rowSpan = 1, column = 1, colSpan = 1 } = position;
return {
from: {
row: row - 1,
col: column - 1,
offsetX: pixelsToEMU(offsetX),
offsetY: pixelsToEMU(offsetY)
},
to: {
row: row - 1 + (fitCell ? 1 : rowSpan - 1),
col: column - 1 + (fitCell ? 1 : colSpan - 1),
offsetX: pixelsToEMU(width + offsetX),
offsetY: pixelsToEMU(height + offsetY)
},
height: pixelsToEMU(totalHeight || height),
width: pixelsToEMU(totalWidth || width)
};
};
var getPicture = (image, currentIndex, worksheetImageIndex, imageBoxSize) => {
return {
name: "xdr:pic",
children: [
getNvPicPr(image, currentIndex + 1),
getBlipFill(image, worksheetImageIndex + 1),
getSpPr(image, imageBoxSize)
]
};
};
var drawingFactory = {
getTemplate(config) {
const { sheetIndex } = config;
const sheetImages = XLSX_WORKSHEET_IMAGES.get(sheetIndex);
const sheetImageIds = XLSX_WORKSHEET_IMAGE_IDS.get(sheetIndex);
const children = sheetImages.map((image, idx) => {
const boxSize = getImageBoxSize(image);
return {
name: "xdr:twoCellAnchor",
properties: {
rawMap: {
editAs: "absolute"
}
},
children: [
getAnchor("from", boxSize.from),
getAnchor("to", boxSize.to),
getPicture(image, idx, sheetImageIds.get(image.id).index, boxSize),
{ name: "xdr:clientData" }
]
};
});
return {
name: "xdr:wsDr",
properties: {
rawMap: {
"xmlns:a": "http://schemas.openxmlformats.org/drawingml/2006/main",
"xmlns:xdr": "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"
}
},
children
};
}
};
var drawing_default = drawingFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/relationship.ts
var relationshipFactory = {
getTemplate(config) {
const { Id, Type, Target } = config;
return {
name: "Relationship",
properties: {
rawMap: {
Id,
Type,
Target
}
}
};
}
};
var relationship_default = relationshipFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/relationships.ts
var relationshipsFactory = {
getTemplate(c) {
const children = c.map((relationship) => relationship_default.getTemplate(relationship));
return {
name: "Relationships",
properties: {
rawMap: {
xmlns: "http://schemas.openxmlformats.org/package/2006/relationships"
}
},
children
};
}
};
var relationships_default = relationshipsFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/sharedStrings.ts
var sharedStrings = {
getTemplate(strings) {
return {
name: "sst",
properties: {
rawMap: {
xmlns: "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
count: strings.size,
uniqueCount: strings.size
}
},
children: buildSharedString(strings)
};
}
};
var sharedStrings_default = sharedStrings;
// packages/ag-grid-enterprise/src/excelExport/assets/excelLegacyConvert.ts
var getWeightName = (value) => {
switch (value) {
case 1:
return "thin";
case 2:
return "medium";
case 3:
return "thick";
default:
return "hair";
}
};
var mappedBorderNames = {
None: "None",
Dot: "Dotted",
Dash: "Dashed",
Double: "Double",
DashDot: "DashDot",
DashDotDot: "DashDotDot",
SlantDashDot: "SlantDashDot",
Continuous: "Continuous"
};
var mediumBorders = ["Dashed", "DashDot", "DashDotDot"];
var colorMap = {
None: "none",
Solid: "solid",
Gray50: "mediumGray",
Gray75: "darkGray",
Gray25: "lightGray",
HorzStripe: "darkHorizontal",
VertStripe: "darkVertical",
ReverseDiagStripe: "darkDown",
DiagStripe: "darkUp",
DiagCross: "darkGrid",
ThickDiagCross: "darkTrellis",
ThinHorzStripe: "lightHorizontal",
ThinVertStripe: "lightVertical",
ThinReverseDiagStripe: "lightDown",
ThinDiagStripe: "lightUp",
ThinHorzCross: "lightGrid",
ThinDiagCross: "lightTrellis",
Gray125: "gray125",
Gray0625: "gray0625"
};
var horizontalAlignmentMap = {
Automatic: "general",
Left: "left",
Center: "center",
Right: "right",
Fill: "fill",
Justify: "justify",
CenterAcrossSelection: "centerContinuous",
Distributed: "distributed",
JustifyDistributed: "justify"
};
var verticalAlignmentMap = {
Automatic: void 0,
Top: "top",
Bottom: "bottom",
Center: "center",
Justify: "justify",
Distributed: "distributed",
JustifyDistributed: "justify"
};
var convertLegacyPattern = (name) => {
if (!name) {
return "none";
}
return colorMap[name] || name;
};
var convertLegacyColor = (color) => {
if (color == void 0) {
return color;
}
if (color.charAt(0) === "#") {
color = color.substring(1);
}
return color.length === 6 ? "FF" + color : color;
};
var convertLegacyBorder = (type, weight) => {
if (!type) {
return "thin";
}
const namedWeight = getWeightName(weight);
if (type === "Continuous") {
return namedWeight;
}
const mappedName = mappedBorderNames[type];
if (namedWeight === "medium" && mediumBorders.some((type2) => type2 === mappedName)) {
return `medium${mappedName}`;
}
return `${mappedName.charAt(0).toLowerCase()}${mappedName.substring(1)}`;
};
var convertLegacyHorizontalAlignment = (alignment) => {
return horizontalAlignmentMap[alignment] || "general";
};
var convertLegacyVerticalAlignment = (alignment) => {
return verticalAlignmentMap[alignment] || void 0;
};
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/border.ts
var getBorderColor = (color) => {
return {
name: "color",
properties: {
rawMap: {
rgb: convertLegacyColor(color || "#000000")
}
}
};
};
var borderFactory = {
getTemplate(border) {
const { left, right, top, bottom, diagonal } = border;
const leftChildren = left ? [getBorderColor(left.color)] : void 0;
const rightChildren = right ? [getBorderColor(right.color)] : void 0;
const topChildren = top ? [getBorderColor(top.color)] : void 0;
const bottomChildren = bottom ? [getBorderColor(bottom.color)] : void 0;
const diagonalChildren = diagonal ? [getBorderColor(diagonal.color)] : void 0;
return {
name: "border",
children: [
{
name: "left",
properties: { rawMap: { style: left && left.style } },
children: leftChildren
},
{
name: "right",
properties: { rawMap: { style: right && right.style } },
children: rightChildren
},
{
name: "top",
properties: { rawMap: { style: top && top.style } },
children: topChildren
},
{
name: "bottom",
properties: { rawMap: { style: bottom && bottom.style } },
children: bottomChildren
},
{
name: "diagonal",
properties: { rawMap: { style: diagonal && diagonal.style } },
children: diagonalChildren
}
]
};
}
};
var border_default = borderFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/borders.ts
var bordersFactory = {
getTemplate(borders) {
return {
name: "borders",
properties: {
rawMap: {
count: borders.length
}
},
children: borders.map((border) => border_default.getTemplate(border))
};
}
};
var borders_default = bordersFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/alignment.ts
var getReadingOrderId = (readingOrder) => {
const order = ["Context", "LeftToRight", "RightToLeft"];
const pos = order.indexOf(readingOrder);
return Math.max(pos, 0);
};
var alignmentFactory = {
getTemplate(alignment) {
const { horizontal, indent, readingOrder, rotate, shrinkToFit, vertical, wrapText } = alignment;
return {
name: "alignment",
properties: {
rawMap: {
horizontal: horizontal && convertLegacyHorizontalAlignment(horizontal),
indent,
readingOrder: readingOrder && getReadingOrderId(readingOrder),
textRotation: rotate,
shrinkToFit,
vertical: vertical && convertLegacyVerticalAlignment(vertical),
wrapText
}
}
};
}
};
var alignment_default = alignmentFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/protection.ts
var protectionFactory = {
getTemplate(protection) {
const locked = protection.protected === false ? 0 : 1;
const hidden = protection.hideFormula === true ? 1 : 0;
return {
name: "protection",
properties: {
rawMap: {
hidden,
locked
}
}
};
}
};
var protection_default = protectionFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/xf.ts
var xfFactory = {
getTemplate(xf) {
const { alignment, borderId, fillId, fontId, numFmtId, protection, quotePrefix, xfId } = xf;
const children = [];
if (alignment) {
children.push(alignment_default.getTemplate(alignment));
}
if (protection) {
children.push(protection_default.getTemplate(protection));
}
return {
name: "xf",
properties: {
rawMap: {
applyAlignment: alignment ? 1 : void 0,
applyProtection: protection ? 1 : void 0,
applyBorder: borderId ? 1 : void 0,
applyFill: fillId ? 1 : void 0,
borderId,
fillId,
applyFont: fontId ? 1 : void 0,
fontId,
applyNumberFormat: numFmtId ? 1 : void 0,
numFmtId,
quotePrefix: quotePrefix ? 1 : void 0,
xfId
}
},
children: children.length ? children : void 0
};
}
};
var xf_default = xfFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/cellStyleXfs.ts
var cellStylesXfsFactory = {
getTemplate(xfs) {
return {
name: "cellStyleXfs",
properties: {
rawMap: {
count: xfs.length
}
},
children: xfs.map((xf) => xf_default.getTemplate(xf))
};
}
};
var cellStyleXfs_default = cellStylesXfsFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/cellStyle.ts
var borderFactory2 = {
getTemplate(cellStyle) {
const { builtinId, name, xfId } = cellStyle;
return {
name: "cellStyle",
properties: {
rawMap: {
builtinId,
name,
xfId
}
}
};
}
};
var cellStyle_default = borderFactory2;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/cellStyles.ts
var cellStylesFactory = {
getTemplate(cellStyles) {
return {
name: "cellStyles",
properties: {
rawMap: {
count: cellStyles.length
}
},
children: cellStyles.map((cellStyle) => cellStyle_default.getTemplate(cellStyle))
};
}
};
var cellStyles_default = cellStylesFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/cellXfs.ts
var cellXfsFactory = {
getTemplate(xfs) {
return {
name: "cellXfs",
properties: {
rawMap: {
count: xfs.length
}
},
children: xfs.map((xf) => xf_default.getTemplate(xf))
};
}
};
var cellXfs_default = cellXfsFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/fill.ts
var fillFactory = {
getTemplate(fill) {
const { patternType, fgTheme, fgTint, fgRgb, bgRgb, bgIndexed } = fill;
const pf = {
name: "patternFill",
properties: {
rawMap: {
patternType
}
}
};
if (fgTheme || fgTint || fgRgb) {
pf.children = [
{
name: "fgColor",
properties: {
rawMap: {
theme: fgTheme,
tint: fgTint,
rgb: fgRgb
}
}
}
];
}
if (bgIndexed || bgRgb) {
if (!pf.children) {
pf.children = [];
}
pf.children.push({
name: "bgColor",
properties: {
rawMap: {
indexed: bgIndexed,
rgb: bgRgb
}
}
});
}
return {
name: "fill",
children: [pf]
};
}
};
var fill_default = fillFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/fills.ts
var fillsFactory = {
getTemplate(fills) {
return {
name: "fills",
properties: {
rawMap: {
count: fills.length
}
},
children: fills.map((fill) => fill_default.getTemplate(fill))
};
}
};
var fills_default = fillsFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/font.ts
var fontFactory = {
getTemplate(font) {
const {
size,
colorTheme,
color = "FF000000",
fontName = "Calibri",
family,
scheme,
italic,
bold,
strikeThrough,
outline,
shadow: shadow2,
underline,
verticalAlign
} = font;
const children = [
{ name: "sz", properties: { rawMap: { val: size } } },
{ name: "color", properties: { rawMap: { theme: colorTheme, rgb: color } } },
{ name: "name", properties: { rawMap: { val: fontName } } }
];
if (family) {
children.push({ name: "family", properties: { rawMap: { val: family } } });
}
if (scheme) {
children.push({ name: "scheme", properties: { rawMap: { val: scheme } } });
}
if (italic) {
children.push({ name: "i" });
}
if (bold) {
children.push({ name: "b" });
}
if (strikeThrough) {
children.push({ name: "strike" });
}
if (outline) {
children.push({ name: "outline" });
}
if (shadow2) {
children.push({ name: "shadow" });
}
if (underline) {
children.push({ name: "u", properties: { rawMap: { val: underline } } });
}
if (verticalAlign) {
children.push({ name: "vertAlign", properties: { rawMap: { val: verticalAlign } } });
}
return { name: "font", children };
}
};
var font_default = fontFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/fonts.ts
var fontsFactory = {
getTemplate(fonts) {
return {
name: "fonts",
properties: {
rawMap: {
count: fonts.length
}
},
children: fonts.map((font) => font_default.getTemplate(font))
};
}
};
var fonts_default = fontsFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/numberFormat.ts
var import_ag_grid_community4 = require("ag-grid-community");
function prepareString(str) {
const split = str.split(/(\[[^\]]*\])/);
for (let i = 0; i < split.length; i++) {
let currentString = split[i];
if (!currentString.length) {
continue;
}
if (!currentString.startsWith("[")) {
currentString = currentString.replace(/\$/g, '"$"');
}
split[i] = (0, import_ag_grid_community4._escapeString)(currentString);
}
return split.join("");
}
var numberFormatFactory = {
getTemplate(numberFormat) {
let { formatCode, numFmtId } = numberFormat;
if (formatCode.length) {
formatCode = prepareString(formatCode);
}
return {
name: "numFmt",
properties: {
rawMap: {
formatCode,
numFmtId
}
}
};
}
};
var numberFormat_default = numberFormatFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/numberFormats.ts
var numberFormatsFactory = {
getTemplate(numberFormats) {
return {
name: "numFmts",
properties: {
rawMap: {
count: numberFormats.length
}
},
children: numberFormats.map((numberFormat) => numberFormat_default.getTemplate(numberFormat))
};
}
};
var numberFormats_default = numberFormatsFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/styles/stylesheet.ts
var stylesMap;
var registeredNumberFmts;
var registeredFonts;
var registeredFills;
var registeredBorders;
var registeredCellStyleXfs;
var registeredCellXfs;
var registeredCellStyles;
var currentSheet;
var getStyleName = (name, currentSheet2) => {
if (name.indexOf("mixedStyle") !== -1 && currentSheet2 > 1) {
name += `_${currentSheet2}`;
}
return name;
};
var resetStylesheetValues = () => {
stylesMap = { base: 0 };
registeredNumberFmts = [];
registeredFonts = [{ fontName: "Calibri", colorTheme: "1", family: "2", scheme: "minor" }];
registeredFills = [{ patternType: "none" }, { patternType: "gray125" }];
registeredBorders = [{ left: void 0, right: void 0, top: void 0, bottom: void 0, diagonal: void 0 }];
registeredCellStyleXfs = [{ borderId: 0, fillId: 0, fontId: 0, numFmtId: 0 }];
registeredCellXfs = [{ borderId: 0, fillId: 0, fontId: 0, numFmtId: 0, xfId: 0 }];
registeredCellStyles = [{ builtinId: 0, name: "Normal", xfId: 0 }];
};
var registerFill = (fill) => {
const convertedPattern = convertLegacyPattern(fill.pattern);
const convertedFillColor = convertLegacyColor(fill.color);
const convertedPatternColor = convertLegacyColor(fill.patternColor);
let pos = registeredFills.findIndex((currentFill) => {
const { patternType, fgRgb, bgRgb } = currentFill;
if (patternType != convertedPattern || fgRgb != convertedFillColor || bgRgb != convertedPatternColor) {
return false;
}
return true;
});
if (pos === -1) {
pos = registeredFills.length;
registeredFills.push({
patternType: convertedPattern,
fgRgb: convertedFillColor,
bgRgb: convertedPatternColor
});
}
return pos;
};
var registerNumberFmt = (format) => {
if (numberFormatMap[format]) {
return numberFormatMap[format];
}
let pos = registeredNumberFmts.findIndex((currentFormat) => currentFormat.formatCode === format);
if (pos === -1) {
pos = registeredNumberFmts.length + 164;
registeredNumberFmts.push({ formatCode: format, numFmtId: pos });
} else {
pos = registeredNumberFmts[pos].numFmtId;
}
return pos;
};
var registerBorders = (borders) => {
const { borderBottom, borderTop, borderLeft, borderRight } = borders;
let bottomStyle;
let topStyle;
let leftStyle;
let rightStyle;
let bottomColor;
let topColor;
let leftColor;
let rightColor;
if (borderLeft) {
leftStyle = convertLegacyBorder(borderLeft.lineStyle, borderLeft.weight);
leftColor = convertLegacyColor(borderLeft.color);
}
if (borderRight) {
rightStyle = convertLegacyBorder(borderRight.lineStyle, borderRight.weight);
rightColor = convertLegacyColor(borderRight.color);
}
if (borderBottom) {
bottomStyle = convertLegacyBorder(borderBottom.lineStyle, borderBottom.weight);
bottomColor = convertLegacyColor(borderBottom.color);
}
if (borderTop) {
topStyle = convertLegacyBorder(borderTop.lineStyle, borderTop.weight);
topColor = convertLegacyColor(borderTop.color);
}
let pos = registeredBorders.findIndex((currentBorder) => {
const { left, right, top, bottom } = currentBorder;
if (!left && (leftStyle || leftColor)) {
return false;
}
if (!right && (rightStyle || rightColor)) {
return false;
}
if (!top && (topStyle || topColor)) {
return false;
}
if (!bottom && (bottomStyle || bottomColor)) {
return false;
}
const { style: clS, color: clC } = left || {};
const { style: crS, color: crC } = right || {};
const { style: ctS, color: ctC } = top || {};
const { style: cbS, color: cbC } = bottom || {};
if (clS != leftStyle || clC != leftColor) {
return false;
}
if (crS != rightStyle || crC != rightColor) {
return false;
}
if (ctS != topStyle || ctC != topColor) {
return false;
}
if (cbS != bottomStyle || cbC != bottomColor) {
return false;
}
return true;
});
if (pos === -1) {
pos = registeredBorders.length;
registeredBorders.push({
left: {
style: leftStyle,
color: leftColor
},
right: {
style: rightStyle,
color: rightColor
},
top: {
style: topStyle,
color: topColor
},
bottom: {
style: bottomStyle,
color: bottomColor
},
diagonal: {
style: void 0,
color: void 0
}
});
}
return pos;
};
var registerFont = (font) => {
const {
fontName: name = "Calibri",
color,
size,
bold,
italic,
outline,
shadow: shadow2,
strikeThrough,
underline,
family,
verticalAlign
} = font;
const convertedColor = convertLegacyColor(color);
const familyId = getFontFamilyId(family);
const convertedUnderline = underline ? underline.toLocaleLowerCase() : void 0;
const convertedVerticalAlign = verticalAlign ? verticalAlign.toLocaleLowerCase() : void 0;
let pos = registeredFonts.findIndex((currentFont) => {
if (currentFont.fontName != name || currentFont.color != convertedColor || currentFont.size != size || currentFont.bold != bold || currentFont.italic != italic || currentFont.outline != outline || currentFont.shadow != shadow2 || currentFont.strikeThrough != strikeThrough || currentFont.underline != convertedUnderline || currentFont.verticalAlign != convertedVerticalAlign || currentFont.family != familyId) {
return false;
}
return true;
});
if (pos === -1) {
pos = registeredFonts.length;
registeredFonts.push({
fontName: name,
color: convertedColor,
size,
bold,
italic,
outline,
shadow: shadow2,
strikeThrough,
underline: convertedUnderline,
verticalAlign: convertedVerticalAlign,
family: familyId != null ? familyId.toString() : void 0
});
}
return pos;
};
var registerStyle = (config) => {
const { alignment, borders, font, interior, numberFormat, protection, quotePrefix } = config;
let { id } = config;
let currentFill = 0;
let currentBorder = 0;
let currentFont = 0;
let currentNumberFmt = 0;
if (!id) {
return;
}
id = getStyleName(id, currentSheet);
if (stylesMap[id] != void 0) {
return;
}
if (interior) {
currentFill = registerFill(interior);
}
if (borders) {
currentBorder = registerBorders(borders);
}
if (font) {
currentFont = registerFont(font);
}
if (numberFormat) {
currentNumberFmt = registerNumberFmt(numberFormat.format);
}
stylesMap[id] = registeredCellXfs.length;
registeredCellXfs.push({
alignment,
borderId: currentBorder || 0,
fillId: currentFill || 0,
fontId: currentFont || 0,
numFmtId: currentNumberFmt || 0,
protection,
quotePrefix,
xfId: 0
});
};
var stylesheetFactory = {
getTemplate(defaultFontSize) {
const numberFormats = numberFormats_default.getTemplate(registeredNumberFmts);
const fonts = fonts_default.getTemplate(
registeredFonts.map((font) => ({ ...font, size: font.size != null ? font.size : defaultFontSize }))
);
const fills = fills_default.getTemplate(registeredFills);
const borders = borders_default.getTemplate(registeredBorders);
const cellStylesXfs = cellStyleXfs_default.getTemplate(registeredCellStyleXfs);
const cellXfs = cellXfs_default.getTemplate(registeredCellXfs);
const cellStyles = cellStyles_default.getTemplate(registeredCellStyles);
resetStylesheetValues();
return {
name: "styleSheet",
properties: {
rawMap: {
"mc:Ignorable": "x14ac x16r2 xr",
xmlns: "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
"xmlns:mc": "http://schemas.openxmlformats.org/markup-compatibility/2006",
"xmlns:x14ac": "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac",
"xmlns:x16r2": "http://schemas.microsoft.com/office/spreadsheetml/2015/02/main",
"xmlns:xr": "http://schemas.microsoft.com/office/spreadsheetml/2014/revision"
}
},
children: [
numberFormats,
fonts,
fills,
borders,
cellStylesXfs,
cellXfs,
cellStyles,
{
name: "tableStyles",
properties: {
rawMap: {
count: 0,
defaultPivotStyle: "PivotStyleLight16",
defaultTableStyle: "TableStyleMedium2"
}
}
}
]
};
}
};
var getStyleId = (name, currentSheet2) => {
return stylesMap[getStyleName(name, currentSheet2)] || 0;
};
var registerStyles = (styles, _currentSheet) => {
currentSheet = _currentSheet;
if (currentSheet === 1) {
resetStylesheetValues();
}
styles.forEach(registerStyle);
};
var stylesheet_default = stylesheetFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/table.ts
var import_ag_grid_community5 = require("ag-grid-community");
var tableFactory = {
getTemplate(dataTable, idx) {
const {
name,
columns,
rowRange,
displayName,
showRowStripes,
showColumnStripes,
showFilterButtons,
highlightFirstColumn,
highlightLastColumn
} = dataTable || {};
const noRows = !rowRange || rowRange[0] - rowRange[1] === 0;
if (!dataTable || !name || !Array.isArray(columns) || !columns.length || noRows) {
return { name: "table" };
}
const filterColumns = columns.map((col, idx2) => ({
name: "filterColumn",
properties: {
rawMap: {
colId: idx2.toString(),
// For filters, this should start with 0
hiddenButton: showFilterButtons[idx2] ? 0 : 1
}
}
}));
const firstCell = `A${rowRange[0]}`;
const lastCell = `${getExcelColumnName(columns.length)}${rowRange[1]}`;
const ref = `${firstCell}:${lastCell}`;
const id = `${idx + 1}`;
const displayNameToUse = idx ? `${displayName}_${id}` : displayName;
return {
name: "table",
properties: {
rawMap: {
xmlns: "http://schemas.openxmlformats.org/spreadsheetml/2006/main",
"xmlns:mc": "http://schemas.openxmlformats.org/markup-compatibility/2006",
"mc:Ignorable": "xr xr3",
"xmlns:xr": "http://schemas.microsoft.com/office/spreadsheetml/2014/revision",
"xmlns:xr3": "http://schemas.microsoft.com/office/spreadsheetml/2016/revision3",
name,
displayName: displayNameToUse,
ref,
totalsRowShown: 0,
id
}
},
children: [
{
name: "autoFilter",
properties: {
rawMap: {
ref
}
},
children: filterColumns
},
{
name: "tableColumns",
properties: {
rawMap: {
count: columns.length
}
},
children: columns.map((col, idx2) => ({
name: "tableColumn",
properties: {
rawMap: {
id: (idx2 + 1).toString(),
name: (0, import_ag_grid_community5._escapeString)(sanitizeTableName(col)),
dataCellStyle: "Normal"
}
}
}))
},
{
name: "tableStyleInfo",
properties: {
rawMap: {
name: "TableStyleLight1",
showFirstColumn: highlightFirstColumn ? 1 : 0,
showLastColumn: highlightLastColumn ? 1 : 0,
showRowStripes: showRowStripes ? 1 : 0,
showColumnStripes: showColumnStripes ? 1 : 0
}
}
}
]
};
}
};
var table_default = tableFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/themes/office/colorScheme.ts
var getColorChildren = (props) => {
const [type, innerType, val, lastClr] = props;
return {
name: `a:${type}`,
children: [
{
name: `a:${innerType}`,
properties: {
rawMap: {
val,
lastClr
}
}
}
]
};
};
var colorScheme = {
getTemplate() {
return {
name: "a:clrScheme",
properties: {
rawMap: {
name: "Office"
}
},
children: [
getColorChildren(["dk1", "sysClr", "windowText", "000000"]),
getColorChildren(["lt1", "sysClr", "window", "FFFFFF"]),
getColorChildren(["dk2", "srgbClr", "44546A"]),
getColorChildren(["lt2", "srgbClr", "E7E6E6"]),
getColorChildren(["accent1", "srgbClr", "4472C4"]),
getColorChildren(["accent2", "srgbClr", "ED7D31"]),
getColorChildren(["accent3", "srgbClr", "A5A5A5"]),
getColorChildren(["accent4", "srgbClr", "FFC000"]),
getColorChildren(["accent5", "srgbClr", "5B9BD5"]),
getColorChildren(["accent6", "srgbClr", "70AD47"]),
getColorChildren(["hlink", "srgbClr", "0563C1"]),
getColorChildren(["folHlink", "srgbClr", "954F72"])
]
};
}
};
var colorScheme_default = colorScheme;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/themes/office/fontScheme.ts
var getFont = (props) => {
const [type, typeface, script, panose] = props;
return {
name: `a:${type}`,
properties: {
rawMap: {
script,
typeface,
panose
}
}
};
};
var fontScheme = {
getTemplate() {
return {
name: "a:fontScheme",
properties: {
rawMap: {
name: "Office"
}
},
children: [
{
name: "a:majorFont",
children: [
getFont(["latin", "Calibri Light", void 0, "020F0302020204030204"]),
getFont(["ea", ""]),
getFont(["cs", ""]),
getFont(["font", "\u6E38\u30B4\u30B7\u30C3\u30AF Light", "Jpan"]),
getFont(["font", "\uB9D1\uC740 \uACE0\uB515", "Hang"]),
getFont(["font", "\u7B49\u7EBF Light", "Hans"]),
getFont(["font", "\u65B0\u7D30\u660E\u9AD4", "Hant"]),
getFont(["font", "Times New Roman", "Arab"]),
getFont(["font", "Times New Roman", "Hebr"]),
getFont(["font", "Tahoma", "Thai"]),
getFont(["font", "Nyala", "Ethi"]),
getFont(["font", "Vrinda", "Beng"]),
getFont(["font", "Shruti", "Gujr"]),
getFont(["font", "MoolBoran", "Khmr"]),
getFont(["font", "Tunga", "Knda"]),
getFont(["font", "Raavi", "Guru"]),
getFont(["font", "Euphemia", "Cans"]),
getFont(["font", "Plantagenet Cherokee", "Cher"]),
getFont(["font", "Microsoft Yi Baiti", "Yiii"]),
getFont(["font", "Microsoft Himalaya", "Tibt"]),
getFont(["font", "MV Boli", "Thaa"]),
getFont(["font", "Mangal", "Deva"]),
getFont(["font", "Gautami", "Telu"]),
getFont(["font", "Latha", "Taml"]),
getFont(["font", "Estrangelo Edessa", "Syrc"]),
getFont(["font", "Kalinga", "Orya"]),
getFont(["font", "Kartika", "Mlym"]),
getFont(["font", "DokChampa", "Laoo"]),
getFont(["font", "Iskoola Pota", "Sinh"]),
getFont(["font", "Mongolian Baiti", "Mong"]),
getFont(["font", "Times New Roman", "Viet"]),
getFont(["font", "Microsoft Uighur", "Uigh"]),
getFont(["font", "Sylfaen", "Geor"]),
getFont(["font", "Arial", "Armn"]),
getFont(["font", "Leelawadee UI", "Bugi"]),
getFont(["font", "Microsoft JhengHei", "Bopo"]),
getFont(["font", "Javanese Text", "Java"]),
getFont(["font", "Segoe UI", "Lisu"]),
getFont(["font", "Myanmar Text", "Mymr"]),
getFont(["font", "Ebrima", "Nkoo"]),
getFont(["font", "Nirmala UI", "Olck"]),
getFont(["font", "Ebrima", "Osma"]),
getFont(["font", "Phagspa", "Phag"]),
getFont(["font", "Estrangelo Edessa", "Syrn"]),
getFont(["font", "Estrangelo Edessa", "Syrj"]),
getFont(["font", "Estrangelo Edessa", "Syre"]),
getFont(["font", "Nirmala UI", "Sora"]),
getFont(["font", "Microsoft Tai Le", "Tale"]),
getFont(["font", "Microsoft New Tai Lue", "Talu"]),
getFont(["font", "Ebrima", "Tfng"])
]
},
{
name: "a:minorFont",
children: [
getFont(["latin", "Calibri", void 0, "020F0502020204030204"]),
getFont(["ea", ""]),
getFont(["cs", ""]),
getFont(["font", "\u6E38\u30B4\u30B7\u30C3\u30AF", "Jpan"]),
getFont(["font", "\uB9D1\uC740 \uACE0\uB515", "Hang"]),
getFont(["font", "\u7B49\u7EBF", "Hans"]),
getFont(["font", "\u65B0\u7D30\u660E\u9AD4", "Hant"]),
getFont(["font", "Arial", "Arab"]),
getFont(["font", "Arial", "Hebr"]),
getFont(["font", "Tahoma", "Thai"]),
getFont(["font", "Nyala", "Ethi"]),
getFont(["font", "Vrinda", "Beng"]),
getFont(["font", "Shruti", "Gujr"]),
getFont(["font", "DaunPenh", "Khmr"]),
getFont(["font", "Tunga", "Knda"]),
getFont(["font", "Raavi", "Guru"]),
getFont(["font", "Euphemia", "Cans"]),
getFont(["font", "Plantagenet Cherokee", "Cher"]),
getFont(["font", "Microsoft Yi Baiti", "Yiii"]),
getFont(["font", "Microsoft Himalaya", "Tibt"]),
getFont(["font", "MV Boli", "Thaa"]),
getFont(["font", "Mangal", "Deva"]),
getFont(["font", "Gautami", "Telu"]),
getFont(["font", "Latha", "Taml"]),
getFont(["font", "Estrangelo Edessa", "Syrc"]),
getFont(["font", "Kalinga", "Orya"]),
getFont(["font", "Kartika", "Mlym"]),
getFont(["font", "DokChampa", "Laoo"]),
getFont(["font", "Iskoola Pota", "Sinh"]),
getFont(["font", "Mongolian Baiti", "Mong"]),
getFont(["font", "Arial", "Viet"]),
getFont(["font", "Microsoft Uighur", "Uigh"]),
getFont(["font", "Sylfaen", "Geor"]),
getFont(["font", "Arial", "Armn"]),
getFont(["font", "Leelawadee UI", "Bugi"]),
getFont(["font", "Microsoft JhengHei", "Bopo"]),
getFont(["font", "Javanese Text", "Java"]),
getFont(["font", "Segoe UI", "Lisu"]),
getFont(["font", "Myanmar Text", "Mymr"]),
getFont(["font", "Ebrima", "Nkoo"]),
getFont(["font", "Nirmala UI", "Olck"]),
getFont(["font", "Ebrima", "Osma"]),
getFont(["font", "Phagspa", "Phag"]),
getFont(["font", "Estrangelo Edessa", "Syrn"]),
getFont(["font", "Estrangelo Edessa", "Syrj"]),
getFont(["font", "Estrangelo Edessa", "Syre"]),
getFont(["font", "Nirmala UI", "Sora"]),
getFont(["font", "Microsoft Tai Le", "Tale"]),
getFont(["font", "Microsoft New Tai Lue", "Talu"]),
getFont(["font", "Ebrima", "Tfng"])
]
}
]
};
}
};
var fontScheme_default = fontScheme;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/themes/office/formatScheme.ts
var getPropertyVal = (name, val, children) => ({
name: `a:${name}`,
properties: {
rawMap: {
val
}
},
children
});
var getGs = (props) => {
const [pos, schemeColor, satMod, lumMod, tint, shade] = props;
const children = [];
children.push(getPropertyVal("satMod", satMod));
if (lumMod) {
children.push(getPropertyVal("lumMod", lumMod));
}
if (tint) {
children.push(getPropertyVal("tint", tint));
}
if (shade) {
children.push(getPropertyVal("shade", shade));
}
return {
name: "a:gs",
properties: {
rawMap: {
pos
}
},
children: [
{
name: "a:schemeClr",
properties: {
rawMap: {
val: schemeColor
}
},
children
}
]
};
};
var getSolidFill = (val, children) => ({
name: "a:solidFill",
children: [getPropertyVal("schemeClr", val, children)]
});
var getGradFill = (props) => {
const [rotWithShape, gs1, gs2, gs3, lin] = props;
const [ang, scaled] = lin;
return {
name: "a:gradFill",
properties: {
rawMap: {
rotWithShape
}
},
children: [
{
name: "a:gsLst",
children: [getGs(gs1), getGs(gs2), getGs(gs3)]
},
{
name: "a:lin",
properties: {
rawMap: {
ang,
scaled
}
}
}
]
};
};
var getLine = (props) => {
const [w, cap, cmpd, algn] = props;
return {
name: "a:ln",
properties: {
rawMap: { w, cap, cmpd, algn }
},
children: [
getSolidFill("phClr"),
getPropertyVal("prstDash", "solid"),
{
name: "a:miter",
properties: {
rawMap: {
lim: "800000"
}
}
}
]
};
};
var getEffectStyle = (shadow2) => {
const children = [];
if (shadow2) {
const [blurRad, dist, dir, algn, rotWithShape] = shadow2;
children.push({
name: "a:outerShdw",
properties: {
rawMap: { blurRad, dist, dir, algn, rotWithShape }
},
children: [getPropertyVal("srgbClr", "000000", [getPropertyVal("alpha", "63000")])]
});
}
return {
name: "a:effectStyle",
children: [
Object.assign(
{},
{
name: "a:effectLst"
},
children.length ? { children } : {}
)
]
};
};
var getFillStyleList = () => ({
name: "a:fillStyleLst",
children: [
getSolidFill("phClr"),
getGradFill([
"1",
["0", "phClr", "105000", "110000", "67000"],
["50000", "phClr", "103000", "105000", "73000"],
["100000", "phClr", "109000", "105000", "81000"],
["5400000", "0"]
]),
getGradFill([
"1",
["0", "phClr", "103000", "102000", "94000"],
["50000", "phClr", "110000", "100000", void 0, "100000"],
["100000", "phClr", "120000", "99000", void 0, "78000"],
["5400000", "0"]
])
]
});
var getLineStyleList = () => ({
name: "a:lnStyleLst",
children: [
getLine(["6350", "flat", "sng", "ctr"]),
getLine(["12700", "flat", "sng", "ctr"]),
getLine(["19050", "flat", "sng", "ctr"])
]
});
var getEffectStyleList = () => ({
name: "a:effectStyleLst",
children: [getEffectStyle(), getEffectStyle(), getEffectStyle(["57150", "19050", "5400000", "ctr", "0"])]
});
var getBgFillStyleList = () => ({
name: "a:bgFillStyleLst",
children: [
getSolidFill("phClr"),
getSolidFill("phClr", [getPropertyVal("tint", "95000"), getPropertyVal("satMod", "170000")]),
getGradFill([
"1",
["0", "phClr", "150000", "102000", "93000", "98000"],
["50000", "phClr", "130000", "103000", "98000", "90000"],
["100000", "phClr", "120000", void 0, void 0, "63000"],
["5400000", "0"]
])
]
});
var formatScheme = {
getTemplate() {
return {
name: "a:fmtScheme",
properties: {
rawMap: {
name: "Office"
}
},
children: [getFillStyleList(), getLineStyleList(), getEffectStyleList(), getBgFillStyleList()]
};
}
};
var formatScheme_default = formatScheme;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/themes/office/themeElements.ts
var themeElements = {
getTemplate() {
return {
name: "a:themeElements",
children: [colorScheme_default.getTemplate(), fontScheme_default.getTemplate(), formatScheme_default.getTemplate()]
};
}
};
var themeElements_default = themeElements;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/themes/office.ts
var officeTheme = {
getTemplate() {
return {
name: "a:theme",
properties: {
prefixedAttributes: [
{
prefix: "xmlns:",
map: {
a: "http://schemas.openxmlformats.org/drawingml/2006/main"
}
}
],
rawMap: {
name: "Office Theme"
}
},
children: [
themeElements_default.getTemplate(),
{
name: "a:objectDefaults"
},
{
name: "a:extraClrSchemeLst"
}
]
};
}
};
var office_default = officeTheme;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/vmlDrawing.ts
var getShapeLayout = () => ({
name: "o:shapelayout",
properties: {
prefixedAttributes: [
{
prefix: "v:",
map: {
ext: "edit"
}
}
]
},
children: [
{
name: "o:idmap",
properties: {
prefixedAttributes: [
{
prefix: "v:",
map: {
ext: "edit"
}
}
],
rawMap: {
data: "1"
}
}
}
]
});
var getStroke = () => ({
name: "v:stroke",
properties: {
rawMap: {
joinstyle: "miter"
}
}
});
var getFormulas = (formulas) => ({
name: "v:formulas",
children: formulas.map((formula) => ({
name: "v:f",
properties: {
rawMap: {
eqn: formula
}
}
}))
});
var getPath = () => ({
name: "v:path",
properties: {
prefixedAttributes: [
{
prefix: "o:",
map: {
connecttype: "rect",
extrusionok: "f"
}
}
],
rawMap: {
gradientshapeok: "t"
}
}
});
var getLock = (params) => {
const { aspectratio, rotation } = params || {};
const rawMap = {};
if (aspectratio) {
rawMap.aspectratio = "t";
}
if (rotation) {
rawMap.rotation = "t";
}
return {
name: "o:lock",
properties: {
prefixedAttributes: [
{
prefix: "v:",
map: {
ext: "edit"
}
}
],
rawMap
}
};
};
function mapNumber(value, startSource, endSource, startTarget, endTarget) {
return (value - startSource) / (endSource - startSource) * (endTarget - startTarget) + startTarget;
}
var getImageData = (image, idx) => {
let rawMap;
const { recolor, brightness, contrast, id } = image;
if (recolor) {
rawMap = {};
if (recolor === "Washout" || recolor === "Grayscale") {
rawMap.gain = "19661f";
rawMap.blacklevel = "22938f";
}
if (recolor === "Black & White" || recolor === "Grayscale") {
rawMap.grayscale = "t";
if (recolor === "Black & White") {
rawMap.bilevel = "t";
}
}
}
if (!recolor || recolor === "Grayscale") {
if (!rawMap) {
rawMap = {};
}
if (contrast != null && contrast !== 50) {
let gain = "1";
if (contrast >= 0) {
if (contrast < 50) {
gain = String(contrast / 50);
} else if (contrast < 100) {
gain = String(50 / (100 - contrast));
} else if (contrast === 100) {
gain = "2147483647f";
}
}
rawMap.gain = gain;
}
if (brightness != null && brightness !== 50) {
rawMap.blacklevel = mapNumber(brightness, 0, 100, -0.5, 0.5).toString();
}
}
return {
name: "v:imagedata",
properties: {
prefixedAttributes: [
{
prefix: "o:",
map: {
relid: `rId${idx}`,
title: id
}
}
],
rawMap
}
};
};
var getShapeType = () => {
const formulas = [
"if lineDrawn pixelLineWidth 0",
"sum @0 1 0",
"sum 0 0 @1",
"prod @2 1 2",
"prod @3 21600 pixelWidth",
"prod @3 21600 pixelHeight",
"sum @0 0 1",
"prod @6 1 2",
"prod @7 21600 pixelWidth",
"sum @8 21600 0",
"prod @7 21600 pixelHeight",
"sum @10 21600 0"
];
return {
name: "v:shapetype",
properties: {
prefixedAttributes: [
{
prefix: "o:",
map: {
spt: "75",
preferrelative: "t"
}
}
],
rawMap: {
coordsize: "21600,21600",
filled: "f",
id: "_x0000_t75",
path: "m@4@5l@4@11@9@11@9@5xe",
stroked: "f"
}
},
children: [getStroke(), getFormulas(formulas), getPath(), getLock({ aspectratio: true })]
};
};
var pixelToPoint = (value) => Math.floor((value ?? 0) * 0.74999943307122);
var getShape = (image, idx) => {
const { width = 0, height = 0, altText } = image;
const imageWidth = pixelToPoint(width);
const imageHeight = pixelToPoint(height);
return {
name: "v:shape",
properties: {
rawMap: {
id: image.headerFooterPosition,
"o:spid": "_x0000_s1025",
style: `position: absolute; margin-left: 0; margin-top: 10in; margin-bottom: 0; margin-right: 0; width: ${imageWidth}pt; height: ${imageHeight}pt; z-index: ${idx + 1}`,
type: "#_x0000_t75",
alt: altText
}
},
children: [getImageData(image, idx + 1), getLock({ rotation: true })]
};
};
var vmlDrawingFactory = {
getTemplate(params) {
const headerFooterImages = XLSX_WORKSHEET_HEADER_FOOTER_IMAGES.get(params.sheetIndex) || [];
const children = [
getShapeLayout(),
getShapeType(),
...headerFooterImages.map((img, idx) => getShape(img, idx))
];
return {
name: "xml",
properties: {
prefixedAttributes: [
{
prefix: "xmlns:",
map: {
v: "urn:schemas-microsoft-com:vml",
o: "urn:schemas-microsoft-com:office:office",
x: "urn:schemas-microsoft-com:office:excel"
}
}
]
},
children
};
}
};
var vmlDrawing_default = vmlDrawingFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/sheet.ts
var sheetFactory = {
getTemplate(name, idx) {
const sheetId = (idx + 1).toString();
return {
name: "sheet",
properties: {
rawMap: {
name,
sheetId,
"r:id": `rId${sheetId}`
}
}
};
}
};
var sheet_default = sheetFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/sheets.ts
var sheetsFactory = {
getTemplate(names) {
return {
name: "sheets",
children: names.map((sheet, idx) => sheet_default.getTemplate(sheet, idx))
};
}
};
var sheets_default = sheetsFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/workbook.ts
var workbookFactory = {
getTemplate(names, activeTab) {
return {
name: "workbook",
properties: {
prefixedAttributes: [
{
prefix: "xmlns:",
map: {
r: "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
}
}
],
rawMap: {
xmlns: "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}
},
children: [
{
name: "bookViews",
children: [
{
name: "workbookView",
properties: {
rawMap: {
activeTab
}
}
}
]
},
sheets_default.getTemplate(names)
]
};
}
};
var workbook_default = workbookFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/worksheet.ts
var import_ag_grid_community7 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/column.ts
var getExcelCellWidth = (width) => Math.ceil((width - 12) / 7 + 1);
var colFactory = {
getTemplate(config) {
const { min, max, outlineLevel, s, width, hidden, bestFit } = config;
let excelWidth = 1;
let customWidth = "0";
if (width > 1) {
excelWidth = getExcelCellWidth(width);
customWidth = "1";
}
return {
name: "col",
properties: {
rawMap: {
min,
max,
outlineLevel: outlineLevel != null ? outlineLevel : void 0,
width: excelWidth,
style: s,
hidden: hidden ? "1" : "0",
bestFit: bestFit ? "1" : "0",
customWidth
}
}
};
}
};
var column_default = colFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/mergeCell.ts
var mergeCellFactory = {
getTemplate(ref) {
return {
name: "mergeCell",
properties: {
rawMap: {
ref
}
}
};
}
};
var mergeCell_default = mergeCellFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/cell.ts
var import_ag_grid_community6 = require("ag-grid-community");
var convertLegacyType = (type) => {
const t = type.charAt(0).toLowerCase();
return t === "s" ? "inlineStr" : t;
};
var cellFactory = {
getTemplate(config, idx, currentSheet2) {
const { ref, data, styleId } = config;
const { type, value } = data || { type: "empty", value: null };
let convertedType = type;
if (type === "f") {
convertedType = "str";
} else if (type.charAt(0) === type.charAt(0).toUpperCase()) {
convertedType = convertLegacyType(type);
}
const obj = {
name: "c",
properties: {
rawMap: {
r: ref,
t: convertedType === "empty" ? void 0 : convertedType,
s: styleId ? getStyleId(styleId, currentSheet2) : void 0
}
}
};
if (convertedType === "empty") {
return obj;
}
let children;
if (convertedType === "str" && type === "f") {
children = [
{
name: "f",
textNode: (0, import_ag_grid_community6._escapeString)(replaceInvisibleCharacters(value))
}
];
} else if (convertedType === "inlineStr") {
children = [
{
name: "is",
children: [
{
name: "t",
textNode: (0, import_ag_grid_community6._escapeString)(replaceInvisibleCharacters(value))
}
]
}
];
} else {
children = [
{
name: "v",
textNode: value
}
];
}
return Object.assign({}, obj, { children });
}
};
var cell_default = cellFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/row.ts
var addEmptyCells = (cells, rowIdx) => {
const mergeMap = [];
let posCounter = 0;
for (let i = 0; i < cells.length; i++) {
const cell = cells[i];
if (cell.mergeAcross) {
mergeMap.push({
pos: i,
excelPos: posCounter
});
posCounter += cell.mergeAcross;
}
posCounter++;
}
if (mergeMap.length) {
for (let i = mergeMap.length - 1; i >= 0; i--) {
const mergedCells = [];
const cell = cells[mergeMap[i].pos];
for (let j = 1; j <= cell.mergeAcross; j++) {
mergedCells.push({
ref: `${getExcelColumnName(mergeMap[i].excelPos + 1 + j)}${rowIdx + 1}`,
styleId: cell.styleId,
data: { type: "empty", value: null }
});
}
if (mergedCells.length) {
cells.splice(mergeMap[i].pos + 1, 0, ...mergedCells);
}
}
}
};
var shouldDisplayCell = (cell) => cell.data?.value !== "" || cell.styleId !== void 0;
var rowFactory = {
getTemplate(config, idx, currentSheet2) {
const { collapsed, hidden, height, outlineLevel, cells = [] } = config;
addEmptyCells(cells, idx);
const children = cells.filter(shouldDisplayCell).map((cell, idx2) => cell_default.getTemplate(cell, idx2, currentSheet2));
return {
name: "row",
properties: {
rawMap: {
r: idx + 1,
collapsed: collapsed ? "1" : "0",
hidden: hidden ? "1" : "0",
ht: height,
customHeight: height != null ? "1" : "0",
spans: "1:1",
outlineLevel: outlineLevel || void 0
}
},
children
};
}
};
var row_default = rowFactory;
// packages/ag-grid-enterprise/src/excelExport/files/ooxml/worksheet.ts
var getMergedCellsAndAddColumnGroups = (rows, cols, suppressColumnOutline) => {
const mergedCells = [];
const cellsWithCollapsibleGroups = [];
rows.forEach((currentRow, rowIdx) => {
const cells = currentRow.cells;
let merges = 0;
let lastCol;
cells.forEach((currentCell, cellIdx) => {
const min = cellIdx + merges + 1;
const start = getExcelColumnName(min);
const outputRow = rowIdx + 1;
if (currentCell.mergeAcross) {
merges += currentCell.mergeAcross;
const end = getExcelColumnName(cellIdx + merges + 1);
mergedCells.push(`${start}${outputRow}:${end}${outputRow}`);
}
if (!cols[min - 1]) {
cols[min - 1] = {};
}
const { collapsibleRanges } = currentCell;
if (collapsibleRanges) {
collapsibleRanges.forEach((range) => {
cellsWithCollapsibleGroups.push([min + range[0], min + range[1]]);
});
}
lastCol = cols[min - 1];
lastCol.min = min;
lastCol.max = min;
currentCell.ref = `${start}${outputRow}`;
});
});
cellsWithCollapsibleGroups.sort((a, b) => {
if (a[0] !== b[0]) {
return a[0] - b[0];
}
return b[1] - a[1];
});
const rangeMap = /* @__PURE__ */ new Map();
const outlineLevel = /* @__PURE__ */ new Map();
cellsWithCollapsibleGroups.filter((currentRange) => {
const rangeString = currentRange.toString();
const inMap = rangeMap.get(rangeString);
if (inMap) {
return false;
}
rangeMap.set(rangeString, true);
return true;
}).forEach((range) => {
const refCol = cols.find((col) => col.min == range[0] && col.max == range[1]);
const currentOutlineLevel = outlineLevel.get(range[0]);
cols.push({
min: range[0],
max: range[1],
outlineLevel: suppressColumnOutline ? void 0 : currentOutlineLevel || 1,
width: (refCol || { width: 100 }).width
});
outlineLevel.set(range[0], (currentOutlineLevel || 0) + 1);
});
return mergedCells;
};
var getPageOrientation = (orientation) => {
if (!orientation || orientation !== "Portrait" && orientation !== "Landscape") {
return "portrait";
}
return orientation.toLocaleLowerCase();
};
var getPageSize = (pageSize) => {
if (pageSize == null) {
return 1;
}
const positions = [
"Letter",
"Letter Small",
"Tabloid",
"Ledger",
"Legal",
"Statement",
"Executive",
"A3",
"A4",
"A4 Small",
"A5",
"A6",
"B4",
"B5",
"Folio",
"Envelope",
"Envelope DL",
"Envelope C5",
"Envelope B5",
"Envelope C3",
"Envelope C4",
"Envelope C6",
"Envelope Monarch",
"Japanese Postcard",
"Japanese Double Postcard"
];
const pos = positions.indexOf(pageSize);
return pos === -1 ? 1 : pos + 1;
};
var replaceHeaderFooterTokens = (value) => {
const map = {
"&[Page]": "&P",
"&[Pages]": "&N",
"&[Date]": "&D",
"&[Time]": "&T",
"&[Tab]": "&A",
"&[Path]": "&Z",
"&[File]": "&F",
"&[Picture]": "&G"
};
for (const key of Object.keys(map)) {
value = value.replace(key, map[key]);
}
return value;
};
var getHeaderPosition = (position) => {
if (position === "Center") {
return "C";
}
if (position === "Right") {
return "R";
}
return "L";
};
var applyHeaderFontStyle = (headerString, font) => {
if (!font) {
return headerString;
}
headerString += "&"";
headerString += font.fontName || "Calibri";
if (font.bold !== font.italic) {
headerString += font.bold ? ",Bold" : ",Italic";
} else if (font.bold) {
headerString += ",Bold Italic";
} else {
headerString += ",Regular";
}
headerString += """;
if (font.size) {
headerString += `&${font.size}`;
}
if (font.strikeThrough) {
headerString += "&S";
}
if (font.underline) {
headerString += `&${font.underline === "Double" ? "E" : "U"}`;
}
if (font.color) {
headerString += `&K${font.color.replace("#", "").toUpperCase()}`;
}
return headerString;
};
var processHeaderFooterContent = (content, location, rule) => content.reduce((prev, curr, idx) => {
const pos = getHeaderPosition(curr.position);
const output = applyHeaderFontStyle(`${prev}&${pos}`, curr.font);
const PositionMap = ["Left", "Center", "Right"];
if (!curr.position) {
curr.position = PositionMap[idx];
}
const { image } = curr;
if (curr.value === "&[Picture]" && image) {
const imagePosition = `${pos}${location}${rule}`;
addXlsxHeaderFooterImageToMap(image, imagePosition);
}
return `${output}${(0, import_ag_grid_community7._escapeString)(replaceHeaderFooterTokens(curr.value))}`;
}, "");
var buildHeaderFooter = (headerFooterConfig) => {
const rules = ["all", "first", "even"];
const headersAndFooters = [];
rules.forEach((rule) => {
const headerFooter = headerFooterConfig[rule];
const namePrefix = rule === "all" ? "odd" : rule;
if (!headerFooter) {
return;
}
for (const key of Object.keys(headerFooter)) {
const value = headerFooter[key];
const nameSuffix = `${key.charAt(0).toUpperCase()}${key.slice(1)}`;
const location = key[0].toUpperCase();
if (value) {
const normalizedRule = rule === "all" ? "" : rule.toUpperCase();
headersAndFooters.push({
name: `${namePrefix}${nameSuffix}`,
properties: {
rawMap: { "xml:space": "preserve" }
},
textNode: processHeaderFooterContent(value, location, normalizedRule)
});
}
}
});
return headersAndFooters;
};
var addColumns = (columns) => {
return (params) => {
if (columns.length) {
params.children.push({
name: "cols",
children: columns.map((column) => column_default.getTemplate(column))
});
}
return params;
};
};
var addSheetData = (rows, sheetNumber) => {
return (params) => {
if (rows.length) {
params.children.push({
name: "sheetData",
children: rows.map((row, idx) => row_default.getTemplate(row, idx, sheetNumber))
});
}
return params;
};
};
var addMergeCells = (mergeCells) => {
return (params) => {
if (mergeCells.length) {
params.children.push({
name: "mergeCells",
properties: {
rawMap: {
count: mergeCells.length
}
},
children: mergeCells.map((mergedCell) => mergeCell_default.getTemplate(mergedCell))
});
}
return params;
};
};
var addPageMargins = (margins) => {
return (params) => {
const { top = 0.75, right = 0.7, bottom = 0.75, left = 0.7, header = 0.3, footer = 0.3 } = margins;
params.children.push({
name: "pageMargins",
properties: {
rawMap: { bottom, footer, header, left, right, top }
}
});
return params;
};
};
var addPageSetup = (pageSetup) => {
return (params) => {
if (pageSetup) {
params.children.push({
name: "pageSetup",
properties: {
rawMap: {
horizontalDpi: 0,
verticalDpi: 0,
orientation: getPageOrientation(pageSetup.orientation),
paperSize: getPageSize(pageSetup.pageSize)
}
}
});
}
return params;
};
};
var addHeaderFooter = (headerFooterConfig) => {
return (params) => {
if (!headerFooterConfig) {
return params;
}
const differentFirst = headerFooterConfig.first != null ? 1 : 0;
const differentOddEven = headerFooterConfig.even != null ? 1 : 0;
params.children.push({
name: "headerFooter",
properties: {
rawMap: {
differentFirst,
differentOddEven
}
},
children: buildHeaderFooter(headerFooterConfig)
});
return params;
};
};
var addExcelTableRel = (excelTable) => {
return (params) => {
if (excelTable) {
params.children.push({
name: "tableParts",
properties: {
rawMap: {
count: "1"
}
},
children: [
{
name: "tablePart",
properties: {
rawMap: {
"r:id": `rId${++params.rIdCounter}`
}
}
}
]
});
}
return params;
};
};
var addDrawingRel = (currentSheet2) => {
return (params) => {
const worksheetImages = XLSX_WORKSHEET_IMAGES.get(currentSheet2);
if (worksheetImages?.length) {
params.children.push({
name: "drawing",
properties: {
rawMap: {
"r:id": `rId${++params.rIdCounter}`
}
}
});
}
return params;
};
};
var addVmlDrawingRel = (currentSheet2) => {
return (params) => {
if (XLSX_WORKSHEET_HEADER_FOOTER_IMAGES.get(currentSheet2)) {
params.children.push({
name: "legacyDrawingHF",
properties: {
rawMap: {
"r:id": `rId${++params.rIdCounter}`
}
}
});
}
return params;
};
};
var getPane = (xSplit = 0, ySplit = 0) => {
const shouldSplit = xSplit > 0 || ySplit > 0;
return shouldSplit ? [
{
name: "pane",
properties: {
rawMap: {
state: shouldSplit ? "frozen" : void 0,
topLeftCell: shouldSplit ? `${getExcelColumnName(xSplit + 1)}${ySplit + 1}` : void 0,
xSplit: xSplit === 0 ? void 0 : xSplit,
ySplit: ySplit === 0 ? void 0 : ySplit
}
}
}
] : void 0;
};
var addSheetViews = (rtl = false, xSplit, ySplit) => {
return (params) => {
params.children.push({
name: "sheetViews",
children: [
{
name: "sheetView",
properties: {
rawMap: {
rightToLeft: rtl === true ? "1" : "0",
workbookViewId: "0"
}
},
children: getPane(xSplit, ySplit)
}
]
});
return params;
};
};
var addSheetPr = () => {
return (params) => {
params.children.push({
name: "sheetPr",
children: [
{
name: "outlinePr",
properties: {
rawMap: {
summaryBelow: 0
}
}
}
]
});
return params;
};
};
var addSheetFormatPr = (rows) => {
return (params) => {
const maxOutline = rows.reduce((prev, row) => {
if (row.outlineLevel && row.outlineLevel > prev) {
return row.outlineLevel;
}
return prev;
}, 0);
params.children.push({
name: "sheetFormatPr",
properties: {
rawMap: {
baseColWidth: 10,
defaultRowHeight: 16,
outlineLevelRow: maxOutline ? maxOutline : void 0
}
}
});
return params;
};
};
var worksheetFactory = {
getTemplate(params) {
const { worksheet, currentSheet: currentSheet2, config } = params;
const {
margins = {},
pageSetup,
headerFooterConfig,
suppressColumnOutline,
rightToLeft,
frozenRowCount,
frozenColumnCount
} = config;
const { table } = worksheet;
const { rows, columns } = table;
const mergedCells = columns && columns.length ? getMergedCellsAndAddColumnGroups(rows, columns, !!suppressColumnOutline) : [];
const worksheetExcelTables = XLSX_WORKSHEET_DATA_TABLES.get(currentSheet2);
const { children } = [
addSheetPr(),
addSheetViews(rightToLeft, frozenColumnCount, frozenRowCount),
addSheetFormatPr(rows),
addColumns(columns),
addSheetData(rows, currentSheet2 + 1),
addMergeCells(mergedCells),
addPageMargins(margins),
addPageSetup(pageSetup),
addHeaderFooter(headerFooterConfig),
addDrawingRel(currentSheet2),
addVmlDrawingRel(currentSheet2),
addExcelTableRel(worksheetExcelTables)
].reduce((composed, f) => f(composed), { children: [], rIdCounter: 0 });
return {
name: "worksheet",
properties: {
prefixedAttributes: [
{
prefix: "xmlns:",
map: {
r: "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
}
}
],
rawMap: {
xmlns: "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}
},
children
};
}
};
var worksheet_default = worksheetFactory;
// packages/ag-grid-enterprise/src/excelExport/excelXlsxFactory.ts
var XLSX_SHARED_STRINGS = /* @__PURE__ */ new Map();
var XLSX_SHEET_NAMES = [];
var XLSX_IMAGES = /* @__PURE__ */ new Map();
var XLSX_WORKSHEET_IMAGES = /* @__PURE__ */ new Map();
var XLSX_WORKSHEET_HEADER_FOOTER_IMAGES = /* @__PURE__ */ new Map();
var XLSX_WORKBOOK_IMAGE_IDS = /* @__PURE__ */ new Map();
var XLSX_WORKSHEET_IMAGE_IDS = /* @__PURE__ */ new Map();
var XLSX_WORKSHEET_DATA_TABLES = /* @__PURE__ */ new Map();
var DEFAULT_TABLE_DISPLAY_NAME = "AG-GRID-TABLE";
var XLSX_FACTORY_MODE = "SINGLE_SHEET";
function getXlsxFactoryMode() {
return XLSX_FACTORY_MODE;
}
function setXlsxFactoryMode(factoryMode) {
XLSX_FACTORY_MODE = factoryMode;
}
function createXlsxExcel(styles, worksheet, config) {
addSheetName(worksheet);
registerStyles(styles, XLSX_SHEET_NAMES.length);
const newConfig = Object.assign({}, config);
if (config.exportAsExcelTable) {
if (config.colModel.isPivotActive()) {
(0, import_ag_grid_community8._warn)(163, { featureName: "pivot mode" });
newConfig.exportAsExcelTable = false;
}
}
processTableConfig(worksheet, newConfig);
return createWorksheet(worksheet, newConfig);
}
function getXlsxSanitizedTableName(name) {
return name.replace(/^[^a-zA-Z_]+/, "_").replace(/\s/g, "_").replace(/[^a-zA-Z0-9_]/g, "_");
}
function addXlsxTableToSheet(sheetIndex, table) {
if (XLSX_WORKSHEET_DATA_TABLES.has(sheetIndex)) {
(0, import_ag_grid_community8._warn)(164);
return;
}
XLSX_WORKSHEET_DATA_TABLES.set(sheetIndex, table);
}
function processTableConfig(worksheet, config) {
const { exportAsExcelTable, prependContent, appendContent, colModel } = config;
if (!exportAsExcelTable) {
return;
}
const tableConfig = typeof exportAsExcelTable === "boolean" ? {} : exportAsExcelTable;
const {
name: nameFromConfig,
showColumnStripes,
showRowStripes,
showFilterButton,
highlightFirstColumn,
highlightLastColumn
} = tableConfig;
const tableName = getXlsxSanitizedTableName(nameFromConfig || DEFAULT_TABLE_DISPLAY_NAME);
const sheetIndex = XLSX_SHEET_NAMES.length - 1;
const { table } = worksheet;
const { rows, columns } = table;
const headerRowCount = (0, import_ag_grid_community8._getHeaderRowCount)(colModel);
const skipTopRows = prependContent ? prependContent.length : 0;
const removeFromBottom = appendContent ? appendContent.length : 0;
const tableRowCount = rows.length;
const tableColCount = columns.length;
const tableColumns = [];
const showFilterButtons = [];
for (let i = 0; i < tableColCount; i++) {
const col = columns[i];
tableColumns.push(col.displayName || "");
showFilterButtons.push(
showFilterButton === "match" || showFilterButton === void 0 ? col.filterAllowed ?? false : showFilterButton
);
}
if (!tableColumns || !tableColumns.length || !tableRowCount || !tableName) {
(0, import_ag_grid_community8._warn)(165);
return;
}
addXlsxTableToSheet(sheetIndex, {
name: `table${XLSX_WORKSHEET_DATA_TABLES.size + 1}`,
displayName: tableName,
columns: tableColumns,
showFilterButtons,
rowRange: [headerRowCount + skipTopRows, headerRowCount + (tableRowCount - headerRowCount) - removeFromBottom],
showRowStripes: showRowStripes ?? true,
showColumnStripes: showColumnStripes ?? false,
highlightFirstColumn: highlightFirstColumn ?? false,
highlightLastColumn: highlightLastColumn ?? false
});
}
function addXlsxHeaderFooterImageToMap(image, position) {
const sheetIndex = XLSX_SHEET_NAMES.length - 1;
const headerFooterImage = image;
headerFooterImage.headerFooterPosition = position;
buildImageMap({ imageToAdd: headerFooterImage, idx: sheetIndex });
let headerFooterImagesForSheet = XLSX_WORKSHEET_HEADER_FOOTER_IMAGES.get(sheetIndex);
if (!headerFooterImagesForSheet) {
headerFooterImagesForSheet = [];
XLSX_WORKSHEET_HEADER_FOOTER_IMAGES.set(sheetIndex, headerFooterImagesForSheet);
}
if (!headerFooterImagesForSheet.find((img) => img.id === image.id)) {
headerFooterImagesForSheet.push(image);
}
}
function addXlsxBodyImageToMap(image, rowIndex, col, columnsToExport, rowHeight) {
const sheetIndex = XLSX_SHEET_NAMES.length;
const { row, column } = image.position || {};
const calculatedImage = image;
if (columnsToExport) {
if (rowIndex != null && col != null && (!row || !column)) {
if (!image.position) {
image.position = {};
}
image.position = Object.assign({}, image.position, {
row: rowIndex,
column: columnsToExport.indexOf(col) + 1
});
}
setExcelImageTotalWidth(calculatedImage, columnsToExport);
setExcelImageTotalHeight(calculatedImage, rowHeight);
}
buildImageMap({ imageToAdd: calculatedImage, idx: sheetIndex });
let worksheetImageIdMap = XLSX_WORKSHEET_IMAGE_IDS.get(sheetIndex);
if (!worksheetImageIdMap) {
worksheetImageIdMap = /* @__PURE__ */ new Map();
XLSX_WORKSHEET_IMAGE_IDS.set(sheetIndex, worksheetImageIdMap);
}
const sheetImages = XLSX_WORKSHEET_IMAGES.get(sheetIndex);
if (!sheetImages) {
XLSX_WORKSHEET_IMAGES.set(sheetIndex, [calculatedImage]);
} else {
sheetImages.push(calculatedImage);
}
if (!worksheetImageIdMap.get(image.id)) {
worksheetImageIdMap.set(image.id, { index: worksheetImageIdMap.size, type: image.imageType });
}
}
function buildImageMap(params) {
const { imageToAdd, idx } = params;
const mappedImagesToSheet = XLSX_IMAGES.get(imageToAdd.id);
if (mappedImagesToSheet) {
const currentSheetImages = mappedImagesToSheet.find((currentImage) => currentImage.sheetId === idx);
if (currentSheetImages) {
currentSheetImages.image.push(imageToAdd);
} else {
mappedImagesToSheet.push({
sheetId: idx,
image: [imageToAdd]
});
}
} else {
XLSX_IMAGES.set(imageToAdd.id, [{ sheetId: idx, image: [imageToAdd] }]);
XLSX_WORKBOOK_IMAGE_IDS.set(imageToAdd.id, {
type: imageToAdd.imageType,
index: XLSX_WORKBOOK_IMAGE_IDS.size
});
}
}
function addSheetName(worksheet) {
const name = (0, import_ag_grid_community8._escapeString)(worksheet.name) || "";
let append = "";
while (XLSX_SHEET_NAMES.indexOf(`${name}${append}`) !== -1) {
if (append === "") {
append = "_1";
} else {
const curr = parseInt(append.slice(1), 10);
append = `_${curr + 1}`;
}
}
worksheet.name = `${name}${append}`;
XLSX_SHEET_NAMES.push(worksheet.name);
}
function getXlsxStringPosition(str) {
if (XLSX_SHARED_STRINGS.has(str)) {
return XLSX_SHARED_STRINGS.get(str);
}
XLSX_SHARED_STRINGS.set(str, XLSX_SHARED_STRINGS.size);
return XLSX_SHARED_STRINGS.size - 1;
}
function resetXlsxFactory() {
XLSX_SHARED_STRINGS.clear();
XLSX_IMAGES.clear();
XLSX_WORKSHEET_IMAGES.clear();
XLSX_WORKSHEET_HEADER_FOOTER_IMAGES.clear();
XLSX_WORKBOOK_IMAGE_IDS.clear();
XLSX_WORKSHEET_IMAGE_IDS.clear();
XLSX_WORKSHEET_DATA_TABLES.clear();
XLSX_SHEET_NAMES = [];
XLSX_FACTORY_MODE = "SINGLE_SHEET";
}
function createXlsxWorkbook(currentSheet2) {
return createXmlPart(workbook_default.getTemplate(XLSX_SHEET_NAMES, currentSheet2));
}
function createXlsxStylesheet(defaultFontSize) {
return createXmlPart(stylesheet_default.getTemplate(defaultFontSize));
}
function createXlsxSharedStrings() {
return createXmlPart(sharedStrings_default.getTemplate(XLSX_SHARED_STRINGS));
}
function createXlsxCore(author) {
return createXmlPart(core_default.getTemplate(author));
}
function createXlsxContentTypes(sheetLen) {
return createXmlPart(contentTypes_default.getTemplate(sheetLen));
}
function createXlsxRels() {
const rs = relationships_default.getTemplate([
{
Id: "rId1",
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
Target: "xl/workbook.xml"
},
{
Id: "rId2",
Type: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",
Target: "docProps/core.xml"
}
]);
return createXmlPart(rs);
}
function createXlsxTheme() {
return createXmlPart(office_default.getTemplate());
}
function createXlsxTable(dataTable, index) {
return createXmlPart(table_default.getTemplate(dataTable, index));
}
function createXlsxWorkbookRels(sheetLen) {
const worksheets = new Array(sheetLen).fill(void 0).map((v, i) => ({
Id: `rId${i + 1}`,
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
Target: `worksheets/sheet${i + 1}.xml`
}));
const rs = relationships_default.getTemplate([
...worksheets,
{
Id: `rId${sheetLen + 1}`,
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
Target: "theme/theme1.xml"
},
{
Id: `rId${sheetLen + 2}`,
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
Target: "styles.xml"
},
{
Id: `rId${sheetLen + 3}`,
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings",
Target: "sharedStrings.xml"
}
]);
return createXmlPart(rs);
}
function createXlsxDrawing(sheetIndex) {
return createXmlPart(drawing_default.getTemplate({ sheetIndex }));
}
function createXlsxDrawingRel(sheetIndex) {
const worksheetImageIds = XLSX_WORKSHEET_IMAGE_IDS.get(sheetIndex) || [];
const XMLArr = [];
for (const [key, value] of worksheetImageIds) {
const { index, type } = value;
XMLArr.push({
Id: `rId${index + 1}`,
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
Target: `../media/image${XLSX_WORKBOOK_IMAGE_IDS.get(key).index + 1}.${_normaliseImageExtension(type)}`
});
}
return createXmlPart(relationships_default.getTemplate(XMLArr));
}
function createXlsxVmlDrawing(sheetIndex) {
return createXmlPart(vmlDrawing_default.getTemplate({ sheetIndex }), true);
}
function createXlsxVmlDrawingRel(sheetIndex) {
const worksheetHeaderFooterImages = XLSX_WORKSHEET_HEADER_FOOTER_IMAGES.get(sheetIndex) || [];
const XMLArr = [];
for (let i = 0; i < worksheetHeaderFooterImages.length; i++) {
const headerFooterImage = worksheetHeaderFooterImages[i];
const workbookImage = XLSX_WORKBOOK_IMAGE_IDS.get(headerFooterImage.id);
if (!workbookImage) {
continue;
}
const { index, type } = workbookImage;
XMLArr.push({
Id: `rId${i + 1}`,
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
Target: `../media/image${index + 1}.${_normaliseImageExtension(type)}`
});
}
return createXmlPart(relationships_default.getTemplate(XMLArr));
}
function createXlsxRelationships({
drawingIndex,
vmlDrawingIndex,
tableName
} = {}) {
if (drawingIndex === void 0 && vmlDrawingIndex === void 0 && tableName === void 0) {
return "";
}
const config = [];
if (drawingIndex != null) {
config.push({
Id: `rId${config.length + 1}`,
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing",
Target: `../drawings/drawing${drawingIndex + 1}.xml`
});
}
if (vmlDrawingIndex != null) {
config.push({
Id: `rId${config.length + 1}`,
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing",
Target: `../drawings/vmlDrawing${vmlDrawingIndex + 1}.vml`
});
}
if (tableName != null) {
config.push({
Id: `rId${config.length + 1}`,
Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/table",
Target: `../tables/${tableName}.xml`
});
}
const rs = relationships_default.getTemplate(config);
return createXmlPart(rs);
}
function createWorksheet(worksheet, config) {
return createXmlPart(
worksheet_default.getTemplate({
worksheet,
currentSheet: XLSX_SHEET_NAMES.length - 1,
config
})
);
}
// packages/ag-grid-enterprise/src/excelExport/excelSerializingSession.ts
var ExcelSerializingSession = class extends import_ag_grid_community9.BaseGridSerializingSession {
constructor(config) {
super(config);
this.mixedStyles = {};
this.mixedStyleCounter = 0;
this.rows = [];
this.frozenRowCount = 0;
this.skipFrozenRows = false;
this.frozenColumnCount = 0;
this.skipFrozenColumns = false;
this.config = Object.assign({}, config);
this.stylesByIds = {};
this.config.baseExcelStyles.forEach((style) => {
this.stylesByIds[style.id] = style;
});
this.excelStyles = [...this.config.baseExcelStyles, { id: "_quotePrefix", quotePrefix: 1 }];
}
addCustomContent(customContent) {
customContent.forEach((row) => {
const rowLen = this.rows.length + 1;
let outlineLevel;
if (!this.config.suppressRowOutline && row.outlineLevel != null) {
outlineLevel = row.outlineLevel;
}
const rowObj = {
height: getHeightFromProperty(rowLen, row.height || this.config.rowHeight),
cells: (row.cells || []).map((cell, idx) => {
const image = this.addImage(rowLen, this.columnsToExport[idx], cell.data?.value);
let excelStyles = null;
if (cell.styleId) {
excelStyles = typeof cell.styleId === "string" ? [cell.styleId] : cell.styleId;
}
const excelStyleId = this.getStyleId(excelStyles);
if (image) {
return this.createCell(
excelStyleId,
this.getDataTypeForValue(image.value),
image.value == null ? "" : image.value
);
}
const value = cell.data?.value ?? "";
const type = this.getDataTypeForValue(value);
if (cell.mergeAcross) {
return this.createMergedCell(excelStyleId, type, value, cell.mergeAcross);
}
return this.createCell(excelStyleId, type, value);
}),
outlineLevel
};
if (row.collapsed != null) {
rowObj.collapsed = row.collapsed;
}
if (row.hidden != null) {
rowObj.hidden = row.hidden;
}
this.rows.push(rowObj);
});
}
onNewHeaderGroupingRow() {
const currentCells = [];
const { freezeRows, headerRowHeight } = this.config;
this.rows.push({
cells: currentCells,
height: getHeightFromProperty(this.rows.length + 1, headerRowHeight)
});
if (freezeRows) {
this.frozenRowCount++;
}
return {
onColumn: (columnGroup, header, index, span, collapsibleRanges) => {
const styleIds = this.config.styleLinker({
rowType: "HEADER_GROUPING",
rowIndex: 1,
value: `grouping-${header}`,
columnGroup
});
currentCells.push({
...this.createMergedCell(
this.getStyleId(styleIds),
this.getDataTypeForValue("string"),
header,
span
),
collapsibleRanges
});
}
};
}
onNewHeaderRow() {
const { freezeRows, headerRowHeight } = this.config;
if (freezeRows) {
this.frozenRowCount++;
}
return this.onNewRow(this.onNewHeaderColumn, headerRowHeight);
}
onNewBodyRow(node) {
const { freezeRows, rowHeight } = this.config;
if (!this.skipFrozenRows) {
if (freezeRows === "headersAndPinnedRows" && node?.rowPinned === "top") {
this.frozenRowCount++;
} else if (typeof freezeRows === "function") {
if (freezeRows((0, import_ag_grid_community9._addGridCommonParams)(this.gos, { node }))) {
this.frozenRowCount++;
} else {
this.skipFrozenRows = true;
}
} else {
this.skipFrozenRows = true;
}
}
const rowAccumulator = this.onNewRow(this.onNewBodyColumn, rowHeight);
if (node) {
this.addRowOutlineIfNecessary(node);
}
return rowAccumulator;
}
prepare(columnsToExport) {
super.prepare(columnsToExport);
this.columnsToExport = [...columnsToExport];
this.cols = columnsToExport.map((col, i) => this.convertColumnToExcel(col, i));
}
parse() {
const longestRow = this.rows.reduce((a, b) => Math.max(a, b.cells.length), 0);
while (this.cols.length < longestRow) {
this.cols.push(this.convertColumnToExcel(null, this.cols.length + 1));
}
const { config } = this;
let name;
if (config.sheetName != null) {
const { sheetName } = config;
const sheetNameValue = typeof sheetName === "function" ? sheetName((0, import_ag_grid_community9._addGridCommonParams)(this.gos, {})) : sheetName;
name = String(sheetNameValue).substring(0, 31);
} else {
name = "ag-grid";
}
const data = {
name,
table: {
columns: this.cols,
rows: this.rows
}
};
return this.createExcel(data);
}
addRowOutlineIfNecessary(node) {
const { gos, suppressRowOutline, rowGroupExpandState = "expanded" } = this.config;
const isGroupHideOpenParents = gos.get("groupHideOpenParents");
if (isGroupHideOpenParents || suppressRowOutline || node.level == null) {
return;
}
const padding = node.footer ? 1 : 0;
const currentRow = (0, import_ag_grid_community9._last)(this.rows);
const outlineLevel = Math.min(node.level + padding, 7);
currentRow.outlineLevel = outlineLevel;
if (rowGroupExpandState === "expanded") {
return;
}
const collapseAll = rowGroupExpandState === "collapsed";
if (node.isExpandable()) {
const isExpanded = !collapseAll && node.expanded;
currentRow.collapsed = !isExpanded;
}
currentRow.hidden = // always show the node if there is no parent to be expanded
!!node.parent && // or if it is a child of the root node
node.parent.level !== -1 && (collapseAll || this.isAnyParentCollapsed(node.parent));
}
isAnyParentCollapsed(node) {
while (node && node.level !== -1) {
if (!node.expanded) {
return true;
}
node = node.parent;
}
return false;
}
convertColumnToExcel(column, index) {
const columnWidth = this.config.columnWidth;
const headerValue = column ? this.extractHeaderValue(column) : void 0;
const displayName = headerValue ?? "";
const filterAllowed = column ? column.isFilterAllowed() : false;
if (columnWidth) {
if (typeof columnWidth === "number") {
return { width: columnWidth, displayName, filterAllowed };
}
return { width: columnWidth({ column, index }), displayName, filterAllowed };
}
if (column) {
const smallestUsefulWidth = 75;
return { width: Math.max(column.getActualWidth(), smallestUsefulWidth), displayName, filterAllowed };
}
return {
displayName,
filterAllowed
};
}
onNewHeaderColumn(rowIndex, currentCells) {
return (column) => {
const nameForCol = this.extractHeaderValue(column);
const styleIds = this.config.styleLinker({
rowType: "HEADER",
rowIndex,
value: nameForCol,
column
});
currentCells.push(
this.createCell(this.getStyleId(styleIds), this.getDataTypeForValue("string"), nameForCol)
);
};
}
onNewBodyColumn(rowIndex, currentCells) {
let skipCols = 0;
const { freezeColumns, rightToLeft } = this.config;
return (column, index, node) => {
if (skipCols > 0) {
skipCols -= 1;
return;
}
if (!this.skipFrozenColumns) {
const pinned = column.getPinned();
const isPinnedLeft = pinned === true || pinned === "left";
if (freezeColumns === "pinned" && pinned && isPinnedLeft !== rightToLeft) {
this.frozenColumnCount++;
} else if (typeof freezeColumns === "function" && freezeColumns((0, import_ag_grid_community9._addGridCommonParams)(this.gos, { column }))) {
this.frozenColumnCount++;
} else {
this.skipFrozenColumns = true;
}
}
const { value: valueForCell, valueFormatted } = this.extractRowCellValue(
column,
index,
rowIndex,
"excel",
node
);
const styleIds = this.config.styleLinker({
rowType: "BODY",
rowIndex,
value: valueForCell,
column,
node
});
const excelStyleId = this.getStyleId(styleIds);
const colSpan = column.getColSpan(node);
const addedImage = this.addImage(rowIndex, column, valueForCell);
if (addedImage) {
currentCells.push(
this.createCell(
excelStyleId,
this.getDataTypeForValue(addedImage.value),
addedImage.value == null ? "" : addedImage.value
)
);
} else if (colSpan > 1) {
skipCols = colSpan - 1;
currentCells.push(
this.createMergedCell(
excelStyleId,
this.getDataTypeForValue(valueForCell),
valueForCell,
colSpan - 1
)
);
} else {
currentCells.push(
this.createCell(excelStyleId, this.getDataTypeForValue(valueForCell), valueForCell, valueFormatted)
);
}
};
}
onNewRow(onNewColumnAccumulator, height) {
const currentCells = [];
this.rows.push({
cells: currentCells,
height: getHeightFromProperty(this.rows.length + 1, height)
});
return {
onColumn: onNewColumnAccumulator.bind(this, this.rows.length, currentCells)()
};
}
createExcel(data) {
const { excelStyles, config } = this;
if (this.frozenColumnCount) {
config.frozenColumnCount = this.frozenColumnCount;
}
if (this.frozenRowCount) {
config.frozenRowCount = this.frozenRowCount;
}
return createXlsxExcel(excelStyles, data, config);
}
getDataTypeForValue(valueForCell) {
if (valueForCell === void 0) {
return "empty";
}
let dataType = "s";
try {
if (this.isNumerical(valueForCell)) {
dataType = "n";
}
} catch (e) {
}
return dataType;
}
getTypeFromStyle(style, value) {
if (this.isFormula(value)) {
return "f";
}
if (style && style.dataType) {
switch (style.dataType.toLocaleLowerCase()) {
case "formula":
return "f";
case "string":
return "s";
case "number":
return "n";
case "datetime":
return "d";
case "error":
return "e";
case "boolean":
return "b";
default:
(0, import_ag_grid_community9._warn)(162, { id: style.id, dataType: style.dataType });
}
}
return null;
}
addImage(rowIndex, column, value) {
if (!this.config.addImageToCell) {
return;
}
const addedImage = this.config.addImageToCell(rowIndex, column, value);
if (!addedImage) {
return;
}
addXlsxBodyImageToMap(addedImage.image, rowIndex, column, this.columnsToExport, this.config.rowHeight);
return addedImage;
}
createCell(styleId, type, value, valueFormatted) {
const actualStyle = this.getStyleById(styleId);
if (!actualStyle?.dataType && type === "s" && valueFormatted != null) {
value = valueFormatted;
}
const processedType = this.getTypeFromStyle(actualStyle, value) || type;
const { value: processedValue, escaped } = this.getCellValue(processedType, value);
const styles = [];
if (actualStyle) {
styles.push(styleId);
}
if (escaped) {
styles.push("_quotePrefix");
}
styleId = this.getStyleId(styles) || void 0;
return {
styleId,
data: {
type: processedType,
value: processedValue
}
};
}
createMergedCell(styleId, type, value, numOfCells) {
const valueToUse = value == null ? "" : value;
return {
styleId: this.getStyleById(styleId) ? styleId : void 0,
data: {
type,
value: type === "s" ? getXlsxStringPosition(valueToUse).toString() : value
},
mergeAcross: numOfCells
};
}
getCellValue(type, value) {
let escaped = false;
if (value == null || type === "s" && value === "") {
return { value: "", escaped: false };
}
if (type === "s") {
if (value && value[0] === "'") {
escaped = true;
value = value.slice(1);
}
value = getXlsxStringPosition(value).toString();
} else if (type === "f") {
value = value.slice(1);
} else if (type === "n") {
const numberValue = Number(value);
if (isNaN(numberValue)) {
value = "";
} else if (value !== "") {
value = numberValue.toString();
}
}
return { value, escaped };
}
getStyleId(styleIds) {
if (!styleIds || !styleIds.length) {
return null;
}
if (styleIds.length === 1) {
return styleIds[0];
}
const key = styleIds.join("-");
if (!this.mixedStyles[key]) {
this.addNewMixedStyle(styleIds);
}
return this.mixedStyles[key].excelID;
}
deepCloneObject(object) {
return JSON.parse(JSON.stringify(object));
}
addNewMixedStyle(styleIds) {
this.mixedStyleCounter += 1;
const excelId = `mixedStyle${this.mixedStyleCounter}`;
const resultantStyle = {};
for (const styleId of styleIds) {
for (const excelStyle of this.excelStyles) {
if (excelStyle.id === styleId) {
(0, import_ag_grid_community9._mergeDeep)(resultantStyle, this.deepCloneObject(excelStyle));
}
}
}
resultantStyle.id = excelId;
const key = styleIds.join("-");
this.mixedStyles[key] = {
excelID: excelId,
key,
result: resultantStyle
};
this.excelStyles.push(resultantStyle);
this.stylesByIds[excelId] = resultantStyle;
}
isFormula(value) {
if (value == null) {
return false;
}
return this.config.autoConvertFormulas && value.toString().startsWith("=");
}
isNumerical(value) {
if (typeof value === "bigint") {
return true;
}
return isFinite(value) && value !== "" && !isNaN(parseFloat(value));
}
getStyleById(styleId) {
if (styleId == null) {
return null;
}
return this.stylesByIds[styleId] || null;
}
};
// packages/ag-grid-enterprise/src/excelExport/zipContainer/zipContainerHelper.ts
var import_ag_grid_community10 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/excelExport/zipContainer/compress.ts
var compressBlob = async (data) => {
let chunksSize = 0;
const chunks = [];
const writeCompressedData = new WritableStream({
write: (chunk) => {
chunks.push(chunk);
chunksSize += chunk.length;
}
});
const readable = new ReadableStream({
start: (controller) => {
const reader = new FileReader();
reader.onload = (e) => {
if (e.target?.result) {
controller.enqueue(e.target.result);
}
controller.close();
};
reader.readAsArrayBuffer(data);
}
});
const compressStream = new window.CompressionStream("deflate-raw");
await readable.pipeThrough(compressStream).pipeTo(writeCompressedData);
return {
size: chunksSize,
content: new Blob(chunks)
};
};
var deflateLocalFile = async (rawContent) => {
const contentAsBlob = new Blob([rawContent]);
const { size: compressedSize, content: compressedContent } = await compressBlob(contentAsBlob);
const compressedContentAsUint8Array = new Uint8Array(await compressedContent.arrayBuffer());
return {
size: compressedSize,
content: compressedContentAsUint8Array
};
};
// packages/ag-grid-enterprise/src/excelExport/zipContainer/convert.ts
var convertTime = (date) => {
let time = date.getHours();
time <<= 6;
time = time | date.getMinutes();
time <<= 5;
time = time | date.getSeconds() / 2;
return time;
};
var convertDate = (date) => {
let dt = date.getFullYear() - 1980;
dt <<= 4;
dt = dt | date.getMonth() + 1;
dt <<= 5;
dt = dt | date.getDate();
return dt;
};
function convertDecToHex(number, bytes) {
let hex = "";
for (let i = 0; i < bytes; i++) {
hex += String.fromCharCode(number & 255);
number >>>= 8;
}
return hex;
}
// packages/ag-grid-enterprise/src/excelExport/zipContainer/crcTable.ts
var getCrcFromCrc32TableAndByteArray = (content) => {
if (!content.length) {
return 0;
}
let crc = 0 ^ -1;
let j = 0;
let k = 0;
let l = 0;
for (let i = 0; i < content.length; i++) {
j = content[i];
k = (crc ^ j) & 255;
l = crcTable[k];
crc = crc >>> 8 ^ l;
}
return crc ^ -1;
};
var getCrcFromCrc32Table = (content) => {
if (!content.length) {
return 0;
}
if (typeof content === "string") {
return getCrcFromCrc32TableAndByteArray(new TextEncoder().encode(content));
}
return getCrcFromCrc32TableAndByteArray(content);
};
var crcTable = /* @__PURE__ */ new Uint32Array([
0,
1996959894,
3993919788,
2567524794,
124634137,
1886057615,
3915621685,
2657392035,
249268274,
2044508324,
3772115230,
2547177864,
162941995,
2125561021,
3887607047,
2428444049,
498536548,
1789927666,
4089016648,
2227061214,
450548861,
1843258603,
4107580753,
2211677639,
325883990,
1684777152,
4251122042,
2321926636,
335633487,
1661365465,
4195302755,
2366115317,
997073096,
1281953886,
3579855332,
2724688242,
1006888145,
1258607687,
3524101629,
2768942443,
901097722,
1119000684,
3686517206,
2898065728,
853044451,
1172266101,
3705015759,
2882616665,
651767980,
1373503546,
3369554304,
3218104598,
565507253,
1454621731,
3485111705,
3099436303,
671266974,
1594198024,
3322730930,
2970347812,
795835527,
1483230225,
3244367275,
3060149565,
1994146192,
31158534,
2563907772,
4023717930,
1907459465,
112637215,
2680153253,
3904427059,
2013776290,
251722036,
2517215374,
3775830040,
2137656763,
141376813,
2439277719,
3865271297,
1802195444,
476864866,
2238001368,
4066508878,
1812370925,
453092731,
2181625025,
4111451223,
1706088902,
314042704,
2344532202,
4240017532,
1658658271,
366619977,
2362670323,
4224994405,
1303535960,
984961486,
2747007092,
3569037538,
1256170817,
1037604311,
2765210733,
3554079995,
1131014506,
879679996,
2909243462,
3663771856,
1141124467,
855842277,
2852801631,
3708648649,
1342533948,
654459306,
3188396048,
3373015174,
1466479909,
544179635,
3110523913,
3462522015,
1591671054,
702138776,
2966460450,
3352799412,
1504918807,
783551873,
3082640443,
3233442989,
3988292384,
2596254646,
62317068,
1957810842,
3939845945,
2647816111,
81470997,
1943803523,
3814918930,
2489596804,
225274430,
2053790376,
3826175755,
2466906013,
167816743,
2097651377,
4027552580,
2265490386,
503444072,
1762050814,
4150417245,
2154129355,
426522225,
1852507879,
4275313526,
2312317920,
282753626,
1742555852,
4189708143,
2394877945,
397917763,
1622183637,
3604390888,
2714866558,
953729732,
1340076626,
3518719985,
2797360999,
1068828381,
1219638859,
3624741850,
2936675148,
906185462,
1090812512,
3747672003,
2825379669,
829329135,
1181335161,
3412177804,
3160834842,
628085408,
1382605366,
3423369109,
3138078467,
570562233,
1426400815,
3317316542,
2998733608,
733239954,
1555261956,
3268935591,
3050360625,
752459403,
1541320221,
2607071920,
3965973030,
1969922972,
40735498,
2617837225,
3943577151,
1913087877,
83908371,
2512341634,
3803740692,
2075208622,
213261112,
2463272603,
3855990285,
2094854071,
198958881,
2262029012,
4057260610,
1759359992,
534414190,
2176718541,
4139329115,
1873836001,
414664567,
2282248934,
4279200368,
1711684554,
285281116,
2405801727,
4167216745,
1634467795,
376229701,
2685067896,
3608007406,
1308918612,
956543938,
2808555105,
3495958263,
1231636301,
1047427035,
2932959818,
3654703836,
1088359270,
936918e3,
2847714899,
3736837829,
1202900863,
817233897,
3183342108,
3401237130,
1404277552,
615818150,
3134207493,
3453421203,
1423857449,
601450431,
3009837614,
3294710456,
1567103746,
711928724,
3020668471,
3272380065,
1510334235,
755167117
]);
// packages/ag-grid-enterprise/src/excelExport/zipContainer/zipContainerHelper.ts
function _utf8_encode(s) {
const stringFromCharCode = String.fromCharCode;
function ucs2decode(string) {
const output = [];
if (!string) {
return [];
}
const len = string.length;
let counter = 0;
let value;
let extra;
while (counter < len) {
value = string.charCodeAt(counter++);
if (value >= 55296 && value <= 56319 && counter < len) {
extra = string.charCodeAt(counter++);
if ((extra & 64512) == 56320) {
output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
} else {
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
function checkScalarValue(point) {
if (point >= 55296 && point <= 57343) {
throw Error((0, import_ag_grid_community10._errMsg)(255, { point }));
}
}
function createByte(point, shift) {
return stringFromCharCode(point >> shift & 63 | 128);
}
function encodeCodePoint(point) {
if ((point & 4294967168) == 0) {
return stringFromCharCode(point);
}
let symbol = "";
if ((point & 4294965248) == 0) {
symbol = stringFromCharCode(point >> 6 & 31 | 192);
} else if ((point & 4294901760) == 0) {
checkScalarValue(point);
symbol = stringFromCharCode(point >> 12 & 15 | 224);
symbol += createByte(point, 6);
} else if ((point & 4292870144) == 0) {
symbol = stringFromCharCode(point >> 18 & 7 | 240);
symbol += createByte(point, 12);
symbol += createByte(point, 6);
}
symbol += stringFromCharCode(point & 63 | 128);
return symbol;
}
const codePoints = ucs2decode(s);
const length = codePoints.length;
let index = -1;
let codePoint;
let byteString = "";
while (++index < length) {
codePoint = codePoints[index];
byteString += encodeCodePoint(codePoint);
}
return byteString;
}
var getHeaders = (currentFile, isCompressed, offset, rawSize, rawContent, deflatedSize) => {
const { content, path, created: creationDate } = currentFile;
const time = convertTime(creationDate);
const dt = convertDate(creationDate);
const crcFlag = getCrcFromCrc32Table(rawContent);
const zipSize = deflatedSize !== void 0 ? deflatedSize : rawSize;
const utfPath = _utf8_encode(path);
const isUTF8 = utfPath !== path;
let extraFields = "";
if (isUTF8) {
const uExtraFieldPath = convertDecToHex(1, 1) + convertDecToHex(getCrcFromCrc32Table(utfPath), 4) + utfPath;
extraFields = "up" + convertDecToHex(uExtraFieldPath.length, 2) + uExtraFieldPath;
}
const commonHeader = "\0" + // version needed to extract
(isUTF8 ? "\0\b" : "\0\0") + // Language encoding flag (EFS) (12th bit turned on)
convertDecToHex(isCompressed ? 8 : 0, 2) + // As per ECMA-376 Part 2 specs
convertDecToHex(time, 2) + // last modified time
convertDecToHex(dt, 2) + // last modified date
convertDecToHex(zipSize ? crcFlag : 0, 4) + convertDecToHex(deflatedSize ?? rawSize, 4) + // compressed size
convertDecToHex(rawSize, 4) + // uncompressed size
convertDecToHex(utfPath.length, 2) + // file name length
convertDecToHex(extraFields.length, 2);
const localFileHeader = "PK" + commonHeader + utfPath + extraFields;
const centralDirectoryHeader = "PK\0" + commonHeader + // file header
"\0\0\0\0\0\0" + (content ? "\0\0\0\0" : "\0\0\0") + // external file attributes
convertDecToHex(offset, 4) + // relative offset of local header
utfPath + // file name
extraFields;
return {
localFileHeader: Uint8Array.from(localFileHeader, (c) => c.charCodeAt(0)),
centralDirectoryHeader: Uint8Array.from(centralDirectoryHeader, (c) => c.charCodeAt(0))
};
};
var getDecodedContent = (content) => {
let contentToUse;
if (typeof content === "string") {
const base64String = atob(content.split(";base64,")[1]);
contentToUse = Uint8Array.from(base64String, (c) => c.charCodeAt(0));
} else {
contentToUse = content;
}
return {
size: contentToUse.length,
content: contentToUse
};
};
var getDeflatedHeaderAndContent = async (currentFile, offset) => {
const { content } = currentFile;
const { size, content: rawContent } = !content ? { size: 0, content: Uint8Array.from([]) } : getDecodedContent(content);
let deflatedContent = void 0;
let deflatedSize = void 0;
let deflationPerformed = false;
const shouldDeflate = currentFile.type === "file" && rawContent && size > 0;
if (shouldDeflate) {
const result = await deflateLocalFile(rawContent);
deflatedContent = result.content;
deflatedSize = result.size;
deflationPerformed = true;
}
const headers = getHeaders(currentFile, deflationPerformed, offset, size, rawContent, deflatedSize);
return {
...headers,
content: deflatedContent || rawContent,
isCompressed: deflationPerformed
};
};
var getHeaderAndContent = (currentFile, offset) => {
const { content } = currentFile;
const { content: rawContent } = !content ? { content: Uint8Array.from([]) } : getDecodedContent(content);
const headers = getHeaders(currentFile, false, offset, rawContent.length, rawContent, void 0);
return {
...headers,
content: rawContent,
isCompressed: false
};
};
var buildCentralDirectoryEnd = (tLen, cLen, lLen) => {
const str = "PK\0\0\0\0" + convertDecToHex(tLen, 2) + // total number of entries in the central folder
convertDecToHex(tLen, 2) + // total number of entries in the central folder
convertDecToHex(cLen, 4) + // size of the central folder
convertDecToHex(lLen, 4) + // central folder start offset
"\0\0";
return Uint8Array.from(str, (c) => c.charCodeAt(0));
};
// packages/ag-grid-enterprise/src/excelExport/zipContainer/zipContainer.ts
var ZipContainer = class {
constructor() {
this.folders = [];
this.files = [];
}
addFolders(paths) {
paths.forEach(this.addFolder.bind(this));
}
addFolder(path) {
this.folders.push({
path,
created: /* @__PURE__ */ new Date(),
isBase64: false,
type: "folder"
});
}
addFile(path, content, isBase64 = false) {
this.files.push({
path,
created: /* @__PURE__ */ new Date(),
content: isBase64 ? content : new TextEncoder().encode(content),
isBase64,
type: "file"
});
}
async getZipFile(mimeType = "application/zip") {
const textOutput = await this.buildCompressedFileStream();
this.clearStream();
return new Blob([textOutput], { type: mimeType });
}
getUncompressedZipFile(mimeType = "application/zip") {
const textOutput = this.buildFileStream();
this.clearStream();
return new Blob([textOutput], { type: mimeType });
}
clearStream() {
this.folders = [];
this.files = [];
}
packageFiles(files) {
let fileLen = 0;
let folderLen = 0;
for (const currentFile of files) {
const { localFileHeader, centralDirectoryHeader, content } = currentFile;
fileLen += localFileHeader.length + content.length;
folderLen += centralDirectoryHeader.length;
}
const fileData = new Uint8Array(fileLen);
const folderData = new Uint8Array(folderLen);
let fileOffset = 0;
let folderOffset = 0;
for (const currentFile of files) {
const { localFileHeader, centralDirectoryHeader, content } = currentFile;
fileData.set(localFileHeader, fileOffset);
fileOffset += localFileHeader.length;
fileData.set(content, fileOffset);
fileOffset += content.length;
folderData.set(centralDirectoryHeader, folderOffset);
folderOffset += centralDirectoryHeader.length;
}
const folderEnd = buildCentralDirectoryEnd(files.length, folderLen, fileLen);
const result = new Uint8Array(fileData.length + folderData.length + folderEnd.length);
result.set(fileData);
result.set(folderData, fileData.length);
result.set(folderEnd, fileData.length + folderData.length);
return result;
}
async buildCompressedFileStream() {
const totalFiles = [...this.folders, ...this.files];
const readyFiles = [];
let lL = 0;
for (const currentFile of totalFiles) {
const output = await getDeflatedHeaderAndContent(currentFile, lL);
const { localFileHeader, content } = output;
readyFiles.push(output);
lL += localFileHeader.length + content.length;
}
return this.packageFiles(readyFiles);
}
buildFileStream() {
const totalFiles = [...this.folders, ...this.files];
const readyFiles = [];
let lL = 0;
for (const currentFile of totalFiles) {
const readyFile = getHeaderAndContent(currentFile, lL);
const { localFileHeader, content } = readyFile;
readyFiles.push(readyFile);
lL += localFileHeader.length + content.length;
}
return this.packageFiles(readyFiles);
}
};
// packages/ag-grid-enterprise/src/excelExport/excelCreator.ts
var createExcelXMLCoreFolderStructure = (zipContainer) => {
zipContainer.addFolders(["_rels/", "docProps/", "xl/", "xl/theme/", "xl/_rels/", "xl/worksheets/"]);
if (!XLSX_IMAGES.size) {
return;
}
zipContainer.addFolders(["xl/worksheets/_rels", "xl/drawings/", "xl/drawings/_rels", "xl/media/"]);
let imgCounter = 0;
XLSX_IMAGES.forEach((value) => {
const firstImage = value[0].image[0];
const { base64, imageType } = firstImage;
zipContainer.addFile(`xl/media/image${++imgCounter}.${_normaliseImageExtension(imageType)}`, base64, true);
});
};
var createExcelXmlWorksheets = (zipContainer, data) => {
let imageRelationCounter = 0;
let headerFooterImageCounter = 0;
for (let i = 0; i < data.length; i++) {
const value = data[i];
zipContainer.addFile(`xl/worksheets/sheet${i + 1}.xml`, value, false);
const hasImages = XLSX_IMAGES.size > 0 && XLSX_WORKSHEET_IMAGES.has(i);
const tableData = XLSX_WORKSHEET_DATA_TABLES.size > 0 && XLSX_WORKSHEET_DATA_TABLES.get(i);
const hasHeaderFooterImages = XLSX_IMAGES.size && XLSX_WORKSHEET_HEADER_FOOTER_IMAGES.has(i);
if (!hasImages && !tableData && !hasHeaderFooterImages) {
continue;
}
let tableName;
let drawingIndex;
let vmlDrawingIndex;
if (hasImages) {
createExcelXmlDrawings(zipContainer, i, imageRelationCounter);
drawingIndex = imageRelationCounter;
imageRelationCounter++;
}
if (hasHeaderFooterImages) {
createExcelVmlDrawings(zipContainer, i, headerFooterImageCounter);
vmlDrawingIndex = headerFooterImageCounter;
headerFooterImageCounter++;
}
if (tableData) {
tableName = tableData.name;
}
const worksheetRelFile = `xl/worksheets/_rels/sheet${i + 1}.xml.rels`;
zipContainer.addFile(
worksheetRelFile,
createXlsxRelationships({
tableName,
drawingIndex,
vmlDrawingIndex
})
);
}
};
var createExcelXmlDrawings = (zipContainer, sheetIndex, drawingIndex) => {
const drawingFolder = "xl/drawings";
const drawingFileName = `${drawingFolder}/drawing${drawingIndex + 1}.xml`;
const relFileName = `${drawingFolder}/_rels/drawing${drawingIndex + 1}.xml.rels`;
zipContainer.addFile(relFileName, createXlsxDrawingRel(sheetIndex));
zipContainer.addFile(drawingFileName, createXlsxDrawing(sheetIndex));
};
var createExcelVmlDrawings = (zipContainer, sheetIndex, drawingIndex) => {
const drawingFolder = "xl/drawings";
const drawingFileName = `${drawingFolder}/vmlDrawing${drawingIndex + 1}.vml`;
const relFileName = `${drawingFolder}/_rels/vmlDrawing${drawingIndex + 1}.vml.rels`;
zipContainer.addFile(drawingFileName, createXlsxVmlDrawing(sheetIndex));
zipContainer.addFile(relFileName, createXlsxVmlDrawingRel(sheetIndex));
};
var createExcelXmlTables = (zipContainer) => {
const tablesDataByWorksheet = XLSX_WORKSHEET_DATA_TABLES;
const worksheetKeys = Array.from(tablesDataByWorksheet.keys());
for (let i = 0; i < worksheetKeys.length; i++) {
const sheetIndex = worksheetKeys[i];
const table = tablesDataByWorksheet.get(sheetIndex);
if (!table) {
continue;
}
zipContainer.addFile(`xl/tables/${table.name}.xml`, createXlsxTable(table, i));
}
};
var createExcelXmlCoreSheets = (zipContainer, fontSize, author, sheetLen, activeTab) => {
zipContainer.addFile("xl/workbook.xml", createXlsxWorkbook(activeTab));
zipContainer.addFile("xl/styles.xml", createXlsxStylesheet(fontSize));
zipContainer.addFile("xl/sharedStrings.xml", createXlsxSharedStrings());
zipContainer.addFile("xl/theme/theme1.xml", createXlsxTheme());
zipContainer.addFile("xl/_rels/workbook.xml.rels", createXlsxWorkbookRels(sheetLen));
zipContainer.addFile("docProps/core.xml", createXlsxCore(author));
zipContainer.addFile("[Content_Types].xml", createXlsxContentTypes(sheetLen));
zipContainer.addFile("_rels/.rels", createXlsxRels());
};
var createExcelFileForExcel = (zipContainer, data, options = {}) => {
if (!data || data.length === 0) {
(0, import_ag_grid_community11._warn)(159);
resetXlsxFactory();
return false;
}
const { fontSize = 11, author = "AG Grid", activeTab = 0 } = options;
const len = data.length;
const activeTabWithinBounds = Math.max(Math.min(activeTab, len - 1), 0);
createExcelXMLCoreFolderStructure(zipContainer);
createExcelXmlTables(zipContainer);
createExcelXmlWorksheets(zipContainer, data);
createExcelXmlCoreSheets(zipContainer, fontSize, author, len, activeTabWithinBounds);
resetXlsxFactory();
return true;
};
var getMultipleSheetsAsExcelCompressed = (params) => {
const { data, fontSize, author, activeSheetIndex } = params;
const mimeType = params.mimeType || "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
const zipContainer = new ZipContainer();
if (!createExcelFileForExcel(zipContainer, data, {
author,
fontSize,
activeTab: activeSheetIndex
})) {
return Promise.resolve(void 0);
}
return zipContainer.getZipFile(mimeType);
};
var getMultipleSheetsAsExcel = (params) => {
const { data, fontSize, author, activeSheetIndex } = params;
const mimeType = params.mimeType || "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
const zipContainer = new ZipContainer();
if (!createExcelFileForExcel(zipContainer, data, {
author,
fontSize,
activeTab: activeSheetIndex
})) {
return;
}
return zipContainer.getUncompressedZipFile(mimeType);
};
var exportMultipleSheetsAsExcel = (params) => {
const { fileName = "export.xlsx" } = params;
getMultipleSheetsAsExcelCompressed(params).then((contents) => {
if (contents) {
const downloadFileName = typeof fileName === "function" ? fileName() : fileName;
(0, import_ag_grid_community11._downloadFile)(downloadFileName, contents);
}
});
};
var ExcelCreator = class extends import_ag_grid_community11.BaseCreator {
constructor() {
super(...arguments);
this.beanName = "excelCreator";
}
getMergedParams(params) {
const baseParams = this.gos.get("defaultExcelExportParams");
return Object.assign({}, baseParams, params);
}
export(userParams) {
if (this.isExportSuppressed()) {
(0, import_ag_grid_community11._warn)(160);
return;
}
const mergedParams = this.getMergedParams(userParams);
const data = this.getData(mergedParams);
const exportParams = {
data: [data],
fontSize: mergedParams.fontSize,
author: mergedParams.author,
mimeType: mergedParams.mimeType
};
this.packageCompressedFile(exportParams).then((packageFile) => {
if (packageFile) {
const { fileName } = mergedParams;
const providedFileName = typeof fileName === "function" ? fileName((0, import_ag_grid_community11._addGridCommonParams)(this.gos, {})) : fileName;
(0, import_ag_grid_community11._downloadFile)(this.getFileName(providedFileName), packageFile);
}
});
}
exportDataAsExcel(params) {
this.export(params);
}
getDataAsExcel(params) {
const mergedParams = this.getMergedParams(params);
const data = this.getData(mergedParams);
const exportParams = {
data: [data],
fontSize: mergedParams.fontSize,
author: mergedParams.author,
mimeType: mergedParams.mimeType
};
return this.packageFile(exportParams);
}
setFactoryMode(factoryMode) {
setXlsxFactoryMode(factoryMode);
}
getFactoryMode() {
return getXlsxFactoryMode();
}
getSheetDataForExcel(params) {
const mergedParams = this.getMergedParams(params);
return this.getData(mergedParams);
}
getMultipleSheetsAsExcel(params) {
return getMultipleSheetsAsExcel(params);
}
exportMultipleSheetsAsExcel(params) {
exportMultipleSheetsAsExcel(params);
}
getDefaultFileExtension() {
return "xlsx";
}
createSerializingSession(params) {
const { colModel, colNames, rowGroupColsSvc, valueSvc, gos } = this.beans;
const config = {
...params,
colModel,
colNames,
rowGroupColsSvc,
valueSvc,
gos,
suppressRowOutline: params.suppressRowOutline || params.skipRowGroups,
headerRowHeight: params.headerRowHeight || params.rowHeight,
baseExcelStyles: gos.get("excelStyles") || [],
rightToLeft: params.rightToLeft ?? gos.get("enableRtl"),
styleLinker: this.styleLinker.bind(this)
};
return new ExcelSerializingSession(config);
}
styleLinker(params) {
const { rowType, rowIndex, value, column, columnGroup, node } = params;
const isHeader = rowType === "HEADER";
const isGroupHeader = rowType === "HEADER_GROUPING";
const col = isHeader ? column : columnGroup;
let headerClasses = [];
const { gos, cellStyles } = this.beans;
if (isHeader || isGroupHeader) {
headerClasses.push("header");
if (isGroupHeader) {
headerClasses.push("headerGroup");
}
if (col) {
headerClasses = headerClasses.concat(
(0, import_ag_grid_community11._getHeaderClassesFromColDef)(
col.getDefinition(),
gos,
column || null,
columnGroup || null
)
);
}
return headerClasses;
}
const styles = gos.get("excelStyles");
const applicableStyles = ["cell"];
if (!styles || !styles.length) {
return applicableStyles;
}
const styleIds = styles.map((it) => {
return it.id;
});
const colDef = column.getDefinition();
cellStyles?.processAllCellClasses(
colDef,
(0, import_ag_grid_community11._addGridCommonParams)(gos, {
value,
data: node.data,
node,
colDef,
column,
rowIndex
}),
(className) => {
if (styleIds.indexOf(className) > -1) {
applicableStyles.push(className);
}
}
);
return applicableStyles.sort((left, right) => {
return styleIds.indexOf(left) < styleIds.indexOf(right) ? -1 : 1;
});
}
isExportSuppressed() {
return this.gos.get("suppressExcelExport");
}
packageCompressedFile(params) {
return getMultipleSheetsAsExcelCompressed(params);
}
packageFile(params) {
return getMultipleSheetsAsExcel(params);
}
};
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterModule.ts
var import_ag_grid_community40 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/version.ts
var VERSION = "34.1.2";
// packages/ag-grid-enterprise/src/agGridEnterpriseModule.ts
var EnterpriseCoreModule = {
moduleName: "EnterpriseCore",
version: VERSION,
beans: [GridLicenseManager],
icons: {
// accordion open (filter tool panel group, charts group)
accordionOpen: "tree-open",
// accordion closed (filter tool panel group, charts group)
accordionClosed: "tree-closed",
// accordion indeterminate - shown when some children are expanded and
// others are collapsed (filter tool panel group, charts group)
accordionIndeterminate: "tree-indeterminate",
// dialog title bar
close: "cross",
// X (remove) on column 'pill' after adding it to a drop zone list
cancel: "cancel",
// 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",
// drag handle used to pick up draggable columns
columnDrag: "grip"
},
dependsOn: []
};
// packages/ag-grid-enterprise/src/advancedFilter/advanced-filter.css-GENERATED.ts
var advancedFilterCSS = (
/*css*/
`.ag-advanced-filter-header{align-items:center;background-color:var(--ag-header-background-color);border-bottom:var(--ag-header-row-border);display:flex;position:relative}.ag-advanced-filter{align-items:center;display:flex;width:100%}.ag-advanced-filter-buttons{display:contents}.ag-advanced-filter-header-cell{height:100%;padding-left:var(--ag-cell-horizontal-padding);padding-right:var(--ag-cell-horizontal-padding)}.ag-advanced-filter-apply-button,.ag-advanced-filter-builder-button{align-items:center;background-color:unset;border:0;display:flex;font-size:var(--ag-font-size);font-weight:600;line-height:normal;padding:var(--ag-spacing);white-space:nowrap;&:where(:not(:disabled)){cursor:pointer;&:hover{background-color:var(--ag-row-hover-color)}}}:where(.ag-ltr) .ag-advanced-filter-apply-button,:where(.ag-ltr) .ag-advanced-filter-builder-button{margin-left:calc(var(--ag-spacing)*2)}:where(.ag-rtl) .ag-advanced-filter-apply-button,:where(.ag-rtl) .ag-advanced-filter-builder-button{margin-right:calc(var(--ag-spacing)*2)}:where(.ag-ltr) .ag-advanced-filter-builder-button-label{margin-left:var(--ag-spacing)}:where(.ag-rtl) .ag-advanced-filter-builder-button-label{margin-right:var(--ag-spacing)}.ag-advanced-filter-builder{display:flex;flex-direction:column;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:100%}.ag-advanced-filter-builder-list{flex:1;overflow:auto}.ag-advanced-filter-builder-button-panel{border-top:var(--ag-advanced-filter-builder-button-bar-border);display:flex;justify-content:flex-end;padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding)}:where(.ag-ltr) .ag-advanced-filter-builder-apply-button,:where(.ag-ltr) .ag-advanced-filter-builder-cancel-button{margin-left:calc(var(--ag-spacing)*2)}:where(.ag-rtl) .ag-advanced-filter-builder-apply-button,:where(.ag-rtl) .ag-advanced-filter-builder-cancel-button{margin-right:calc(var(--ag-spacing)*2)}.ag-advanced-filter-builder-item-wrapper{align-items:center;display:flex;flex:1 1 auto;justify-content:space-between;overflow:hidden}:where(.ag-ltr) .ag-advanced-filter-builder-item-wrapper{padding-left:calc(var(--ag-icon-size)/2);padding-right:var(--ag-icon-size)}:where(.ag-rtl) .ag-advanced-filter-builder-item-wrapper{padding-left:var(--ag-icon-size);padding-right:calc(var(--ag-icon-size)/2)}:where(.ag-virtual-list-viewport .ag-advanced-filter-builder-item-wrapper) .ag-tab-guard{position:absolute}.ag-advanced-filter-builder-item-tree-lines>*{width:var(--ag-advanced-filter-builder-indent-size)}.ag-advanced-filter-builder-item-tree-line-root{width:var(--ag-icon-size);&:before{height:50%;top:50%}}.ag-advanced-filter-builder-item-tree-line-horizontal,.ag-advanced-filter-builder-item-tree-line-vertical,.ag-advanced-filter-builder-item-tree-line-vertical-bottom,.ag-advanced-filter-builder-item-tree-line-vertical-top{align-items:center;display:flex;height:100%;position:relative;&:after,&:before{content:"";height:100%;position:absolute}}.ag-advanced-filter-builder-item-tree-line-horizontal:after{border-bottom:var(--ag-border-width) solid var(--ag-border-color);height:50%;top:0;width:calc(var(--ag-advanced-filter-builder-indent-size) - var(--ag-icon-size))}:where(.ag-ltr) .ag-advanced-filter-builder-item-tree-line-horizontal:after{left:calc(var(--ag-icon-size)/2)}:where(.ag-rtl) .ag-advanced-filter-builder-item-tree-line-horizontal:after{right:calc(var(--ag-icon-size)/2)}.ag-advanced-filter-builder-item-tree-line-vertical:before{top:0;width:calc(var(--ag-advanced-filter-builder-indent-size) - var(--ag-icon-size)/2)}:where(.ag-ltr) .ag-advanced-filter-builder-item-tree-line-vertical:before{border-left:var(--ag-border-width) solid var(--ag-border-color);left:calc(var(--ag-icon-size)/2)}:where(.ag-rtl) .ag-advanced-filter-builder-item-tree-line-vertical:before{border-right:var(--ag-border-width) solid var(--ag-border-color);right:calc(var(--ag-icon-size)/2)}.ag-advanced-filter-builder-item-tree-line-vertical-top:before{height:50%;top:0;width:calc(var(--ag-advanced-filter-builder-indent-size) - var(--ag-icon-size)/2)}:where(.ag-ltr) .ag-advanced-filter-builder-item-tree-line-vertical-top:before{border-left:var(--ag-border-width) solid var(--ag-border-color);left:calc(var(--ag-icon-size)/2)}:where(.ag-rtl) .ag-advanced-filter-builder-item-tree-line-vertical-top:before{border-right:var(--ag-border-width) solid var(--ag-border-color);right:calc(var(--ag-icon-size)/2)}.ag-advanced-filter-builder-item-tree-line-vertical-bottom:before{height:calc(50% - var(--ag-icon-size)*1.5/2);top:calc(50% + var(--ag-icon-size)*1.5/2);width:calc(var(--ag-icon-size)/2)}:where(.ag-ltr) .ag-advanced-filter-builder-item-tree-line-vertical-bottom:before{border-left:var(--ag-border-width) solid var(--ag-border-color);left:calc(var(--ag-icon-size)/2)}:where(.ag-rtl) .ag-advanced-filter-builder-item-tree-line-vertical-bottom:before{border-right:var(--ag-border-width) solid var(--ag-border-color);right:calc(var(--ag-icon-size)/2)}.ag-advanced-filter-builder-item-condition{padding-bottom:var(--ag-spacing);padding-top:var(--ag-spacing)}.ag-advanced-filter-builder-item,.ag-advanced-filter-builder-item-buttons,.ag-advanced-filter-builder-item-condition,.ag-advanced-filter-builder-item-tree-lines,.ag-advanced-filter-builder-pill,.ag-advanced-filter-builder-pill-wrapper{align-items:center;display:flex;height:100%}.ag-advanced-filter-builder-pill-wrapper{margin:0 var(--ag-spacing)}.ag-advanced-filter-builder-pill{border-radius:var(--ag-border-radius);min-height:calc(100% - var(--ag-spacing)*3);min-width:calc(var(--ag-spacing)*2);padding:var(--ag-spacing) calc(var(--ag-spacing)*2);position:relative}:where(.ag-advanced-filter-builder-pill){.ag-advanced-filter-builder-value-number{font-family:monospace;font-weight:700}.ag-advanced-filter-builder-value-empty{color:var(--ag-subtle-text-color)}}:where(.ag-ltr) :where(.ag-advanced-filter-builder-pill){.ag-picker-field-display{margin-right:var(--ag-spacing)}}:where(.ag-rtl) :where(.ag-advanced-filter-builder-pill){.ag-picker-field-display{margin-left:var(--ag-spacing)}}.ag-advanced-filter-builder-pill-display{font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ag-advanced-filter-builder-join-pill{background-color:var(--ag-advanced-filter-builder-join-pill-color);cursor:pointer}.ag-advanced-filter-builder-column-pill{background-color:var(--ag-advanced-filter-builder-column-pill-color);cursor:pointer}.ag-advanced-filter-builder-option-pill{background-color:var(--ag-advanced-filter-builder-option-pill-color);cursor:pointer}.ag-advanced-filter-builder-value-pill{background-color:var(--ag-advanced-filter-builder-value-pill-color);cursor:text;max-width:140px;:where(.ag-advanced-filter-builder-pill-display){display:block}}.ag-advanced-filter-builder-item-buttons>*{margin:0 calc(var(--ag-spacing)*.5)}.ag-advanced-filter-builder-item-button{color:var(--ag-subtle-text-color);cursor:pointer;position:relative}.ag-advanced-filter-builder-item-button,.ag-advanced-filter-builder-pill{&:focus-visible{box-shadow:var(--ag-focus-shadow)}}.ag-advanced-filter-builder-item-button-disabled{cursor:default;opacity:.5}.ag-advanced-filter-builder-virtual-list-container{top:var(--ag-spacing)}.ag-advanced-filter-builder-virtual-list-item{cursor:default;display:flex;height:var(--ag-list-item-height);&:hover{background-color:var(--ag-row-hover-color);:where(.ag-advanced-filter-builder-item-button){opacity:1}}}.ag-advanced-filter-builder-invalid{color:var(--ag-subtle-text-color);cursor:default;margin:0 var(--ag-spacing)}:where(.ag-advanced-filter-builder-validation) .ag-advanced-filter-builder-invalid{color:var(--ag-invalid-color)}:where(.ag-advanced-filter-builder-virtual-list-item-highlight) .ag-advanced-filter-builder-item-button:focus-visible{opacity:1}`
);
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterApi.ts
function getAdvancedFilterModel(beans) {
return beans.filterManager?.getAdvFilterModel() ?? null;
}
function setAdvancedFilterModel(beans, advancedFilterModel) {
beans.filterManager?.setAdvFilterModel(advancedFilterModel);
}
function showAdvancedFilterBuilder(beans) {
beans.filterManager?.toggleAdvFilterBuilder(true, "api");
}
function hideAdvancedFilterBuilder(beans) {
beans.filterManager?.toggleAdvFilterBuilder(false, "api");
}
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterExpressionService.ts
var import_ag_grid_community12 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterLocaleText.ts
var ADVANCED_FILTER_LOCALE_TEXT = {
ariaAdvancedFilterBuilderItem: (variableValues) => `${variableValues[0]}. Level ${variableValues[1]}. Press ENTER to edit`,
ariaAdvancedFilterBuilderItemValidation: (variableValues) => `${variableValues[0]}. Level ${variableValues[1]}. ${variableValues[2]} Press ENTER to edit`,
ariaAdvancedFilterBuilderList: "Advanced Filter Builder List",
ariaAdvancedFilterBuilderFilterItem: "Filter Condition",
ariaAdvancedFilterBuilderGroupItem: "Filter Group",
ariaAdvancedFilterBuilderColumn: "Column",
ariaAdvancedFilterBuilderOption: "Option",
ariaAdvancedFilterBuilderValue: "Value",
ariaAdvancedFilterBuilderJoinOperator: "Join Operator",
ariaAdvancedFilterInput: "Advanced Filter Input",
ariaLabelAdvancedFilterAutocomplete: "Advanced Filter Autocomplete",
advancedFilterContains: "contains",
advancedFilterNotContains: "does not contain",
advancedFilterTextEquals: "equals",
advancedFilterTextNotEqual: "does not equal",
advancedFilterStartsWith: "begins with",
advancedFilterEndsWith: "ends with",
advancedFilterBlank: "is blank",
advancedFilterNotBlank: "is not blank",
advancedFilterEquals: "=",
advancedFilterNotEqual: "!=",
advancedFilterGreaterThan: ">",
advancedFilterGreaterThanOrEqual: ">=",
advancedFilterLessThan: "<",
advancedFilterLessThanOrEqual: "<=",
advancedFilterTrue: "is true",
advancedFilterFalse: "is false",
advancedFilterAnd: "AND",
advancedFilterOr: "OR",
advancedFilterApply: "Apply",
advancedFilterReset: "Reset",
advancedFilterCancel: "Cancel",
advancedFilterClear: "Clear",
advancedFilterBuilder: "Builder",
advancedFilterValidationMissingColumn: "Column is missing",
advancedFilterValidationMissingOption: "Option is missing",
advancedFilterValidationMissingValue: "Value is missing",
advancedFilterValidationInvalidColumn: "Column not found",
advancedFilterValidationInvalidOption: "Option not found",
advancedFilterValidationMissingQuote: "Value is missing an end quote",
advancedFilterValidationNotANumber: "Value is not a number",
advancedFilterValidationInvalidDate: "Value is not a valid date",
advancedFilterValidationMissingCondition: "Condition is missing",
advancedFilterValidationJoinOperatorMismatch: "Join operators within a condition must be the same",
advancedFilterValidationInvalidJoinOperator: "Join operator not found",
advancedFilterValidationMissingEndBracket: "Missing end bracket",
advancedFilterValidationExtraEndBracket: "Too many end brackets",
advancedFilterValidationMessage: (variableValues) => `Expression has an error. ${variableValues[0]} - ${variableValues[1]}.`,
advancedFilterValidationMessageAtEnd: (variableValues) => `Expression has an error. ${variableValues[0]} at end of expression.`,
advancedFilterBuilderTitle: "Advanced Filter",
advancedFilterBuilderApply: "Apply",
advancedFilterBuilderCancel: "Cancel",
advancedFilterBuilderClear: "Clear",
advancedFilterBuilderReset: "Reset",
advancedFilterBuilderAddButtonTooltip: "Add Filter or Group",
advancedFilterBuilderRemoveButtonTooltip: "Remove",
advancedFilterBuilderMoveUpButtonTooltip: "Move Up",
advancedFilterBuilderMoveDownButtonTooltip: "Move Down",
advancedFilterBuilderAddJoin: "Add Group",
advancedFilterBuilderAddCondition: "Add Filter",
advancedFilterBuilderSelectColumn: "Select a column",
advancedFilterBuilderSelectOption: "Select an option",
advancedFilterBuilderEnterValue: "Enter a value...",
advancedFilterBuilderValidationAlreadyApplied: "Current filter already applied.",
advancedFilterBuilderValidationIncomplete: "Not all conditions are complete.",
advancedFilterBuilderValidationSelectColumn: "Must select a column.",
advancedFilterBuilderValidationSelectOption: "Must select an option.",
advancedFilterBuilderValidationEnterValue: "Must enter a value."
};
// packages/ag-grid-enterprise/src/advancedFilter/filterExpressionUtils.ts
function getSearchString(value, position, endPosition) {
if (!value) {
return "";
}
const numChars = endPosition - position;
return numChars ? value.slice(0, value.length - numChars) : value;
}
function updateExpression(expression, startPosition, endPosition, updatedValuePart, appendSpace, appendQuote, empty) {
const secondPartStartPosition = endPosition + (!expression.length || empty ? 0 : 1);
let positionOffset = 0;
if (appendSpace) {
if (expression[secondPartStartPosition] === " ") {
positionOffset = 1;
} else {
updatedValuePart += " ";
if (appendQuote) {
updatedValuePart += `"`;
}
}
}
const updatedValue = expression.slice(0, startPosition) + updatedValuePart + expression.slice(secondPartStartPosition);
return { updatedValue, updatedPosition: startPosition + updatedValuePart.length + positionOffset };
}
function findStartPosition(expression, position, endPosition) {
let startPosition = position;
while (startPosition < endPosition) {
const char = expression[startPosition];
if (char !== " ") {
break;
}
startPosition++;
}
return startPosition;
}
function findEndPosition(expression, position, includeCloseBracket, isStartPositionUnknown) {
let endPosition = position;
let isEmpty = false;
while (endPosition < expression.length) {
const char = expression[endPosition];
if (char === "(") {
if (isStartPositionUnknown && expression[endPosition - 1] === " ") {
isEmpty = true;
} else {
endPosition = endPosition - 1;
}
break;
} else if (char === " " || includeCloseBracket && char === ")") {
endPosition = endPosition - 1;
break;
}
endPosition++;
}
return { endPosition, isEmpty };
}
function checkAndUpdateExpression(params, userValue, displayValue, endPosition) {
if (displayValue !== userValue) {
params.expression = updateExpression(
params.expression,
endPosition - userValue.length + 1,
endPosition,
displayValue
).updatedValue;
}
}
// packages/ag-grid-enterprise/src/advancedFilter/colFilterExpressionParser.ts
var ColumnParser = class {
constructor(params, startPosition) {
this.params = params;
this.startPosition = startPosition;
this.type = "column";
this.valid = true;
this.hasStartChar = false;
this.hasEndChar = false;
this.colName = "";
}
parse(char, position) {
if (char === COL_FILTER_EXPRESSION_START_CHAR && !this.colName) {
this.hasStartChar = true;
} else if (char === COL_FILTER_EXPRESSION_END_CHAR && this.hasStartChar) {
const isMatch = this.parseColumn(false, position);
if (isMatch) {
this.hasEndChar = true;
return false;
} else {
this.colName += char;
}
} else {
this.colName += char;
}
return void 0;
}
getDisplayValue() {
return (this.hasStartChar ? COL_FILTER_EXPRESSION_START_CHAR : "") + this.colName + (this.hasEndChar ? COL_FILTER_EXPRESSION_END_CHAR : "");
}
getColId() {
return this.colId;
}
complete(position) {
this.parseColumn(true, position);
}
getValidationError() {
return this.valid ? null : {
message: this.params.advFilterExpSvc.translate("advancedFilterValidationInvalidColumn"),
startPosition: this.startPosition,
endPosition: this.endPosition ?? this.params.expression.length - 1
};
}
parseColumn(fromComplete, endPosition) {
this.endPosition = endPosition;
const colValue = this.params.advFilterExpSvc.getColId(this.colName);
if (colValue && this.hasStartChar) {
this.colId = colValue.colId;
checkAndUpdateExpression(this.params, this.colName, colValue.columnName, endPosition - 1);
this.colName = colValue.columnName;
this.column = this.params.colModel.getColDefCol(this.colId);
if (this.column) {
this.baseCellDataType = this.params.dataTypeSvc?.getBaseDataType(this.column) ?? "text";
return true;
}
}
if (fromComplete) {
this.valid = false;
}
this.baseCellDataType = "text";
return false;
}
};
var OperatorParser = class {
constructor(params, startPosition, baseCellDataType) {
this.params = params;
this.startPosition = startPosition;
this.baseCellDataType = baseCellDataType;
this.type = "operator";
this.valid = true;
this.expectedNumOperands = 0;
this.operator = "";
}
parse(char, position) {
if (char === " " || char === ")") {
const isMatch = this.parseOperator(false, position - 1);
if (isMatch) {
return true;
} else {
this.operator += char;
}
} else {
this.operator += char;
}
return void 0;
}
complete(position) {
this.parseOperator(true, position);
}
getValidationError() {
return this.valid ? null : {
message: this.params.advFilterExpSvc.translate("advancedFilterValidationInvalidOption"),
startPosition: this.startPosition,
endPosition: this.endPosition ?? this.params.expression.length - 1
};
}
getDisplayValue() {
return this.operator;
}
getOperatorKey() {
return this.parsedOperator;
}
parseOperator(fromComplete, endPosition) {
const operatorForType = this.params.advFilterExpSvc.getDataTypeExpressionOperator(this.baseCellDataType);
const parsedOperator = operatorForType.findOperator(this.operator);
this.endPosition = endPosition;
if (parsedOperator) {
this.parsedOperator = parsedOperator;
const operator = operatorForType.operators[parsedOperator];
this.expectedNumOperands = operator.numOperands;
const operatorDisplayValue = operator.displayValue;
checkAndUpdateExpression(this.params, this.operator, operatorDisplayValue, endPosition);
this.operator = operatorDisplayValue;
return true;
}
const isPartialMatch = parsedOperator === null;
if (fromComplete || !isPartialMatch) {
this.valid = false;
}
return false;
}
};
var OperandParser = class {
constructor(params, startPosition, baseCellDataType, column) {
this.params = params;
this.startPosition = startPosition;
this.baseCellDataType = baseCellDataType;
this.column = column;
this.type = "operand";
this.valid = true;
this.operand = "";
this.validationMessage = null;
this.filterValidationSetters = {
number: () => {
if (this.quotes || isNaN(this.modelValue)) {
this.valid = false;
this.validationMessage = this.params.advFilterExpSvc.translate("advancedFilterValidationNotANumber");
}
},
date: (modelValue) => {
if (modelValue == null) {
this.valid = false;
this.validationMessage = this.params.advFilterExpSvc.translate("advancedFilterValidationInvalidDate");
}
},
dateString: (...args) => this.filterValidationSetters.date(...args),
dateTime: (...args) => this.filterValidationSetters.date(...args),
dateTimeString: (...args) => this.filterValidationSetters.date(...args),
boolean() {
},
object() {
},
text() {
}
};
}
parse(char, position) {
if (char === " ") {
if (this.quotes) {
this.operand += char;
} else {
this.parseOperand(false, position);
return true;
}
} else if (char === ")") {
if (this.baseCellDataType === "number" || !this.quotes) {
this.parseOperand(false, position - 1);
return true;
} else {
this.operand += char;
}
} else if (!this.operand && !this.quotes && (char === `'` || char === `"`)) {
this.quotes = char;
} else if (this.quotes && char === this.quotes) {
this.parseOperand(false, position);
return false;
} else {
this.operand += char;
}
return void 0;
}
complete(position) {
this.parseOperand(true, position);
}
getValidationError() {
return this.validationMessage ? {
message: this.validationMessage,
startPosition: this.startPosition,
endPosition: this.endPosition ?? this.params.expression.length - 1
} : null;
}
getRawValue() {
return this.operand;
}
getModelValue() {
return this.modelValue;
}
parseOperand(fromComplete, position) {
const { advFilterExpSvc } = this.params;
this.endPosition = position;
this.modelValue = this.operand;
if (fromComplete && this.quotes) {
this.valid = false;
this.validationMessage = advFilterExpSvc.translate("advancedFilterValidationMissingQuote");
} else if (this.modelValue === "") {
this.valid = false;
this.validationMessage = advFilterExpSvc.translate("advancedFilterValidationMissingValue");
} else {
const modelValue = advFilterExpSvc.getOperandModelValue(this.operand, this.baseCellDataType, this.column);
if (modelValue != null) {
this.modelValue = modelValue;
}
this.filterValidationSetters[this.baseCellDataType](modelValue);
}
}
};
var COL_FILTER_EXPRESSION_START_CHAR = "[";
var COL_FILTER_EXPRESSION_END_CHAR = "]";
var ColFilterExpressionParser = class {
constructor(params, startPosition) {
this.params = params;
this.startPosition = startPosition;
this.isAwaiting = true;
this.operandValueGetters = {
number: Number,
date: (operand) => this.params.valueSvc.parseValue(this.columnParser.column, null, operand, void 0),
dateString: (...args) => this.operandValueGetters.date(...args),
dateTime: (...args) => this.operandValueGetters.date(...args),
dateTimeString: (...args) => this.operandValueGetters.date(...args),
boolean: (operand) => operand,
object: (operand) => operand,
text: (operand) => operand
};
}
parseExpression() {
let i = this.startPosition;
const { expression } = this.params;
while (i < expression.length) {
const char = expression[i];
if (char === " " && this.isAwaiting) {
} else {
this.isAwaiting = false;
if (!this.parser) {
let parser;
if (!this.columnParser) {
this.columnParser = new ColumnParser(this.params, i);
parser = this.columnParser;
} else if (!this.operatorParser) {
this.operatorParser = new OperatorParser(this.params, i, this.columnParser.baseCellDataType);
parser = this.operatorParser;
} else {
this.operandParser = new OperandParser(
this.params,
i,
this.columnParser.baseCellDataType,
this.columnParser.column
);
parser = this.operandParser;
}
this.parser = parser;
}
const hasCompletedOnPrevChar = this.parser.parse(char, i);
if (hasCompletedOnPrevChar != null) {
if (this.isComplete()) {
return this.returnEndPosition(hasCompletedOnPrevChar ? i - 1 : i, true);
}
this.parser = void 0;
this.isAwaiting = true;
}
}
i++;
}
this.parser?.complete?.(i - 1);
return this.returnEndPosition(i);
}
isValid() {
return this.isComplete() && this.columnParser.valid && this.operatorParser.valid && (!this.operandParser || this.operandParser.valid);
}
getValidationError() {
const validationError = this.columnParser?.getValidationError() ?? this.operatorParser?.getValidationError() ?? this.operandParser?.getValidationError();
if (validationError) {
return validationError;
}
const endPosition = this.params.expression.length;
let translateKey;
if (!this.columnParser) {
translateKey = "advancedFilterValidationMissingColumn";
} else if (!this.operatorParser) {
translateKey = "advancedFilterValidationMissingOption";
} else if (this.operatorParser.expectedNumOperands && !this.operandParser) {
translateKey = "advancedFilterValidationMissingValue";
}
if (translateKey) {
return {
message: this.params.advFilterExpSvc.translate(translateKey),
startPosition: endPosition,
endPosition
};
}
return null;
}
getFunction(params) {
return this.getFunctionCommon(params, (operandIndex, operatorIndex, colId, evaluatorParamsIndex) => {
return (expressionProxy, node, p) => p.operators[operatorIndex].evaluator(
expressionProxy.getValue(colId, node),
node,
p.evaluatorParams[evaluatorParamsIndex],
operandIndex == null ? void 0 : p.operands[operandIndex]
);
});
}
getAutocompleteListParams(position) {
if (this.isColumnPosition(position)) {
return this.getColumnAutocompleteListParams(position);
}
if (this.isOperatorPosition(position)) {
return this.getOperatorAutocompleteListParams(position);
}
if (this.isBeyondEndPosition(position)) {
return void 0;
}
return { enabled: false };
}
updateExpression(position, updateEntry, type) {
const { expression } = this.params;
if (this.isColumnPosition(position)) {
return updateExpression(
this.params.expression,
this.startPosition,
this.columnParser?.getColId() ? this.columnParser.endPosition : findEndPosition(expression, position).endPosition,
this.params.advFilterExpSvc.getColumnValue(updateEntry),
true
);
} else if (this.isOperatorPosition(position)) {
const baseCellDataType = this.getBaseCellDataTypeFromOperatorAutocompleteType(type);
const hasOperand = this.hasOperand(baseCellDataType, updateEntry.key);
const doesOperandNeedQuotes = hasOperand && this.doesOperandNeedQuotes(baseCellDataType);
let update;
if (this.operatorParser?.startPosition != null && position < this.operatorParser.startPosition) {
update = updateExpression(
expression,
position,
position,
updateEntry.displayValue ?? updateEntry.key,
hasOperand,
doesOperandNeedQuotes
);
} else {
let endPosition;
let empty = false;
if (this.operatorParser?.getOperatorKey()) {
endPosition = this.operatorParser.endPosition;
} else {
const { endPosition: calculatedEndPosition, isEmpty } = findEndPosition(
expression,
position,
true,
true
);
endPosition = calculatedEndPosition;
empty = isEmpty;
}
update = updateExpression(
expression,
findStartPosition(expression, this.columnParser.endPosition + 1, endPosition),
endPosition,
updateEntry.displayValue ?? updateEntry.key,
hasOperand,
doesOperandNeedQuotes,
empty
);
}
return { ...update, hideAutocomplete: !hasOperand };
}
return null;
}
getModel() {
const colId = this.columnParser.getColId();
const model = {
filterType: this.columnParser.baseCellDataType,
colId,
type: this.operatorParser.getOperatorKey()
};
if (this.operatorParser.expectedNumOperands) {
model.filter = this.operandParser.getModelValue();
}
return model;
}
getFunctionCommon(params, processFunc) {
const colId = this.columnParser.getColId();
const operator = this.operatorParser?.getOperatorKey();
const { operators, evaluatorParams, operands } = params;
const operatorForColumn = this.params.advFilterExpSvc.getExpressionOperator(
this.columnParser.baseCellDataType,
operator
);
const operatorIndex = this.addToListAndGetIndex(operators, operatorForColumn);
const evaluatorParamsForColumn = this.params.advFilterExpSvc.getExpressionEvaluatorParams(colId);
const evaluatorParamsIndex = this.addToListAndGetIndex(evaluatorParams, evaluatorParamsForColumn);
const operandIndex = this.operatorParser?.expectedNumOperands === 0 ? void 0 : this.addToListAndGetIndex(operands, this.getOperandValue());
return processFunc(operandIndex, operatorIndex, colId, evaluatorParamsIndex);
}
getOperandValue() {
const { baseCellDataType, column } = this.columnParser;
const operand = this.operandValueGetters[baseCellDataType](this.operandParser.getRawValue());
if (baseCellDataType === "dateString" || baseCellDataType === "dateTimeString") {
return this.params.dataTypeSvc?.getDateParserFunction(column)(operand) ?? operand;
}
return operand;
}
isComplete() {
return !!(this.operatorParser && (!this.operatorParser.expectedNumOperands || this.operatorParser.expectedNumOperands && this.operandParser));
}
isColumnPosition(position) {
return !this.columnParser || this.columnParser.endPosition == null || position <= this.columnParser.endPosition + 1;
}
isOperatorPosition(position) {
return !this.operatorParser || this.operatorParser.endPosition == null || position <= this.operatorParser.endPosition + 1;
}
isBeyondEndPosition(position) {
return this.isComplete() && this.endPosition != null && position > this.endPosition + 1 && this.endPosition + 1 < this.params.expression.length;
}
returnEndPosition(returnPosition, treatAsEnd) {
this.endPosition = treatAsEnd ? returnPosition : returnPosition - 1;
return returnPosition;
}
getColumnAutocompleteListParams(position) {
return this.params.advFilterExpSvc.generateAutocompleteListParams(
this.params.advFilterExpSvc.getColumnAutocompleteEntries(),
"column",
this.getColumnSearchString(position)
);
}
getColumnSearchString(position) {
const columnName = this.columnParser?.getDisplayValue() ?? "";
const searchString = getSearchString(
columnName,
position,
this.columnParser?.endPosition == null ? this.params.expression.length : this.columnParser.endPosition + 1
);
const containsStartChar = this.columnParser?.hasStartChar && searchString.length > 0;
const containsEndChar = this.columnParser?.hasEndChar && searchString.length === columnName.length + 2;
if (containsStartChar) {
return searchString.slice(1, containsEndChar ? -1 : void 0);
}
return searchString;
}
getOperatorAutocompleteListParams(position) {
const column = this.columnParser?.column;
if (!column) {
return { enabled: false };
}
const baseCellDataType = this.columnParser.baseCellDataType;
const searchString = this.operatorParser?.startPosition != null && position < this.operatorParser.startPosition ? "" : getSearchString(
this.operatorParser?.getDisplayValue() ?? "",
position,
this.operatorParser?.endPosition == null ? this.params.expression.length : this.operatorParser.endPosition + 1
);
return this.params.advFilterExpSvc.generateAutocompleteListParams(
this.params.advFilterExpSvc.getOperatorAutocompleteEntries(column, baseCellDataType),
`operator-${baseCellDataType}`,
searchString
);
}
getBaseCellDataTypeFromOperatorAutocompleteType(type) {
return type?.replace("operator-", "");
}
hasOperand(baseCellDataType, operator) {
return !baseCellDataType || !operator || (this.params.advFilterExpSvc.getExpressionOperator(baseCellDataType, operator)?.numOperands ?? 0) > 0;
}
doesOperandNeedQuotes(baseCellDataType) {
return baseCellDataType !== "number";
}
addToListAndGetIndex(list, value) {
const index = list.length;
list.push(value);
return index;
}
};
// packages/ag-grid-enterprise/src/advancedFilter/filterExpressionOperators.ts
function findMatch(searchValue, values, getDisplayValue) {
let partialMatch = false;
const searchValueLowerCase = searchValue.toLocaleLowerCase();
const partialSearchValue = searchValueLowerCase + " ";
const parsedValue = Object.keys(values).find((key) => {
const value = values[key];
const displayValueLowerCase = getDisplayValue(value).toLocaleLowerCase();
if (displayValueLowerCase.startsWith(partialSearchValue)) {
partialMatch = true;
}
return displayValueLowerCase === searchValueLowerCase;
});
if (parsedValue) {
return parsedValue;
} else if (partialMatch) {
return null;
} else {
return void 0;
}
}
function getEntries(operators, activeOperatorKeys) {
const keys = activeOperatorKeys ?? Object.keys(operators);
return keys.map((key) => ({
key,
displayValue: operators[key].displayValue
}));
}
var TextFilterExpressionOperators = class {
constructor(params) {
this.params = params;
this.initOperators();
}
getEntries(activeOperators) {
return getEntries(this.operators, activeOperators);
}
findOperator(displayValue) {
return findMatch(displayValue, this.operators, ({ displayValue: displayValue2 }) => displayValue2);
}
initOperators() {
const { translate } = this.params;
this.operators = {
contains: {
displayValue: translate("advancedFilterContains"),
evaluator: (value, node, params, operand1) => this.evaluateExpression(value, node, params, operand1, false, (v, o) => v.includes(o)),
numOperands: 1
},
notContains: {
displayValue: translate("advancedFilterNotContains"),
evaluator: (value, node, params, operand1) => this.evaluateExpression(value, node, params, operand1, true, (v, o) => !v.includes(o)),
numOperands: 1
},
equals: {
displayValue: translate("advancedFilterTextEquals"),
evaluator: (value, node, params, operand1) => this.evaluateExpression(value, node, params, operand1, false, (v, o) => v === o),
numOperands: 1
},
notEqual: {
displayValue: translate("advancedFilterTextNotEqual"),
evaluator: (value, node, params, operand1) => this.evaluateExpression(value, node, params, operand1, true, (v, o) => v != o),
numOperands: 1
},
startsWith: {
displayValue: translate("advancedFilterStartsWith"),
evaluator: (value, node, params, operand1) => this.evaluateExpression(value, node, params, operand1, false, (v, o) => v.startsWith(o)),
numOperands: 1
},
endsWith: {
displayValue: translate("advancedFilterEndsWith"),
evaluator: (value, node, params, operand1) => this.evaluateExpression(value, node, params, operand1, false, (v, o) => v.endsWith(o)),
numOperands: 1
},
blank: {
displayValue: translate("advancedFilterBlank"),
evaluator: (value) => value == null || typeof value === "string" && value.trim().length === 0,
numOperands: 0
},
notBlank: {
displayValue: translate("advancedFilterNotBlank"),
evaluator: (value) => value != null && (typeof value !== "string" || value.trim().length > 0),
numOperands: 0
}
};
}
evaluateExpression(value, node, params, operand, nullsMatch, expression) {
if (value == null) {
return nullsMatch;
}
return params.caseSensitive ? expression(params.valueConverter(value, node), operand) : expression(params.valueConverter(value, node).toLocaleLowerCase(), operand.toLocaleLowerCase());
}
};
var ScalarFilterExpressionOperators = class {
constructor(params) {
this.params = params;
this.initOperators();
}
getEntries(activeOperators) {
return getEntries(this.operators, activeOperators);
}
findOperator(displayValue) {
return findMatch(displayValue, this.operators, ({ displayValue: displayValue2 }) => displayValue2);
}
initOperators() {
const { translate, equals } = this.params;
this.operators = {
equals: {
displayValue: translate("advancedFilterEquals"),
evaluator: (value, node, params, operand1) => this.evaluateSingleOperandExpression(
value,
node,
params,
operand1,
!!params.includeBlanksInEquals,
equals
),
numOperands: 1
},
notEqual: {
displayValue: translate("advancedFilterNotEqual"),
evaluator: (value, node, params, operand1) => this.evaluateSingleOperandExpression(
value,
node,
params,
operand1,
!!params.includeBlanksInEquals,
(v, o) => !equals(v, o)
),
numOperands: 1
},
greaterThan: {
displayValue: translate("advancedFilterGreaterThan"),
evaluator: (value, node, params, operand1) => this.evaluateSingleOperandExpression(
value,
node,
params,
operand1,
!!params.includeBlanksInGreaterThan,
(v, o) => v > o
),
numOperands: 1
},
greaterThanOrEqual: {
displayValue: translate("advancedFilterGreaterThanOrEqual"),
evaluator: (value, node, params, operand1) => this.evaluateSingleOperandExpression(
value,
node,
params,
operand1,
!!params.includeBlanksInGreaterThan,
(v, o) => v >= o
),
numOperands: 1
},
lessThan: {
displayValue: translate("advancedFilterLessThan"),
evaluator: (value, node, params, operand1) => this.evaluateSingleOperandExpression(
value,
node,
params,
operand1,
!!params.includeBlanksInLessThan,
(v, o) => v < o
),
numOperands: 1
},
lessThanOrEqual: {
displayValue: translate("advancedFilterLessThanOrEqual"),
evaluator: (value, node, params, operand1) => this.evaluateSingleOperandExpression(
value,
node,
params,
operand1,
!!params.includeBlanksInLessThan,
(v, o) => v <= o
),
numOperands: 1
},
blank: {
displayValue: translate("advancedFilterBlank"),
evaluator: (value) => value == null,
numOperands: 0
},
notBlank: {
displayValue: translate("advancedFilterNotBlank"),
evaluator: (value) => value != null,
numOperands: 0
}
};
}
evaluateSingleOperandExpression(value, node, params, operand, nullsMatch, expression) {
if (value == null) {
return nullsMatch;
}
return expression(params.valueConverter(value, node), operand);
}
};
var BooleanFilterExpressionOperators = class {
constructor(params) {
this.params = params;
this.initOperators();
}
getEntries(activeOperators) {
return getEntries(this.operators, activeOperators);
}
findOperator(displayValue) {
return findMatch(displayValue, this.operators, ({ displayValue: displayValue2 }) => displayValue2);
}
initOperators() {
const { translate } = this.params;
this.operators = {
true: {
displayValue: translate("advancedFilterTrue"),
evaluator: (value) => !!value,
numOperands: 0
},
false: {
displayValue: translate("advancedFilterFalse"),
evaluator: (value) => value === false,
numOperands: 0
},
blank: {
displayValue: translate("advancedFilterBlank"),
evaluator: (value) => value == null,
numOperands: 0
},
notBlank: {
displayValue: translate("advancedFilterNotBlank"),
evaluator: (value) => value != null,
numOperands: 0
}
};
}
};
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterExpressionService.ts
var AdvancedFilterExpressionService = class extends import_ag_grid_community12.BeanStub {
constructor() {
super(...arguments);
this.beanName = "advFilterExpSvc";
this.filterOperandGetters = {
number: (model) => (0, import_ag_grid_community12._toStringOrNull)(model.filter) ?? "",
date: (model) => {
const column = this.colModel.getColDefCol(model.colId);
if (!column) {
return null;
}
return this.valueSvc.formatValue(column, null, (0, import_ag_grid_community12._parseDateTimeFromString)(model.filter));
},
dateTime: (model) => this.filterOperandGetters.date(model),
dateString: (model) => {
const column = this.colModel.getColDefCol(model.colId);
if (!column) {
return null;
}
const { filter } = model;
const dateFormatFn = this.dataTypeSvc?.getDateFormatterFunction(column);
const dateStringStringValue = dateFormatFn?.((0, import_ag_grid_community12._parseDateTimeFromString)(filter) ?? void 0) ?? filter;
return this.valueSvc.formatValue(column, null, dateStringStringValue);
},
dateTimeString: (model) => this.filterOperandGetters.dateString(model),
boolean: () => null,
object: () => null,
text: () => null
};
this.operandModelValueGetters = {
number: (operand) => (0, import_ag_grid_community12._exists)(operand) ? Number(operand) : null,
date: (operand, column, baseCellDataType) => (0, import_ag_grid_community12._serialiseDate)(
this.valueSvc.parseValue(column, null, operand, void 0),
!!this.dataTypeSvc?.getDateIncludesTimeFlag(baseCellDataType)
),
dateTime: (...args) => this.operandModelValueGetters.date(...args),
dateString: (operand, column, baseCellDataType) => {
const parsedDateString = this.valueSvc.parseValue(column, null, operand, void 0);
if (this.dataTypeSvc) {
return (0, import_ag_grid_community12._serialiseDate)(
this.dataTypeSvc.getDateParserFunction(column)(parsedDateString) ?? null,
this.dataTypeSvc.getDateIncludesTimeFlag(baseCellDataType)
);
}
return parsedDateString;
},
dateTimeString: (...args) => this.operandModelValueGetters.dateString(...args),
boolean: (operand) => operand,
object: (operand) => operand,
text: (operand) => operand
};
this.columnNameToIdMap = {};
this.columnAutocompleteEntries = null;
this.expressionEvaluatorParams = {};
}
wireBeans(beans) {
this.valueSvc = beans.valueSvc;
this.colModel = beans.colModel;
this.colNames = beans.colNames;
this.dataTypeSvc = beans.dataTypeSvc;
}
postConstruct() {
this.expressionJoinOperators = this.generateExpressionJoinOperators();
this.expressionOperators = this.generateExpressionOperators();
}
parseJoinOperator(model) {
const { type } = model;
return this.expressionJoinOperators[type] ?? type;
}
getColumnDisplayValue(model) {
const { colId } = model;
const columnEntries = this.getColumnAutocompleteEntries();
const columnEntry = columnEntries.find(({ key }) => key === colId);
let columnName;
if (columnEntry) {
columnName = columnEntry.displayValue;
this.columnNameToIdMap[columnName.toLocaleUpperCase()] = { colId, columnName };
} else {
columnName = colId;
}
return columnName;
}
getOperatorDisplayValue(model) {
return this.getExpressionOperator(model.filterType, model.type)?.displayValue ?? model.type;
}
getOperandModelValue(operand, baseCellDataType, column) {
return this.operandModelValueGetters[baseCellDataType](operand, column, baseCellDataType);
}
getOperandDisplayValue(model, skipFormatting) {
const { filter } = model;
if (filter == null) {
return "";
}
let operand1 = this.filterOperandGetters[model.filterType](model);
if (model.filterType !== "number") {
operand1 ?? (operand1 = (0, import_ag_grid_community12._toStringOrNull)(filter) ?? "");
if (!skipFormatting) {
operand1 = `"${operand1}"`;
}
}
return skipFormatting ? operand1 : ` ${operand1}`;
}
parseColumnFilterModel(model) {
const columnName = this.getColumnDisplayValue(model) ?? "";
const operator = this.getOperatorDisplayValue(model) ?? "";
const operands = this.getOperandDisplayValue(model);
return `[${columnName}] ${operator}${operands}`;
}
updateAutocompleteCache(updateEntry, type) {
if (type === "column") {
const { key: colId, displayValue } = updateEntry;
this.columnNameToIdMap[updateEntry.displayValue.toLocaleUpperCase()] = {
colId,
columnName: displayValue
};
}
}
translate(key, variableValues) {
let defaultValue = ADVANCED_FILTER_LOCALE_TEXT[key];
if (typeof defaultValue === "function") {
defaultValue = defaultValue(variableValues);
}
return this.getLocaleTextFunc()(key, defaultValue, variableValues);
}
generateAutocompleteListParams(entries, type, searchString) {
return {
enabled: true,
type,
searchString,
entries
};
}
getColumnAutocompleteEntries() {
if (this.columnAutocompleteEntries) {
return this.columnAutocompleteEntries;
}
const columns = this.colModel.getColDefCols() ?? [];
const entries = [];
const includeHiddenColumns = this.gos.get("includeHiddenColumnsInAdvancedFilter");
columns.forEach((column) => {
if (column.getColDef().filter && (includeHiddenColumns || column.isVisible() || column.isRowGroupActive())) {
entries.push({
key: column.getColId(),
displayValue: this.colNames.getDisplayNameForColumn(column, "advancedFilter")
});
}
});
entries.sort((a, b) => {
const aValue = a.displayValue ?? "";
const bValue = b.displayValue ?? "";
if (aValue < bValue) {
return -1;
} else if (bValue > aValue) {
return 1;
}
return 0;
});
return entries;
}
getOperatorAutocompleteEntries(column, baseCellDataType) {
const activeOperators = this.getActiveOperators(column);
return this.getDataTypeExpressionOperator(baseCellDataType).getEntries(activeOperators);
}
getJoinOperatorAutocompleteEntries() {
return Object.entries(this.expressionJoinOperators).map(([key, displayValue]) => ({ key, displayValue }));
}
getDefaultAutocompleteListParams(searchString) {
return this.generateAutocompleteListParams(this.getColumnAutocompleteEntries(), "column", searchString);
}
getDataTypeExpressionOperator(baseCellDataType) {
return this.expressionOperators[baseCellDataType];
}
getExpressionOperator(baseCellDataType, operator) {
return this.getDataTypeExpressionOperator(baseCellDataType)?.operators?.[operator];
}
getExpressionJoinOperators() {
return this.expressionJoinOperators;
}
getColId(columnName) {
const upperCaseColumnName = columnName.toLocaleUpperCase();
const cachedColId = this.columnNameToIdMap[upperCaseColumnName];
if (cachedColId) {
return cachedColId;
}
const columnAutocompleteEntries = this.getColumnAutocompleteEntries();
const colEntry = columnAutocompleteEntries.find(
({ displayValue }) => displayValue.toLocaleUpperCase() === upperCaseColumnName
);
if (colEntry) {
const { key: colId, displayValue } = colEntry;
const colValue = { colId, columnName: displayValue };
this.columnNameToIdMap[upperCaseColumnName] = colValue;
return colValue;
}
return null;
}
getExpressionEvaluatorParams(colId) {
let params = this.expressionEvaluatorParams[colId];
if (params) {
return params;
}
const column = this.colModel.getColDefCol(colId);
if (!column) {
return { valueConverter: (v) => v };
}
const baseCellDataType = this.dataTypeSvc?.getBaseDataType(column);
switch (baseCellDataType) {
case "dateTimeString":
case "dateString":
params = {
valueConverter: this.dataTypeSvc?.getDateParserFunction(column) ?? ((v) => v)
};
break;
case "object":
if (column.getColDef().filterValueGetter) {
params = { valueConverter: (v) => v };
} else {
params = {
valueConverter: (value, node) => this.valueSvc.formatValue(column, node, value) ?? (typeof value.toString === "function" ? value.toString() : "")
};
}
break;
case "text":
case void 0:
params = { valueConverter: (v) => (0, import_ag_grid_community12._toStringOrNull)(v) };
break;
default:
params = { valueConverter: (v) => v };
break;
}
const { filterParams } = column.getColDef();
if (filterParams) {
["caseSensitive", "includeBlanksInEquals", "includeBlanksInLessThan", "includeBlanksInGreaterThan"].forEach(
(param) => {
const paramValue = filterParams[param];
if (paramValue) {
params[param] = paramValue;
}
}
);
}
this.expressionEvaluatorParams[colId] = params;
return params;
}
getColumnDetails(colId) {
const column = this.colModel.getColDefCol(colId) ?? void 0;
const baseCellDataType = (column ? this.dataTypeSvc?.getBaseDataType(column) : void 0) ?? "text";
return { column, baseCellDataType };
}
generateExpressionOperators() {
const translate = (key, variableValues) => this.translate(key, variableValues);
const dateOperatorsParams = {
translate,
equals: (v, o) => v.getTime() === o.getTime()
};
return {
text: new TextFilterExpressionOperators({ translate }),
boolean: new BooleanFilterExpressionOperators({ translate }),
object: new TextFilterExpressionOperators({ translate }),
number: new ScalarFilterExpressionOperators({ translate, equals: (v, o) => v === o }),
date: new ScalarFilterExpressionOperators(dateOperatorsParams),
dateString: new ScalarFilterExpressionOperators(dateOperatorsParams),
dateTime: new ScalarFilterExpressionOperators(dateOperatorsParams),
dateTimeString: new ScalarFilterExpressionOperators(dateOperatorsParams)
};
}
getColumnValue({ displayValue }) {
return `${COL_FILTER_EXPRESSION_START_CHAR}${displayValue}${COL_FILTER_EXPRESSION_END_CHAR}`;
}
generateExpressionJoinOperators() {
return {
AND: this.translate("advancedFilterAnd"),
OR: this.translate("advancedFilterOr")
};
}
getActiveOperators(column) {
const filterOptions = column.getColDef().filterParams?.filterOptions;
if (!filterOptions) {
return void 0;
}
const isValid = filterOptions.every((filterOption) => typeof filterOption === "string");
return isValid ? filterOptions : void 0;
}
resetColumnCaches() {
this.columnAutocompleteEntries = null;
this.columnNameToIdMap = {};
this.expressionEvaluatorParams = {};
}
};
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterService.ts
var import_ag_grid_community39 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterCtrl.ts
var import_ag_grid_community38 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/agDialog.ts
var import_ag_grid_community14 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/agPanel.ts
var import_ag_grid_community13 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/agPanel.css-GENERATED.ts
var agPanelCSS = (
/*css*/
`.ag-panel{background-color:var(--ag-panel-background-color);display:flex;flex-direction:column;overflow:hidden;position:relative}.ag-dialog{border:var(--ag-dialog-border);border-radius:var(--ag-border-radius);box-shadow:var(--ag-dialog-shadow);position:absolute}.ag-panel-title-bar{align-items:center;background-color:var(--ag-panel-title-bar-background-color);border-bottom:var(--ag-panel-title-bar-border);color:var(--ag-panel-title-bar-text-color);cursor:default;display:flex;flex:none;font-weight:var(--ag-panel-title-bar-font-weight);height:var(--ag-header-height);padding:var(--ag-spacing) var(--ag-cell-horizontal-padding)}.ag-panel-title-bar-button{cursor:pointer;:where(.ag-icon){color:var(--ag-panel-title-bar-icon-color)}}:where(.ag-ltr) .ag-panel-title-bar-button{margin-left:calc(var(--ag-spacing)*2);margin-right:var(--ag-spacing)}:where(.ag-rtl) .ag-panel-title-bar-button{margin-left:var(--ag-spacing);margin-right:calc(var(--ag-spacing)*2)}.ag-panel-title-bar-title{flex:1 1 auto}.ag-panel-title-bar-buttons{display:flex}.ag-panel-content-wrapper{display:flex;flex:1 1 auto;overflow:hidden;position:relative}:where(.ag-dragging-fill-handle) .ag-dialog,:where(.ag-dragging-range-handle) .ag-dialog{opacity:.7;pointer-events:none}`
);
// packages/ag-grid-enterprise/src/widgets/agPanel.ts
function getTemplate(config) {
const cssIdentifier = config.cssIdentifier || "default";
return {
tag: "div",
cls: `ag-panel ag-${cssIdentifier}-panel`,
attrs: { tabindex: "-1" },
children: [
{
tag: "div",
ref: "eTitleBar",
cls: `ag-panel-title-bar ag-${cssIdentifier}-panel-title-bar ag-unselectable`,
children: [
{
tag: "span",
ref: "eTitle",
cls: `ag-panel-title-bar-title ag-${cssIdentifier}-panel-title-bar-title`
},
{
tag: "div",
ref: "eTitleBarButtons",
cls: `ag-panel-title-bar-buttons ag-${cssIdentifier}-panel-title-bar-buttons`
}
]
},
{
tag: "div",
ref: "eContentWrapper",
cls: `ag-panel-content-wrapper ag-${cssIdentifier}-panel-content-wrapper`
}
]
};
}
var AgPanel = class extends import_ag_grid_community13.Component {
constructor(config) {
super(getTemplate(config));
this.config = config;
this.closable = true;
this.eContentWrapper = import_ag_grid_community13.RefPlaceholder;
this.eTitleBar = import_ag_grid_community13.RefPlaceholder;
this.eTitleBarButtons = import_ag_grid_community13.RefPlaceholder;
this.eTitle = import_ag_grid_community13.RefPlaceholder;
this.registerCSS(agPanelCSS);
}
postConstruct() {
const {
component,
closable,
hideTitleBar,
title,
minWidth = 250,
width,
minHeight = 250,
height,
centered,
popup,
x,
y,
postProcessPopupParams
} = this.config;
const beans = this.beans;
const positionableFeature = this.createManagedBean(
new import_ag_grid_community13.PositionableFeature(this.getGui(), {
minWidth,
width,
minHeight,
height,
centered,
x,
y,
popup,
calculateTopBuffer: () => this.positionableFeature.getHeight() - this.getBodyHeight()
})
);
this.positionableFeature = positionableFeature;
const eGui = this.getGui();
if (component) {
this.setBodyComponent(component);
}
if (!hideTitleBar) {
if (title) {
this.setTitle(title);
}
this.setClosable(closable != null ? closable : this.closable);
} else {
(0, import_ag_grid_community13._setDisplayed)(this.eTitleBar, false);
}
this.addManagedElementListeners(this.eTitleBar, {
mousedown: (e) => {
if (eGui.contains(e.relatedTarget) || eGui.contains((0, import_ag_grid_community13._getActiveDomElement)(beans)) || this.eTitleBarButtons.contains(e.target)) {
e.preventDefault();
return;
}
const focusEl = this.eContentWrapper.querySelector(
"button, [href], input, select, textarea, [tabindex]"
);
if (focusEl) {
focusEl.focus();
}
}
});
if (popup && positionableFeature.isPositioned()) {
return;
}
if (this.renderComponent) {
this.renderComponent();
}
let postProcessCallback;
if (postProcessPopupParams) {
const { type, eventSource, column, mouseEvent, rowNode } = postProcessPopupParams;
postProcessCallback = () => beans.popupSvc?.callPostProcessPopup(type, eGui, eventSource, mouseEvent, column, rowNode);
}
positionableFeature.initialisePosition(postProcessCallback);
this.eContentWrapper.style.height = "0";
}
renderComponent() {
const eGui = this.getGui();
eGui.focus();
this.close = () => {
eGui.parentElement.removeChild(eGui);
this.destroy();
};
}
getHeight() {
return this.positionableFeature.getHeight();
}
setHeight(height) {
this.positionableFeature.setHeight(height);
}
getWidth() {
return this.positionableFeature.getWidth();
}
setWidth(width) {
this.positionableFeature.setWidth(width);
}
setClosable(closable) {
if (closable !== this.closable) {
this.closable = closable;
}
if (closable) {
const closeButtonComp = this.closeButtonComp = new import_ag_grid_community13.Component({ tag: "div", cls: "ag-button" });
this.createBean(closeButtonComp);
const eGui = closeButtonComp.getGui();
const child = (0, import_ag_grid_community13._createIconNoSpan)("close", this.beans);
child.classList.add("ag-panel-title-bar-button-icon");
eGui.appendChild(child);
this.addTitleBarButton(closeButtonComp);
closeButtonComp.addManagedElementListeners(eGui, { click: this.onBtClose.bind(this) });
} else if (this.closeButtonComp) {
const eGui = this.closeButtonComp.getGui();
eGui.parentElement.removeChild(eGui);
this.closeButtonComp = this.destroyBean(this.closeButtonComp);
}
}
setBodyComponent(bodyComponent) {
bodyComponent.setParentComponent(this);
this.eContentWrapper.appendChild(bodyComponent.getGui());
}
addTitleBarButton(button, position) {
const eTitleBarButtons = this.eTitleBarButtons;
const buttons = eTitleBarButtons.children;
const len = buttons.length;
if (position == null) {
position = len;
}
position = Math.max(0, Math.min(position, len));
button.addCss("ag-panel-title-bar-button");
const eGui = button.getGui();
if (position === 0) {
eTitleBarButtons.insertAdjacentElement("afterbegin", eGui);
} else if (position === len) {
eTitleBarButtons.insertAdjacentElement("beforeend", eGui);
} else {
buttons[position - 1].insertAdjacentElement("afterend", eGui);
}
button.setParentComponent(this);
}
getBodyHeight() {
return (0, import_ag_grid_community13._getInnerHeight)(this.eContentWrapper);
}
getBodyWidth() {
return (0, import_ag_grid_community13._getInnerWidth)(this.eContentWrapper);
}
setTitle(title) {
this.eTitle.innerText = title;
}
// called when user hits the 'x' in the top right
onBtClose() {
this.close();
}
destroy() {
if (this.closeButtonComp) {
this.closeButtonComp = this.destroyBean(this.closeButtonComp);
}
const eGui = this.getGui();
if (eGui && (0, import_ag_grid_community13._isVisible)(eGui)) {
this.close();
}
super.destroy();
}
};
// packages/ag-grid-enterprise/src/widgets/agDialog.ts
var AgDialog = class extends AgPanel {
constructor(config) {
super({ ...config, popup: true });
this.isMaximizable = false;
this.isMaximized = false;
this.maximizeListeners = [];
this.resizeListenerDestroy = null;
this.lastPosition = {
x: 0,
y: 0,
width: 0,
height: 0
};
}
wireBeans(beans) {
this.popupSvc = beans.popupSvc;
}
postConstruct() {
const eGui = this.getGui();
const { movable, resizable, maximizable, modal } = this.config;
this.addCss("ag-dialog");
super.postConstruct();
this.tabGuardFeature = this.createManagedBean(new import_ag_grid_community14.TabGuardFeature(this));
this.tabGuardFeature.initialiseTabGuard({
isFocusableContainer: true,
onFocusIn: () => {
this.popupSvc?.bringPopupToFront(eGui);
},
onTabKeyDown: (e) => {
if (modal) {
return;
}
const backwards = e.shiftKey;
const nextFocusableElement = (0, import_ag_grid_community14._findNextFocusableElement)(this.beans, eGui, false, backwards);
if (!nextFocusableElement || this.tabGuardFeature.getTabGuardCtrl().isTabGuard(nextFocusableElement)) {
if ((0, import_ag_grid_community14._focusNextGridCoreContainer)(this.beans, backwards)) {
e.preventDefault();
}
}
}
});
if (movable) {
this.setMovable(movable);
}
if (maximizable) {
this.setMaximizable(maximizable);
}
if (resizable) {
this.setResizable(resizable);
}
if (!this.config.modal) {
const gridCtrl = this.beans.ctrlsSvc.get("gridCtrl");
gridCtrl.addFocusableContainer(this);
this.addDestroyFunc(() => gridCtrl.removeFocusableContainer(this));
}
}
setAllowFocus(allowFocus) {
this.tabGuardFeature.getTabGuardCtrl().setAllowFocus(allowFocus);
}
renderComponent() {
const eGui = this.getGui();
const { alwaysOnTop, modal, title, afterGuiAttached } = this.config;
const translate = this.getLocaleTextFunc();
const addPopupRes = this.popupSvc?.addPopup({
modal,
eChild: eGui,
closeOnEsc: true,
closedCallback: this.onClosed.bind(this),
alwaysOnTop,
ariaLabel: title || translate("ariaLabelDialog", "Dialog"),
afterGuiAttached
});
if (addPopupRes) {
this.close = addPopupRes.hideFunc;
}
}
onClosed(event) {
this.destroy();
this.config.closedCallback?.(event);
}
setMaximized(maximized) {
if (this.isMaximizable && maximized !== this.isMaximized) {
this.toggleMaximize();
}
}
toggleMaximize() {
const position = this.positionableFeature.getPosition();
if (this.isMaximized) {
const { x, y, width, height } = this.lastPosition;
this.setWidth(width);
this.setHeight(height);
this.positionableFeature.offsetElement(x, y);
} else {
this.lastPosition.width = this.getWidth();
this.lastPosition.height = this.getHeight();
this.lastPosition.x = position.x;
this.lastPosition.y = position.y;
this.positionableFeature.offsetElement(0, 0);
this.setHeight("100%");
this.setWidth("100%");
}
this.isMaximized = !this.isMaximized;
this.refreshMaximizeIcon();
}
refreshMaximizeIcon() {
(0, import_ag_grid_community14._setDisplayed)(this.maximizeIcon, !this.isMaximized);
(0, import_ag_grid_community14._setDisplayed)(this.minimizeIcon, this.isMaximized);
}
clearMaximizebleListeners() {
if (this.maximizeListeners.length) {
this.maximizeListeners.forEach((destroyListener) => destroyListener());
this.maximizeListeners.length = 0;
}
if (this.resizeListenerDestroy) {
this.resizeListenerDestroy();
this.resizeListenerDestroy = null;
}
}
destroy() {
this.maximizeButtonComp = this.destroyBean(this.maximizeButtonComp);
this.clearMaximizebleListeners();
super.destroy();
}
setResizable(resizable) {
this.positionableFeature.setResizable(resizable);
}
setMovable(movable) {
this.positionableFeature.setMovable(movable, this.eTitleBar);
}
setMaximizable(maximizable) {
if (!maximizable) {
this.clearMaximizebleListeners();
if (this.maximizeButtonComp) {
this.destroyBean(this.maximizeButtonComp);
this.maximizeButtonComp = this.maximizeIcon = this.minimizeIcon = void 0;
}
return;
}
const eTitleBar = this.eTitleBar;
if (!eTitleBar || maximizable === this.isMaximizable) {
return;
}
this.isMaximizable = maximizable;
const maximizeButtonComp = this.buildMaximizeAndMinimizeElements();
this.refreshMaximizeIcon();
maximizeButtonComp.addManagedElementListeners(maximizeButtonComp.getGui(), {
click: this.toggleMaximize.bind(this)
});
this.addTitleBarButton(maximizeButtonComp, 0);
this.maximizeListeners.push(
...this.addManagedElementListeners(eTitleBar, {
dblclick: this.toggleMaximize.bind(this)
})
);
[this.resizeListenerDestroy] = this.addManagedListeners(this.positionableFeature, {
resize: () => {
this.isMaximized = false;
this.refreshMaximizeIcon();
}
});
}
buildMaximizeAndMinimizeElements() {
const maximizeButtonComp = this.maximizeButtonComp = this.createBean(
new import_ag_grid_community14.Component({ tag: "div", cls: "ag-dialog-button" })
);
const eGui = maximizeButtonComp.getGui();
this.maximizeIcon = (0, import_ag_grid_community14._createIconNoSpan)("maximize", this.beans);
eGui.appendChild(this.maximizeIcon);
this.maximizeIcon.classList.add("ag-panel-title-bar-button-icon");
this.minimizeIcon = (0, import_ag_grid_community14._createIconNoSpan)("minimize", this.beans);
eGui.appendChild(this.minimizeIcon);
this.minimizeIcon.classList.add("ag-panel-title-bar-button-icon");
return maximizeButtonComp;
}
};
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterComp.ts
var import_ag_grid_community19 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/advancedFilter/autocomplete/agAutocomplete.ts
var import_ag_grid_community18 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/advancedFilter/autocomplete/agAutocomplete.css-GENERATED.ts
var agAutocompleteCSS = (
/*css*/
`.ag-autocomplete{align-items:center;display:flex;width:100%;>*{flex:1 1 auto}}.ag-autocomplete-list-popup{background-color:var(--ag-background-color);border-radius:var(--ag-border-radius);box-shadow:var(--ag-dropdown-shadow);padding:0;position:absolute;-webkit-user-select:none;-moz-user-select:none;user-select:none}.ag-autocomplete-list{height:calc(var(--ag-row-height)*6.5);min-width:200px;position:relative;width:100%}.ag-autocomplete-virtual-list-item{cursor:default;display:flex;height:var(--ag-list-item-height);&:focus-visible:after{content:none}&:hover{background-color:var(--ag-row-hover-color)}}.ag-autocomplete-row{align-items:center;display:flex;flex:1 1 auto;overflow:hidden}.ag-autocomplete-row-label{margin:0 var(--ag-widget-container-horizontal-padding);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ag-autocomplete-row-selected{background-color:var(--ag-selected-row-background-color)}`
);
// packages/ag-grid-enterprise/src/advancedFilter/autocomplete/agAutocompleteList.ts
var import_ag_grid_community17 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/virtualList.ts
var import_ag_grid_community15 = require("ag-grid-community");
function getVirtualListTemplate(cssIdentifier) {
return {
tag: "div",
cls: `ag-virtual-list-viewport ag-${cssIdentifier}-virtual-list-viewport`,
role: "presentation",
children: [
{
tag: "div",
ref: "eContainer",
cls: `ag-virtual-list-container ag-${cssIdentifier}-virtual-list-container`
}
]
};
}
var VirtualList = class extends import_ag_grid_community15.TabGuardComp {
constructor(params) {
super(getVirtualListTemplate(params?.cssIdentifier || "default"));
this.renderedRows = /* @__PURE__ */ new Map();
this.rowHeight = 20;
this.pageSize = -1;
this.isScrolling = false;
this.isHeightFromTheme = true;
this.eContainer = import_ag_grid_community15.RefPlaceholder;
this.awaitStableCallbacks = [];
const { cssIdentifier = "default", ariaRole = "listbox", listName, moveItemCallback } = params || {};
this.cssIdentifier = cssIdentifier;
this.ariaRole = ariaRole;
this.listName = listName;
this.moveItemCallback = moveItemCallback;
}
wireBeans(beans) {
this.environment = beans.environment;
}
postConstruct() {
this.addScrollListener();
this.rowHeight = this.getItemHeight();
this.addResizeObserver();
this.initialiseTabGuard({
onFocusIn: (e) => this.onFocusIn(e),
onFocusOut: (e) => this.onFocusOut(e),
focusInnerElement: (fromBottom) => this.focusInnerElement(fromBottom),
onTabKeyDown: (e) => this.onTabKeyDown(e),
handleKeyDown: (e) => this.handleKeyDown(e)
});
this.refreshAriaProperties();
this.addManagedEventListeners({ gridStylesChanged: this.onGridStylesChanged.bind(this) });
}
onGridStylesChanged(e) {
if (e.listItemHeightChanged) {
this.rowHeight = this.getItemHeight();
this.refresh();
}
}
refreshAriaProperties() {
const translate = this.getLocaleTextFunc();
const listName = translate("ariaDefaultListName", this.listName || "List");
const ariaEl = this.eContainer;
(0, import_ag_grid_community15._setAriaRole)(ariaEl, this.model?.getRowCount() > 0 ? this.ariaRole : "presentation");
(0, import_ag_grid_community15._setAriaLabel)(ariaEl, listName);
}
addResizeObserver() {
const listener = () => (0, import_ag_grid_community15._requestAnimationFrame)(this.beans, () => this.drawVirtualRows());
const destroyObserver = (0, import_ag_grid_community15._observeResize)(this.beans, this.getGui(), listener);
this.addDestroyFunc(destroyObserver);
}
focusInnerElement(fromBottom) {
this.focusRow(fromBottom ? this.model.getRowCount() - 1 : 0);
return true;
}
onFocusIn(e) {
const target = e.target;
if (target.classList.contains("ag-virtual-list-item")) {
this.lastFocusedRowIndex = (0, import_ag_grid_community15._getAriaPosInSet)(target) - 1;
}
}
onFocusOut(e) {
if (!this.getFocusableElement().contains(e.relatedTarget)) {
this.lastFocusedRowIndex = null;
}
}
handleKeyDown(e) {
const { key, shiftKey } = e;
switch (key) {
case import_ag_grid_community15.KeyCode.UP:
case import_ag_grid_community15.KeyCode.DOWN:
{
const isUp = key === import_ag_grid_community15.KeyCode.UP;
e.preventDefault();
if (shiftKey) {
this.moveItem(isUp);
} else {
this.navigate(isUp);
}
}
break;
case import_ag_grid_community15.KeyCode.PAGE_HOME:
case import_ag_grid_community15.KeyCode.PAGE_END:
case import_ag_grid_community15.KeyCode.PAGE_UP:
case import_ag_grid_community15.KeyCode.PAGE_DOWN:
if (this.navigateToPage(key) !== null) {
e.preventDefault();
}
break;
}
}
onTabKeyDown(e) {
(0, import_ag_grid_community15._stopPropagationForAgGrid)(e);
this.forceFocusOutOfContainer(e.shiftKey);
}
getNextRow(up) {
if (this.lastFocusedRowIndex == null) {
return void 0;
}
const nextRow = this.lastFocusedRowIndex + (up ? -1 : 1);
if (nextRow < 0 || nextRow >= this.model.getRowCount()) {
return void 0;
}
return nextRow;
}
moveItem(up) {
if (!this.moveItemCallback) {
return;
}
const item = this.getComponentAt(this.lastFocusedRowIndex);
if (!item) {
return;
}
this.moveItemCallback(item, up);
}
navigate(up) {
const nextRow = this.getNextRow(up);
if (nextRow === void 0) {
return;
}
this.focusRow(nextRow);
}
navigateToPage(key, fromItem = "focused") {
let hasFocus = false;
if (fromItem === "focused") {
fromItem = this.getLastFocusedRow();
hasFocus = true;
}
const rowCount = this.model.getRowCount() - 1;
let newIndex = -1;
if (key === import_ag_grid_community15.KeyCode.PAGE_HOME) {
newIndex = 0;
} else if (key === import_ag_grid_community15.KeyCode.PAGE_END) {
newIndex = rowCount;
} else if (key === import_ag_grid_community15.KeyCode.PAGE_DOWN) {
newIndex = Math.min(fromItem + this.pageSize, rowCount);
} else if (key === import_ag_grid_community15.KeyCode.PAGE_UP) {
newIndex = Math.max(fromItem - this.pageSize, 0);
}
if (newIndex === -1) {
return null;
}
if (hasFocus) {
this.focusRow(newIndex);
} else {
this.ensureIndexVisible(newIndex);
}
return newIndex;
}
getLastFocusedRow() {
return this.lastFocusedRowIndex;
}
focusRow(rowNumber) {
if (this.isScrolling) {
return;
}
this.isScrolling = true;
this.ensureIndexVisible(rowNumber);
(0, import_ag_grid_community15._requestAnimationFrame)(this.beans, () => {
this.isScrolling = false;
if (!this.isAlive()) {
return;
}
const renderedRow = this.renderedRows.get(rowNumber);
if (renderedRow) {
renderedRow.eDiv.focus();
}
});
}
getComponentAt(rowIndex) {
const comp = this.renderedRows.get(rowIndex);
return comp && comp.rowComponent;
}
forEachRenderedRow(func) {
this.renderedRows.forEach((value, key) => func(value.rowComponent, key));
}
getItemHeight() {
if (!this.isHeightFromTheme) {
return this.rowHeight;
}
return this.environment.getDefaultListItemHeight();
}
/**
* Returns true if the view had to be scrolled, otherwise, false.
*/
ensureIndexVisible(index, scrollPartialIntoView = true) {
const lastRow = this.model.getRowCount();
if (typeof index !== "number" || index < 0 || index >= lastRow) {
(0, import_ag_grid_community15._warn)(229, { index });
return false;
}
const rowTopPixel = index * this.rowHeight;
const rowBottomPixel = rowTopPixel + this.rowHeight;
const eGui = this.getGui();
const viewportTopPixel = eGui.scrollTop;
const viewportHeight = eGui.offsetHeight;
const viewportBottomPixel = viewportTopPixel + viewportHeight;
const diff = scrollPartialIntoView ? 0 : this.rowHeight;
const viewportScrolledPastRow = viewportTopPixel > rowTopPixel + diff;
const viewportScrolledBeforeRow = viewportBottomPixel < rowBottomPixel - diff;
if (viewportScrolledPastRow) {
eGui.scrollTop = rowTopPixel;
return true;
}
if (viewportScrolledBeforeRow) {
const newScrollPosition = rowBottomPixel - viewportHeight;
eGui.scrollTop = newScrollPosition;
return true;
}
return false;
}
setComponentCreator(componentCreator) {
this.componentCreator = componentCreator;
}
setComponentUpdater(componentUpdater) {
this.componentUpdater = componentUpdater;
}
getRowHeight() {
return this.rowHeight;
}
getScrollTop() {
return this.getGui().scrollTop;
}
setRowHeight(rowHeight) {
this.isHeightFromTheme = false;
this.rowHeight = rowHeight;
this.refresh();
}
refresh(softRefresh) {
if (this.model == null || !this.isAlive()) {
return;
}
const rowCount = this.model.getRowCount();
this.eContainer.style.height = `${rowCount * this.rowHeight}px`;
this.refreshAriaProperties();
this.awaitStable(() => {
if (!this.isAlive()) {
return;
}
if (this.canSoftRefresh(softRefresh)) {
this.drawVirtualRows(true);
} else {
this.clearVirtualRows();
this.drawVirtualRows();
}
});
}
awaitStable(callback) {
this.awaitStableCallbacks.push(callback);
if (this.awaitStableCallbacks.length > 1) {
return;
}
const rowCount = this.model.getRowCount();
(0, import_ag_grid_community15._waitUntil)(
() => this.eContainer.clientHeight >= rowCount * this.rowHeight,
() => {
if (!this.isAlive()) {
return;
}
const callbacks = this.awaitStableCallbacks;
this.awaitStableCallbacks = [];
callbacks.forEach((c) => c());
}
);
}
canSoftRefresh(softRefresh) {
return !!(softRefresh && this.renderedRows.size && typeof this.model.areRowsEqual === "function" && this.componentUpdater);
}
clearVirtualRows() {
this.renderedRows.forEach((_, rowIndex) => this.removeRow(rowIndex));
}
drawVirtualRows(softRefresh) {
if (!this.isAlive() || !this.model) {
return;
}
const gui = this.getGui();
const topPixel = gui.scrollTop;
const bottomPixel = topPixel + gui.offsetHeight;
if (topPixel === bottomPixel) {
this.clearVirtualRows();
} else {
const firstRow = Math.floor(topPixel / this.rowHeight);
const lastRow = Math.floor(bottomPixel / this.rowHeight);
this.pageSize = Math.floor((bottomPixel - topPixel) / this.rowHeight);
this.ensureRowsRendered(firstRow, lastRow, softRefresh);
}
}
ensureRowsRendered(start, finish, softRefresh) {
this.renderedRows.forEach((_, rowIndex) => {
if ((rowIndex < start || rowIndex > finish) && rowIndex !== this.lastFocusedRowIndex) {
this.removeRow(rowIndex);
}
});
if (softRefresh) {
this.refreshRows();
}
for (let rowIndex = start; rowIndex <= finish; rowIndex++) {
if (this.renderedRows.has(rowIndex)) {
continue;
}
if (rowIndex < this.model.getRowCount()) {
this.insertRow(rowIndex);
}
}
}
insertRow(rowIndex) {
const value = this.model.getRow(rowIndex);
const role = this.ariaRole === "tree" ? "treeitem" : "option";
const eDiv = (0, import_ag_grid_community15._createElement)({
tag: "div",
cls: `ag-virtual-list-item ag-${this.cssIdentifier}-virtual-list-item`,
role,
attrs: { tabindex: "-1" }
});
(0, import_ag_grid_community15._setAriaSetSize)(eDiv, this.model.getRowCount());
(0, import_ag_grid_community15._setAriaPosInSet)(eDiv, rowIndex + 1);
eDiv.style.height = `${this.rowHeight}px`;
eDiv.style.top = `${this.rowHeight * rowIndex}px`;
const rowComponent = this.componentCreator(value, eDiv);
rowComponent.addGuiEventListener("focusin", () => this.lastFocusedRowIndex = rowIndex);
eDiv.appendChild(rowComponent.getGui());
if (this.renderedRows.has(rowIndex - 1)) {
this.renderedRows.get(rowIndex - 1).eDiv.insertAdjacentElement("afterend", eDiv);
} else if (this.renderedRows.has(rowIndex + 1)) {
this.renderedRows.get(rowIndex + 1).eDiv.insertAdjacentElement("beforebegin", eDiv);
} else {
this.eContainer.appendChild(eDiv);
}
this.renderedRows.set(rowIndex, { rowComponent, eDiv, value });
}
removeRow(rowIndex) {
const component = this.renderedRows.get(rowIndex);
this.eContainer.removeChild(component.eDiv);
this.destroyBean(component.rowComponent);
this.renderedRows.delete(rowIndex);
}
refreshRows() {
const rowCount = this.model.getRowCount();
this.renderedRows.forEach((row, rowIndex) => {
if (rowIndex >= rowCount) {
this.removeRow(rowIndex);
} else {
const newValue = this.model.getRow(rowIndex);
if (this.model.areRowsEqual?.(row.value, newValue)) {
this.componentUpdater(newValue, row.rowComponent);
} else {
this.removeRow(rowIndex);
}
}
});
}
addScrollListener() {
this.addGuiEventListener("scroll", () => this.drawVirtualRows(), { passive: true });
}
setModel(model) {
this.model = model;
}
getAriaElement() {
return this.eContainer;
}
destroy() {
if (!this.isAlive()) {
return;
}
this.clearVirtualRows();
this.awaitStableCallbacks.length = 0;
super.destroy();
}
};
// packages/ag-grid-enterprise/src/advancedFilter/autocomplete/agAutocompleteRow.ts
var import_ag_grid_community16 = require("ag-grid-community");
var AgAutocompleteRowElement = {
tag: "div",
cls: "ag-autocomplete-row",
role: "presentation",
children: [{ tag: "div", cls: "ag-autocomplete-row-label" }]
};
var AgAutocompleteRow = class extends import_ag_grid_community16.Component {
constructor() {
super(AgAutocompleteRowElement);
this.hasHighlighting = false;
}
setState(value, selected) {
this.value = value;
this.render();
this.updateSelected(selected);
}
updateSelected(selected) {
this.toggleCss("ag-autocomplete-row-selected", selected);
}
setSearchString(searchString) {
let keepHighlighting = false;
const { value } = this;
if (value && (0, import_ag_grid_community16._exists)(searchString)) {
const index = value.toLocaleLowerCase().indexOf(searchString.toLocaleLowerCase());
if (index >= 0) {
keepHighlighting = true;
this.hasHighlighting = true;
const highlightEndIndex = index + searchString.length;
const child = this.getGui().lastElementChild;
(0, import_ag_grid_community16._clearElement)(child);
child.append(
// Start part
value.slice(0, index),
// Highlighted part wrapped in bold tag
(0, import_ag_grid_community16._createElement)({ tag: "b", children: value.slice(index, highlightEndIndex) }),
// End part
value.slice(highlightEndIndex)
);
}
}
if (!keepHighlighting && this.hasHighlighting) {
this.hasHighlighting = false;
this.render();
}
}
render() {
this.getGui().lastElementChild.textContent = this.value ?? "\xA0";
}
};
// packages/ag-grid-enterprise/src/advancedFilter/autocomplete/agAutocompleteList.ts
var AgAutocompleteListElement = {
tag: "div",
cls: "ag-autocomplete-list-popup",
children: [
{
tag: "div",
ref: "eList",
cls: "ag-autocomplete-list"
}
]
};
var AgAutocompleteList = class extends import_ag_grid_community17.PopupComponent {
constructor(params) {
super(AgAutocompleteListElement);
this.params = params;
this.eList = import_ag_grid_community17.RefPlaceholder;
this.searchString = "";
}
postConstruct() {
this.autocompleteEntries = this.params.autocompleteEntries;
this.virtualList = this.createManagedBean(new VirtualList({ cssIdentifier: "autocomplete" }));
this.virtualList.setComponentCreator(this.createRowComponent.bind(this));
this.eList.appendChild(this.virtualList.getGui());
this.virtualList.setModel({
getRowCount: () => this.autocompleteEntries.length,
getRow: (index) => this.autocompleteEntries[index]
});
const virtualListGui = this.virtualList.getGui();
this.addManagedListeners(virtualListGui, {
click: () => this.params.onConfirmed(),
mousemove: this.onMouseMove.bind(this),
mousedown: (e) => e.preventDefault()
});
this.setSelectedValue(0);
}
onNavigationKeyDown(event, key) {
event.preventDefault();
const oldIndex = this.autocompleteEntries.indexOf(this.selectedValue);
const newIndex = key === import_ag_grid_community17.KeyCode.UP ? oldIndex - 1 : oldIndex + 1;
this.checkSetSelectedValue(newIndex);
}
setSearch(searchString) {
this.searchString = searchString;
if ((0, import_ag_grid_community17._exists)(searchString)) {
this.runSearch();
} else {
this.autocompleteEntries = this.params.autocompleteEntries;
this.virtualList.refresh();
this.checkSetSelectedValue(0);
}
this.updateSearchInList();
}
runContainsSearch(searchString, searchStrings) {
let topMatch;
let topMatchStartsWithSearchString = false;
const lowerCaseSearchString = searchString.toLocaleLowerCase();
const allMatches = searchStrings.filter((string) => {
const lowerCaseString = string.toLocaleLowerCase();
const index = lowerCaseString.indexOf(lowerCaseSearchString);
const startsWithSearchString = index === 0;
const isMatch = index >= 0;
if (isMatch && (!topMatch || !topMatchStartsWithSearchString && startsWithSearchString || topMatchStartsWithSearchString === startsWithSearchString && string.length < topMatch.length)) {
topMatch = string;
topMatchStartsWithSearchString = startsWithSearchString;
}
return isMatch;
});
if (!topMatch && allMatches.length) {
topMatch = allMatches[0];
}
return { topMatch, allMatches };
}
runSearch() {
const { autocompleteEntries, useFuzzySearch, forceLastSelection } = this.params;
const searchStrings = autocompleteEntries.map((v) => v.displayValue ?? v.key);
let matchingStrings;
let topSuggestion;
if (useFuzzySearch) {
matchingStrings = (0, import_ag_grid_community17._fuzzySuggestions)({
inputValue: this.searchString,
allSuggestions: searchStrings,
hideIrrelevant: true
}).values;
topSuggestion = matchingStrings.length ? matchingStrings[0] : void 0;
} else {
const containsMatches = this.runContainsSearch(this.searchString, searchStrings);
matchingStrings = containsMatches.allMatches;
topSuggestion = containsMatches.topMatch;
}
let filteredEntries = autocompleteEntries.filter(
({ key, displayValue }) => matchingStrings.includes(displayValue ?? key)
);
if (!filteredEntries.length && this.selectedValue && forceLastSelection?.(this.selectedValue, this.searchString)) {
filteredEntries = [this.selectedValue];
}
this.autocompleteEntries = filteredEntries;
this.virtualList.refresh();
if (!topSuggestion) {
return;
}
const topSuggestionIndex = matchingStrings.indexOf(topSuggestion);
this.checkSetSelectedValue(topSuggestionIndex);
}
updateSearchInList() {
this.virtualList.forEachRenderedRow((row) => row.setSearchString(this.searchString));
}
checkSetSelectedValue(index) {
if (index >= 0 && index < this.autocompleteEntries.length) {
this.setSelectedValue(index);
}
}
setSelectedValue(index) {
const value = this.autocompleteEntries[index];
if (this.selectedValue === value) {
return;
}
this.selectedValue = value;
this.virtualList.ensureIndexVisible(index);
this.virtualList.forEachRenderedRow((cmp, idx) => {
cmp.updateSelected(index === idx);
});
}
createRowComponent(value) {
const row = new AgAutocompleteRow();
this.createBean(row);
row.setState(value.displayValue ?? value.key, value === this.selectedValue);
return row;
}
onMouseMove(mouseEvent) {
const virtualList = this.virtualList;
const rect = virtualList.getGui().getBoundingClientRect();
const scrollTop = virtualList.getScrollTop();
const mouseY = mouseEvent.clientY - rect.top + scrollTop;
const row = Math.floor(mouseY / virtualList.getRowHeight());
this.checkSetSelectedValue(row);
}
afterGuiAttached() {
this.virtualList.refresh();
}
getSelectedValue() {
if (!this.autocompleteEntries.length) {
return null;
}
return this.selectedValue ?? null;
}
};
// packages/ag-grid-enterprise/src/advancedFilter/autocomplete/agAutocomplete.ts
var AgAutocompleteElement = {
tag: "div",
cls: "ag-autocomplete",
role: "presentation",
children: [
{
tag: "ag-input-text-field",
ref: "eAutocompleteInput"
}
]
};
var AgAutocomplete = class extends import_ag_grid_community18.Component {
constructor() {
super(AgAutocompleteElement, [import_ag_grid_community18.AgInputTextFieldSelector]);
this.eAutocompleteInput = import_ag_grid_community18.RefPlaceholder;
this.isListOpen = false;
this.lastPosition = 0;
this.valid = true;
this.registerCSS(agAutocompleteCSS);
}
wireBeans(beans) {
this.popupSvc = beans.popupSvc;
}
postConstruct() {
this.eAutocompleteInput.onValueChange((value) => this.onValueChanged(value));
this.eAutocompleteInput.getInputElement().setAttribute("autocomplete", "off");
this.addGuiEventListener("keydown", this.onKeyDown.bind(this));
this.addGuiEventListener("click", this.updatePositionAndList.bind(this));
this.addDestroyFunc(() => {
this.destroyBean(this.autocompleteList);
});
this.addGuiEventListener("focusout", () => this.onFocusOut());
}
onValueChanged(value) {
const parsedValue = (0, import_ag_grid_community18._makeNull)(value);
this.updateValue(parsedValue);
this.updateAutocompleteList(parsedValue);
}
updateValue(value) {
this.updateLastPosition();
this.dispatchLocalEvent({
type: "eventValueChanged",
value
});
this.validate(value);
}
updateAutocompleteList(value) {
const autocompleteListParams = this.listGenerator?.(value, this.lastPosition) ?? { enabled: false };
if (!autocompleteListParams.type || autocompleteListParams.type !== this.autocompleteListParams?.type) {
if (this.isListOpen) {
this.closeList();
}
}
const isListOpen = this.isListOpen;
this.autocompleteListParams = autocompleteListParams;
if (autocompleteListParams?.enabled) {
if (!isListOpen) {
this.openList();
}
const { searchString } = autocompleteListParams;
this.autocompleteList.setSearch(searchString ?? "");
} else {
if (isListOpen) {
this.closeList();
}
}
}
onKeyDown(event) {
const key = event.key;
this.updateLastPosition();
switch (key) {
case import_ag_grid_community18.KeyCode.ENTER:
this.onEnterKeyDown(event);
break;
case import_ag_grid_community18.KeyCode.TAB:
this.onTabKeyDown(event);
break;
case import_ag_grid_community18.KeyCode.DOWN:
case import_ag_grid_community18.KeyCode.UP:
this.onUpDownKeyDown(event, key);
break;
case import_ag_grid_community18.KeyCode.LEFT:
case import_ag_grid_community18.KeyCode.RIGHT:
case import_ag_grid_community18.KeyCode.PAGE_HOME:
case import_ag_grid_community18.KeyCode.PAGE_END:
setTimeout(() => {
this.updatePositionAndList();
});
break;
case import_ag_grid_community18.KeyCode.ESCAPE:
this.onEscapeKeyDown(event);
break;
case import_ag_grid_community18.KeyCode.SPACE:
if (event.ctrlKey && !this.isListOpen) {
event.preventDefault();
this.forceOpenList();
}
break;
}
}
confirmSelection() {
const selectedValue = this.autocompleteList?.getSelectedValue();
if (selectedValue) {
this.closeList();
this.dispatchLocalEvent({
type: "eventOptionSelected",
value: this.getValue(),
position: this.lastPosition,
updateEntry: selectedValue,
autocompleteType: this.autocompleteListParams.type
});
}
}
onTabKeyDown(event) {
if (this.isListOpen) {
event.preventDefault();
event.stopPropagation();
this.confirmSelection();
}
}
onEnterKeyDown(event) {
event.preventDefault();
if (this.isListOpen) {
this.confirmSelection();
} else {
this.onCompleted();
}
}
onUpDownKeyDown(event, key) {
event.preventDefault();
if (!this.isListOpen) {
this.forceOpenList();
} else {
this.autocompleteList?.onNavigationKeyDown(event, key);
}
}
onEscapeKeyDown(event) {
if (this.isListOpen) {
event.preventDefault();
event.stopPropagation();
this.closeList();
this.setCaret(this.lastPosition, true);
}
}
onFocusOut() {
if (this.isListOpen) {
this.closeList();
}
}
updatePositionAndList() {
this.updateLastPosition();
this.updateAutocompleteList(this.eAutocompleteInput.getValue() ?? null);
}
setCaret(position, setFocus) {
if (setFocus || (0, import_ag_grid_community18._isNothingFocused)(this.beans)) {
this.eAutocompleteInput.getFocusableElement().focus();
}
const eInput = this.eAutocompleteInput.getInputElement();
eInput.setSelectionRange(position, position);
if (position === eInput.value.length) {
eInput.scrollLeft = eInput.scrollWidth;
}
}
forceOpenList() {
this.onValueChanged(this.eAutocompleteInput.getValue());
}
updateLastPosition() {
this.lastPosition = this.eAutocompleteInput.getInputElement().selectionStart ?? 0;
}
validate(value) {
if (!this.validator) {
return;
}
const validationMessage = this.validationMessage = this.validator(value);
this.eAutocompleteInput.getInputElement().setCustomValidity(validationMessage ?? "");
this.valid = !validationMessage;
this.dispatchLocalEvent({
type: "eventValidChanged",
isValid: this.valid,
validationMessage
});
}
openList() {
this.isListOpen = true;
this.autocompleteList = this.createBean(
new AgAutocompleteList({
autocompleteEntries: this.autocompleteListParams.entries,
onConfirmed: () => this.confirmSelection(),
forceLastSelection: this.forceLastSelection
})
);
const ePopupGui = this.autocompleteList.getGui();
const positionParams = {
ePopup: ePopupGui,
type: "autocomplete",
eventSource: this.getGui(),
position: "under",
alignSide: this.gos.get("enableRtl") ? "right" : "left",
keepWithinBounds: true
};
const addPopupRes = this.popupSvc.addPopup({
eChild: ePopupGui,
anchorToElement: this.getGui(),
positionCallback: () => this.popupSvc.positionPopupByComponent(positionParams),
ariaLabel: this.listAriaLabel
});
this.hidePopup = addPopupRes.hideFunc;
this.autocompleteList.afterGuiAttached();
}
closeList() {
this.isListOpen = false;
this.hidePopup();
this.destroyBean(this.autocompleteList);
this.autocompleteList = null;
}
onCompleted() {
if (this.isListOpen) {
this.closeList();
}
this.dispatchLocalEvent({
type: "eventValueConfirmed",
value: this.getValue(),
isValid: this.isValid()
});
}
getValue() {
return (0, import_ag_grid_community18._makeNull)(this.eAutocompleteInput.getValue());
}
setInputPlaceholder(placeholder) {
this.eAutocompleteInput.setInputPlaceholder(placeholder);
return this;
}
setInputAriaLabel(label) {
this.eAutocompleteInput.setInputAriaLabel(label);
return this;
}
setListAriaLabel(label) {
this.listAriaLabel = label;
return this;
}
setListGenerator(listGenerator) {
this.listGenerator = listGenerator;
return this;
}
setValidator(validator) {
this.validator = validator;
return this;
}
isValid() {
return this.valid;
}
setValue(params) {
const { value, position, silent, updateListOnlyIfOpen, restoreFocus } = params;
this.eAutocompleteInput.setValue(value, true);
this.setCaret(position ?? this.lastPosition, restoreFocus);
if (!silent) {
this.updateValue(value);
}
if (!updateListOnlyIfOpen || this.isListOpen) {
this.updateAutocompleteList(value);
}
}
setForceLastSelection(forceLastSelection) {
this.forceLastSelection = forceLastSelection;
return this;
}
setInputDisabled(disabled) {
this.eAutocompleteInput.setDisabled(disabled);
return this;
}
};
var AgAutocompleteSelector = {
selector: "AG-AUTOCOMPLETE",
component: AgAutocomplete
};
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterComp.ts
var DEFAULT_ADVANCED_FILTER_PARAMS = {
buttons: ["apply"],
suppressBuilderButton: false
};
var ButtonLocaleMap = {
apply: "advancedFilterApply",
clear: "advancedFilterClear",
cancel: "advancedFilterCancel",
reset: "advancedFilterReset"
};
var AdvancedFilterElement = {
tag: "div",
cls: "ag-advanced-filter",
role: "presentation",
attrs: { tabindex: "-1" },
children: [
{ tag: "ag-autocomplete", ref: "eAutocomplete" },
{
tag: "ag-filter-button",
ref: "eButtons",
cls: "ag-advanced-filter-buttons"
},
{
tag: "button",
ref: "eBuilderFilterButton",
cls: "ag-button ag-advanced-filter-builder-button",
children: [
{ tag: "span", ref: "eBuilderFilterButtonIcon", attrs: { "aria-hidden": "true" } },
{ tag: "span", ref: "eBuilderFilterButtonLabel", cls: "ag-advanced-filter-builder-button-label" }
]
}
]
};
var AdvancedFilterComp = class extends import_ag_grid_community19.Component {
constructor() {
super(AdvancedFilterElement, [AgAutocompleteSelector, import_ag_grid_community19.AgFilterButtonSelector]);
this.eAutocomplete = import_ag_grid_community19.RefPlaceholder;
this.eButtons = import_ag_grid_community19.RefPlaceholder;
this.eBuilderFilterButton = import_ag_grid_community19.RefPlaceholder;
this.eBuilderFilterButtonIcon = import_ag_grid_community19.RefPlaceholder;
this.eBuilderFilterButtonLabel = import_ag_grid_community19.RefPlaceholder;
this.expressionParser = null;
this.isApplyDisabled = true;
this.builderOpen = false;
}
wireBeans(beans) {
this.advFilterExpSvc = beans.advFilterExpSvc;
this.advancedFilter = beans.advancedFilter;
this.filterManager = beans.filterManager;
this.registry = beans.registry;
}
postConstruct() {
this.tooltipFeature = this.createOptionalManagedBean(
this.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.getGui(),
getTooltipShowDelayOverride: () => 1e3,
getLocation: () => "advancedFilter"
})
);
this.eAutocomplete.setListGenerator((_value, position) => this.generateAutocompleteListParams(position)).setValidator(() => this.validateValue()).setForceLastSelection(
(lastSelection, searchString) => this.forceLastSelection(lastSelection, searchString)
).setInputAriaLabel(this.advFilterExpSvc.translate("ariaAdvancedFilterInput")).setListAriaLabel(this.advFilterExpSvc.translate("ariaLabelAdvancedFilterAutocomplete"));
this.refresh();
this.addManagedListeners(this.eAutocomplete, {
eventValueChanged: ({ value }) => this.onValueChanged(value),
eventValueConfirmed: ({ isValid }) => this.onValueConfirmed(isValid),
eventOptionSelected: ({ position, updateEntry, autocompleteType }) => this.onOptionSelected(position, updateEntry, autocompleteType),
eventValidChanged: ({ isValid, validationMessage }) => this.onValidChanged(isValid, validationMessage)
});
const { buttons, suppressBuilderButton } = {
...DEFAULT_ADVANCED_FILTER_PARAMS,
...this.gos.get("advancedFilterParams")
};
this.setupButtons(buttons);
this.setupBuilderButton(suppressBuilderButton);
this.beans.gos.addManagedPropertyListener("advancedFilterParams", (event) => {
const currentValue = { ...DEFAULT_ADVANCED_FILTER_PARAMS, ...event.currentValue };
const previousValue = { ...DEFAULT_ADVANCED_FILTER_PARAMS, ...event.previousValue };
if (currentValue.buttons !== previousValue.buttons) {
const buttons2 = currentValue.buttons.map((type) => ({
type,
label: this.advFilterExpSvc.translate(ButtonLocaleMap[type])
}));
this.eButtons.updateButtons(buttons2);
}
if (currentValue.suppressBuilderButton !== previousValue.suppressBuilderButton) {
(0, import_ag_grid_community19._setDisplayed)(this.eBuilderFilterButton, !currentValue.suppressBuilderButton);
}
});
}
refresh() {
const expression = this.advancedFilter.getExpressionDisplayValue();
this.eAutocomplete.setValue({
value: expression ?? "",
position: expression?.length,
updateListOnlyIfOpen: true
});
}
setInputDisabled(disabled) {
this.eAutocomplete.setInputDisabled(disabled);
this.eButtons.updateValidity(
!disabled && !this.isApplyDisabled && !this.advancedFilter.isCurrentExpressionApplied()
);
}
setupButtons(actions) {
const buttons = actions.map((type) => ({
type,
label: this.advFilterExpSvc.translate(ButtonLocaleMap[type])
}));
const getListener = (action) => () => {
this.updateModel(action);
};
this.eButtons.addManagedListeners(this.eButtons, {
apply: getListener("apply"),
clear: getListener("clear"),
reset: getListener("reset"),
cancel: getListener("cancel")
});
this.eButtons.updateButtons(buttons);
}
updateModel(action) {
switch (action) {
case "apply":
this.onValueConfirmed(this.eAutocomplete.isValid());
break;
case "reset":
this.advancedFilter.setModel(null);
this.filterManager?.onFilterChanged({ source: "advancedFilter" });
break;
case "cancel":
this.advancedFilter.setModel(this.advancedFilter.getModel());
this.filterManager?.onFilterChanged({ source: "advancedFilter" });
break;
case "clear":
this.eAutocomplete.setValue({
value: "",
restoreFocus: true
});
break;
}
}
setupBuilderButton(suppressed) {
this.eBuilderFilterButtonIcon.appendChild((0, import_ag_grid_community19._createIconNoSpan)("advancedFilterBuilder", this.beans));
this.eBuilderFilterButtonLabel.textContent = this.advFilterExpSvc.translate("advancedFilterBuilder");
this.activateTabIndex([this.eBuilderFilterButton]);
this.addManagedElementListeners(this.eBuilderFilterButton, { click: () => this.openBuilder() });
this.addManagedListeners(this.advancedFilter.getCtrl(), {
advancedFilterBuilderClosed: () => this.closeBuilder()
});
(0, import_ag_grid_community19._setDisplayed)(this.eBuilderFilterButton, !suppressed);
}
onValueChanged(value) {
value = (0, import_ag_grid_community19._makeNull)(value);
this.advancedFilter.setExpressionDisplayValue(value);
this.expressionParser = this.advancedFilter.createExpressionParser(value);
const updatedExpression = this.expressionParser?.parseExpression();
if (updatedExpression && updatedExpression !== value) {
this.eAutocomplete.setValue({ value: updatedExpression, silent: true, restoreFocus: true });
}
}
onValueConfirmed(isValid) {
if (!isValid || this.isApplyDisabled) {
return;
}
this.eButtons?.updateValidity(false);
this.advancedFilter.applyExpression();
this.filterManager?.onFilterChanged({ source: "advancedFilter" });
}
onOptionSelected(position, updateEntry, type) {
const { updatedValue, updatedPosition, hideAutocomplete } = this.updateExpression(position, updateEntry, type);
this.eAutocomplete.setValue({
value: updatedValue,
position: updatedPosition,
updateListOnlyIfOpen: hideAutocomplete,
restoreFocus: true
});
}
validateValue() {
return this.expressionParser?.isValid() ? null : this.expressionParser?.getValidationMessage() ?? null;
}
onValidChanged(isValid, validationMessage) {
this.isApplyDisabled = !isValid || this.advancedFilter.isCurrentExpressionApplied();
this.eButtons.updateValidity(!this.isApplyDisabled);
this.tooltipFeature?.setTooltipAndRefresh(validationMessage);
}
generateAutocompleteListParams(position) {
return this.expressionParser ? this.expressionParser.getAutocompleteListParams(position) : this.advFilterExpSvc.getDefaultAutocompleteListParams("");
}
updateExpression(position, updateEntry, type) {
this.advFilterExpSvc.updateAutocompleteCache(updateEntry, type);
return this.expressionParser?.updateExpression(position, updateEntry, type) ?? this.advancedFilter.getDefaultExpression(updateEntry);
}
forceLastSelection({ key, displayValue }, searchString) {
return !!searchString.toLocaleLowerCase().match(`^${(displayValue ?? key).toLocaleLowerCase()}\\s*$`);
}
openBuilder() {
if (this.builderOpen) {
return;
}
this.builderOpen = true;
(0, import_ag_grid_community19._setDisabled)(this.eBuilderFilterButton, true);
this.advancedFilter.getCtrl().toggleFilterBuilder({ source: "ui", eventSource: this.eBuilderFilterButton });
}
closeBuilder() {
if (!this.builderOpen) {
return;
}
this.builderOpen = false;
(0, import_ag_grid_community19._setDisabled)(this.eBuilderFilterButton, false);
this.eBuilderFilterButton.focus();
}
};
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterHeaderComp.ts
var import_ag_grid_community20 = require("ag-grid-community");
var AdvancedFilterHeaderElement = {
tag: "div",
cls: "ag-advanced-filter-header",
role: "row"
};
var AdvancedFilterHeaderComp = class extends import_ag_grid_community20.Component {
constructor(enabled) {
super(AdvancedFilterHeaderElement);
this.enabled = enabled;
}
wireBeans(beans) {
this.colModel = beans.colModel;
this.focusSvc = beans.focusSvc;
this.ctrlsSvc = beans.ctrlsSvc;
}
postConstruct() {
this.setupAdvancedFilter(this.enabled);
this.addDestroyFunc(() => this.destroyBean(this.eAdvancedFilter));
const heightListener = () => {
if (this.enabled) {
this.setEnabledHeight();
}
};
this.addManagedEventListeners({
gridColumnsChanged: () => this.onGridColumnsChanged(),
columnHeaderHeightChanged: heightListener,
gridStylesChanged: heightListener
});
this.addManagedPropertyListener("headerHeight", heightListener);
this.addManagedPropertyListener("floatingFiltersHeight", heightListener);
this.addGuiEventListener("keydown", (event) => this.onKeyDown(event));
this.addGuiEventListener("focusout", (event) => {
if (!this.getFocusableElement().contains(event.relatedTarget)) {
this.focusSvc.clearAdvancedFilterColumn();
}
});
}
getFocusableElement() {
return this.eAdvancedFilter?.getGui() ?? this.getGui();
}
setEnabled(enabled) {
if (enabled === this.enabled) {
return;
}
this.setupAdvancedFilter(enabled);
}
refresh() {
this.eAdvancedFilter?.refresh();
}
getHeight() {
return this.height;
}
setInputDisabled(disabled) {
this.eAdvancedFilter?.setInputDisabled(disabled);
}
setupAdvancedFilter(enabled) {
const eGui = this.getGui();
if (enabled) {
this.eAdvancedFilter = this.createBean(new AdvancedFilterComp());
const eAdvancedFilterGui = this.eAdvancedFilter.getGui();
this.eAdvancedFilter.addCss("ag-advanced-filter-header-cell");
this.setEnabledHeight();
this.setAriaRowIndex();
(0, import_ag_grid_community20._setAriaRole)(eAdvancedFilterGui, "gridcell");
(0, import_ag_grid_community20._setAriaColIndex)(eAdvancedFilterGui, 1);
this.setAriaColumnCount(eAdvancedFilterGui);
eGui.appendChild(eAdvancedFilterGui);
} else {
(0, import_ag_grid_community20._clearElement)(eGui);
this.destroyBean(this.eAdvancedFilter);
this.height = 0;
}
(0, import_ag_grid_community20._setDisplayed)(eGui, enabled);
this.enabled = enabled;
}
setEnabledHeight() {
const eGui = this.getGui();
this.height = (0, import_ag_grid_community20._getFloatingFiltersHeight)(this.beans);
const height = `${this.height}px`;
eGui.style.height = height;
eGui.style.minHeight = height;
}
setAriaColumnCount(eAdvancedFilterGui) {
(0, import_ag_grid_community20._setAriaColSpan)(eAdvancedFilterGui, this.colModel.getCols().length);
}
setAriaRowIndex() {
(0, import_ag_grid_community20._setAriaRowIndex)(this.getGui(), this.ctrlsSvc.getHeaderRowContainerCtrl()?.getRowCount() ?? 0);
}
onGridColumnsChanged() {
if (!this.eAdvancedFilter) {
return;
}
this.setAriaColumnCount(this.eAdvancedFilter.getGui());
this.setAriaRowIndex();
}
onKeyDown(event) {
switch (event.key) {
case import_ag_grid_community20.KeyCode.ENTER: {
if (this.hasFocus()) {
if ((0, import_ag_grid_community20._focusInto)(this.getFocusableElement())) {
event.preventDefault();
}
}
break;
}
case import_ag_grid_community20.KeyCode.ESCAPE:
if (!this.hasFocus()) {
this.getFocusableElement().focus();
}
break;
case import_ag_grid_community20.KeyCode.UP:
this.navigateUpDown(true, event);
break;
case import_ag_grid_community20.KeyCode.DOWN:
this.navigateUpDown(false, event);
break;
case import_ag_grid_community20.KeyCode.TAB:
if (this.hasFocus()) {
this.navigateLeftRight(event);
} else {
const nextFocusableEl = (0, import_ag_grid_community20._findNextFocusableElement)(
this.beans,
this.getFocusableElement(),
null,
event.shiftKey
);
if (nextFocusableEl) {
event.preventDefault();
nextFocusableEl.focus();
} else {
this.navigateLeftRight(event);
}
}
break;
}
}
navigateUpDown(backwards, event) {
if (this.hasFocus()) {
if (this.focusSvc.focusNextFromAdvancedFilter(backwards)) {
event.preventDefault();
}
}
}
navigateLeftRight(event) {
if (event.shiftKey ? this.focusSvc.focusLastHeader() : this.focusSvc.focusNextFromAdvancedFilter(false, true)) {
event.preventDefault();
}
}
hasFocus() {
return (0, import_ag_grid_community20._getActiveDomElement)(this.beans) === this.getFocusableElement();
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderComp.ts
var import_ag_grid_community37 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderDragFeature.ts
var import_ag_grid_community22 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/features/virtualListDragFeature.ts
var import_ag_grid_community21 = require("ag-grid-community");
var LIST_ITEM_HOVERED = "ag-list-item-hovered";
var VirtualListDragFeature = class extends import_ag_grid_community21.BeanStub {
constructor(comp, virtualList, params) {
super();
this.comp = comp;
this.virtualList = virtualList;
this.params = params;
this.currentDragValue = null;
this.lastHoveredListItem = null;
}
wireBeans(beans) {
this.dragAndDrop = beans.dragAndDrop;
}
postConstruct() {
this.addManagedListeners(this.params.eventSource, {
[this.params.listItemDragStartEvent]: this.listItemDragStart.bind(this),
[this.params.listItemDragEndEvent]: this.listItemDragEnd.bind(this)
});
this.createDropTarget();
this.createAutoScrollService();
}
listItemDragStart(event) {
this.currentDragValue = this.params.getCurrentDragValue(event);
this.moveBlocked = this.params.isMoveBlocked(this.currentDragValue);
}
listItemDragEnd() {
window.setTimeout(() => {
this.currentDragValue = null;
this.moveBlocked = false;
}, 10);
}
createDropTarget() {
const dropTarget = {
isInterestedIn: (type) => type === this.params.dragSourceType,
getIconName: () => this.moveBlocked ? "pinned" : "move",
getContainer: () => this.comp.getGui(),
onDragging: (e) => this.onDragging(e),
onDragStop: () => this.onDragStop(),
onDragLeave: () => this.onDragLeave(),
onDragCancel: () => this.onDragCancel()
};
this.dragAndDrop?.addDropTarget(dropTarget);
}
createAutoScrollService() {
const virtualListGui = this.virtualList.getGui();
this.autoScrollService = new import_ag_grid_community21.AutoScrollService({
scrollContainer: virtualListGui,
scrollAxis: "y",
getVerticalPosition: () => virtualListGui.scrollTop,
setVerticalPosition: (position) => virtualListGui.scrollTop = position
});
}
onDragging(e) {
if (!this.currentDragValue || this.moveBlocked) {
return;
}
const hoveredListItem = this.getListDragItem(e);
const comp = this.virtualList.getComponentAt(hoveredListItem.rowIndex);
if (!comp) {
return;
}
const el = comp.getGui().parentElement;
if (this.lastHoveredListItem && this.lastHoveredListItem.rowIndex === hoveredListItem.rowIndex && this.lastHoveredListItem.position === hoveredListItem.position) {
return;
}
this.autoScrollService.check(e.event);
this.clearHoveredItems();
this.lastHoveredListItem = hoveredListItem;
(0, import_ag_grid_community21._radioCssClass)(el, LIST_ITEM_HOVERED);
(0, import_ag_grid_community21._radioCssClass)(el, `ag-item-highlight-${hoveredListItem.position}`);
}
getListDragItem(e) {
const virtualListGui = this.virtualList.getGui();
const paddingTop = parseFloat(window.getComputedStyle(virtualListGui).paddingTop);
const rowHeight = this.virtualList.getRowHeight();
const scrollTop = this.virtualList.getScrollTop();
const rowIndex = Math.max(0, (e.y - paddingTop + scrollTop) / rowHeight);
const maxLen = this.params.getNumRows(this.comp) - 1;
const normalizedRowIndex = Math.min(maxLen, rowIndex) | 0;
return {
rowIndex: normalizedRowIndex,
position: Math.round(rowIndex) > rowIndex || rowIndex > maxLen ? "bottom" : "top",
component: this.virtualList.getComponentAt(normalizedRowIndex)
};
}
onDragStop() {
if (this.moveBlocked) {
return;
}
this.params.moveItem(this.currentDragValue, this.lastHoveredListItem);
this.clearDragProperties();
}
onDragCancel() {
this.clearDragProperties();
}
onDragLeave() {
this.clearDragProperties();
}
clearDragProperties() {
this.clearHoveredItems();
this.autoScrollService.ensureCleared();
}
clearHoveredItems() {
const virtualListGui = this.virtualList.getGui();
virtualListGui.querySelectorAll(`.${LIST_ITEM_HOVERED}`).forEach((el) => {
[LIST_ITEM_HOVERED, "ag-item-highlight-top", "ag-item-highlight-bottom"].forEach((cls) => {
el.classList.remove(cls);
});
});
this.lastHoveredListItem = null;
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderDragFeature.ts
var AdvancedFilterBuilderDragFeature = class extends import_ag_grid_community22.BeanStub {
constructor(comp, virtualList) {
super();
this.comp = comp;
this.virtualList = virtualList;
}
postConstruct() {
this.createManagedBean(
new VirtualListDragFeature(this.comp, this.virtualList, {
dragSourceType: import_ag_grid_community22.DragSourceType.AdvancedFilterBuilder,
listItemDragStartEvent: "advancedFilterBuilderDragStarted",
listItemDragEndEvent: "advancedFilterBuilderDragEnded",
eventSource: this,
getCurrentDragValue: (listItemDragStartEvent) => this.getCurrentDragValue(listItemDragStartEvent),
isMoveBlocked: () => false,
getNumRows: (comp) => comp.getNumItems(),
moveItem: (currentDragValue, lastHoveredListItem) => this.moveItem(currentDragValue, lastHoveredListItem)
})
);
}
getCurrentDragValue(listItemDragStartEvent) {
return listItemDragStartEvent.item;
}
moveItem(currentDragValue, lastHoveredListItem) {
this.comp.moveItem(currentDragValue, lastHoveredListItem);
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderItemAddComp.ts
var import_ag_grid_community31 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/advancedFilter/builder/addDropdownComp.ts
var import_ag_grid_community29 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/agRichSelect.ts
var import_ag_grid_community28 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/AgPillContainer.ts
var import_ag_grid_community25 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/agPill.ts
var import_ag_grid_community23 = require("ag-grid-community");
var import_ag_grid_community24 = require("ag-grid-community");
var AgPillElement = {
tag: "div",
cls: "ag-pill",
role: "option",
children: [
{
tag: "span",
ref: "eText",
cls: "ag-pill-text"
},
{
tag: "span",
ref: "eButton",
cls: "ag-button ag-pill-button",
role: "presentation"
}
]
};
var AgPill = class extends import_ag_grid_community24.Component {
constructor(config) {
super(AgPillElement);
this.config = config;
this.eText = import_ag_grid_community23.RefPlaceholder;
this.eButton = import_ag_grid_community23.RefPlaceholder;
}
postConstruct() {
const { config, eButton } = this;
const { onKeyDown, onButtonClick } = config;
this.getGui().setAttribute("tabindex", String(this.gos.get("tabIndex")));
this.addGuiEventListener("focus", () => {
this.eButton.focus();
});
if (onKeyDown) {
this.addGuiEventListener("keydown", onKeyDown);
}
if (onButtonClick) {
this.addManagedElementListeners(eButton, {
click: onButtonClick
});
}
}
toggleCloseButtonClass(className, force) {
this.eButton.classList.toggle(className, force);
}
setText(text) {
this.eText.textContent = text;
}
getText() {
return this.eText.textContent;
}
};
// packages/ag-grid-enterprise/src/widgets/AgPillContainer.ts
var AgPillContainerElement = {
tag: "div",
cls: "ag-pill-container"
};
var AgPillContainer = class extends import_ag_grid_community25.Component {
constructor() {
super(AgPillContainerElement);
this.pills = [];
}
init(params) {
this.params = params;
this.refresh();
}
refresh() {
this.clearPills();
const { params, onPillKeyDown } = this;
let values = params.getValue();
if (!Array.isArray(values)) {
if (values == null) {
return;
}
values = [values];
}
const valueFormatter = params.valueFormatter ?? ((v) => String(v));
const len = values.length;
(0, import_ag_grid_community25._setAriaRole)(this.getGui(), len === 0 ? "presentation" : "listbox");
for (let i = 0; i < len; i++) {
const value = values[i];
const pill = this.createBean(
new AgPill({
onButtonClick: () => this.onPillButtonClick(pill),
onKeyDown: onPillKeyDown.bind(this)
})
);
const pillGui = pill.getGui();
(0, import_ag_grid_community25._setAriaPosInSet)(pillGui, i + 1);
(0, import_ag_grid_community25._setAriaSetSize)(pillGui, len);
if (params.onPillMouseDown) {
pill.addGuiEventListener("mousedown", params.onPillMouseDown);
}
if (params.announceItemFocus) {
pill.addGuiEventListener("focus", params.announceItemFocus);
}
pill.setText(valueFormatter(value) ?? "");
pill.toggleCloseButtonClass("ag-icon-cancel", true);
this.appendChild(pillGui);
this.pills.push(pill);
}
}
onNavigationKeyDown(e) {
const { key } = e;
if (!this.pills.length || key !== import_ag_grid_community25.KeyCode.LEFT && key !== import_ag_grid_community25.KeyCode.RIGHT) {
return;
}
e.preventDefault();
const { params, beans } = this;
const activeEl = (0, import_ag_grid_community25._getActiveDomElement)(beans);
const eGui = this.getGui();
if (eGui.contains(activeEl)) {
const nextFocusableEl = (0, import_ag_grid_community25._findNextFocusableElement)(beans, eGui, false, key === import_ag_grid_community25.KeyCode.LEFT);
if (nextFocusableEl) {
nextFocusableEl.focus();
} else if (params.eWrapper) {
params.eWrapper.focus();
}
} else {
const focusableElements = (0, import_ag_grid_community25._findFocusableElements)(eGui);
if (focusableElements.length > 0) {
focusableElements[key === import_ag_grid_community25.KeyCode.RIGHT ? 0 : focusableElements.length - 1].focus();
}
}
}
clearPills() {
const eGui = this.getGui();
if (eGui.contains((0, import_ag_grid_community25._getActiveDomElement)(this.beans)) && this.params.eWrapper) {
this.params.eWrapper.focus();
}
(0, import_ag_grid_community25._clearElement)(eGui);
this.destroyBeans(this.pills);
this.pills = [];
}
onPillButtonClick(pill) {
this.deletePill(pill);
}
onPillKeyDown(e) {
const key = e.key;
if (key !== import_ag_grid_community25.KeyCode.DELETE && key !== import_ag_grid_community25.KeyCode.BACKSPACE) {
return;
}
e.preventDefault();
const eDoc = (0, import_ag_grid_community25._getDocument)(this.beans);
const pillIndex = this.pills.findIndex((pill2) => pill2.getGui().contains(eDoc.activeElement));
if (pillIndex === -1) {
return;
}
const pill = this.pills[pillIndex];
if (pill) {
this.deletePill(pill, pillIndex);
}
}
deletePill(pill, restoreFocusToIndex) {
const value = pill.getText();
const values = (this.params.getValue() || []).filter((val) => val !== value);
this.params.setValue(values);
if (!values.length && this.params.eWrapper) {
this.params.eWrapper.focus();
} else if (restoreFocusToIndex != null) {
const pill2 = this.pills[Math.min(restoreFocusToIndex, this.pills.length - 1)];
if (pill2) {
pill2.getFocusableElement().focus();
}
}
}
destroy() {
this.clearPills();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/widgets/agRichSelect.css-GENERATED.ts
var agRichSelectCSS = (
/*css*/
`.ag-rich-select{cursor:default;height:100%}.ag-rich-select-value{align-items:center;background-color:var(--ag-picker-button-background-color);display:flex;height:100%;padding:var(--ag-spacing);:where(.ag-picker-field-display){overflow:hidden;text-overflow:ellipsis;&:where(.ag-display-as-placeholder){opacity:.5}}}.ag-rich-select-list{background-color:var(--ag-picker-list-background-color);border:var(--ag-picker-list-border);border-radius:var(--ag-input-border-radius);box-shadow:var(--ag-dropdown-shadow);height:auto;position:relative;width:100%;:where(.ag-loading-text){padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding)}}.ag-rich-select-row{align-items:center;display:flex;flex:1 1 auto;height:100%;overflow:hidden;padding:0 var(--ag-spacing);white-space:nowrap}.ag-rich-select-row-selected{background-color:var(--ag-selected-row-background-color)}.ag-rich-select-row-highlighted,.ag-rich-select-row:hover{background-image:linear-gradient(var(--ag-row-hover-color),var(--ag-row-hover-color))}.ag-rich-select-row-text-highlight{font-weight:700}.ag-rich-select-field-input{flex:1 1 auto;:where(.ag-input-field-input){border:none!important;box-shadow:none!important;padding:0!important;text-overflow:ellipsis;&::-moz-placeholder{opacity:.8}&::placeholder{opacity:.8}}}:where(.ag-ltr) .ag-rich-select-field-input{left:var(--ag-spacing)}:where(.ag-rtl) .ag-rich-select-field-input{right:var(--ag-spacing)}:where(.ag-popup-editor) .ag-rich-select-value{height:var(--ag-row-height);min-width:200px}.ag-rich-select-virtual-list-item{cursor:default;height:var(--ag-list-item-height)}.ag-pill-container{display:flex;flex-wrap:nowrap;gap:.25rem}.ag-pill{align-items:center;background:var(--ag-select-cell-background-color);border:var(--ag-select-cell-border);border-radius:var(--ag-border-radius);display:flex;padding:0 .25rem;white-space:nowrap}.ag-pill-button{border:none;padding:0;&:hover{color:var(--ag-accent-color);cursor:pointer}}:where(.ag-ltr) .ag-pill-button{margin-left:var(--ag-spacing)}:where(.ag-rtl) .ag-pill-button{margin-right:var(--ag-spacing)}`
);
// packages/ag-grid-enterprise/src/widgets/agRichSelectList.ts
var import_ag_grid_community27 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/agRichSelectRow.ts
var import_ag_grid_community26 = require("ag-grid-community");
var RichSelectRowElement = { tag: "div", cls: "ag-rich-select-row", role: "presentation" };
var RichSelectRow = class extends import_ag_grid_community26.Component {
constructor(params) {
super(RichSelectRowElement);
this.params = params;
}
wireBeans(beans) {
this.userCompFactory = beans.userCompFactory;
this.registry = beans.registry;
}
postConstruct() {
this.tooltipFeature = this.createOptionalManagedBean(
this.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.getGui(),
shouldDisplayTooltip: () => this.shouldDisplayTooltip?.() ?? true
})
);
}
setState(value) {
const { params } = this;
const formattedValue = params.valueFormatter?.(value) ?? "";
const rendererSuccessful = this.populateWithRenderer(value, formattedValue);
if (!rendererSuccessful) {
this.populateWithoutRenderer(value, formattedValue);
}
this.value = value;
}
highlightString(matchString) {
const { parsedValue, params } = this;
if (params.cellRenderer || !(0, import_ag_grid_community26._exists)(parsedValue)) {
return;
}
let hasMatch = (0, import_ag_grid_community26._exists)(matchString);
if (hasMatch) {
const index = parsedValue?.toLocaleLowerCase().indexOf(matchString.toLocaleLowerCase());
if (index >= 0) {
const highlightEndIndex = index + matchString.length;
const child = this.getGui().querySelector("span");
if (child) {
(0, import_ag_grid_community26._clearElement)(child);
child.append(
// Start part
parsedValue.slice(0, index),
// Highlighted part wrapped in bold tag
(0, import_ag_grid_community26._createElement)({
tag: "span",
cls: "ag-rich-select-row-text-highlight",
children: parsedValue.slice(index, highlightEndIndex)
}),
// End part
parsedValue.slice(highlightEndIndex)
);
}
} else {
hasMatch = false;
}
}
if (!hasMatch) {
this.renderValueWithoutRenderer(parsedValue);
}
}
updateSelected(selected) {
const eGui = this.getGui();
(0, import_ag_grid_community26._setAriaSelected)(eGui.parentElement, selected);
this.toggleCss("ag-rich-select-row-selected", selected);
}
getValue() {
return this.value;
}
toggleHighlighted(highlighted) {
this.toggleCss("ag-rich-select-row-highlighted", highlighted);
}
populateWithoutRenderer(value, valueFormatted) {
const eGui = this.getGui();
const span = (0, import_ag_grid_community26._createElement)({ tag: "span" });
span.style.overflow = "hidden";
span.style.textOverflow = "ellipsis";
const parsedValue = (0, import_ag_grid_community26._toString)((0, import_ag_grid_community26._exists)(valueFormatted) ? valueFormatted : value);
this.parsedValue = (0, import_ag_grid_community26._exists)(parsedValue) ? parsedValue : null;
eGui.appendChild(span);
this.renderValueWithoutRenderer(parsedValue);
this.shouldDisplayTooltip = (0, import_ag_grid_community26._isElementOverflowingCallback)(() => span);
this.tooltipFeature?.setTooltipAndRefresh(this.parsedValue);
}
renderValueWithoutRenderer(value) {
const span = this.getGui().querySelector("span");
if (!span) {
return;
}
span.textContent = (0, import_ag_grid_community26._exists)(value) ? value : "\xA0";
}
populateWithRenderer(value, valueFormatted) {
let cellRendererPromise;
let userCompDetails;
if (this.params.cellRenderer) {
const richSelect = this.getParentComponent()?.getParentComponent();
userCompDetails = (0, import_ag_grid_community26._getEditorRendererDetails)(
this.userCompFactory,
this.params,
(0, import_ag_grid_community26._addGridCommonParams)(this.gos, {
value,
valueFormatted,
getValue: () => richSelect?.getValue(),
setValue: (value2) => {
richSelect?.setValue(value2, true);
},
setTooltip: (value2, shouldDisplayTooltip) => {
this.gos.assertModuleRegistered("Tooltip", 3);
this.shouldDisplayTooltip = shouldDisplayTooltip;
this.tooltipFeature?.setTooltipAndRefresh(value2);
}
})
);
}
if (userCompDetails) {
cellRendererPromise = userCompDetails.newAgStackInstance();
}
if (cellRendererPromise) {
_bindCellRendererToHtmlElement(cellRendererPromise, this.getGui());
}
if (cellRendererPromise) {
cellRendererPromise.then((childComponent) => {
this.addDestroyFunc(() => {
this.destroyBean(childComponent);
});
});
return true;
}
return false;
}
};
// packages/ag-grid-enterprise/src/widgets/agRichSelectList.ts
var LIST_COMPONENT_NAME = "ag-rich-select-list";
var ROW_COMPONENT_NAME = "ag-rich-select-row";
var AgRichSelectList = class extends VirtualList {
constructor(params, richSelectWrapper, getSearchString2) {
super({ cssIdentifier: "rich-select" });
this.params = params;
this.richSelectWrapper = richSelectWrapper;
this.getSearchString = getSearchString2;
this.lastRowHovered = -1;
this.selectedItems = /* @__PURE__ */ new Set();
this.params = params;
this.setComponentCreator(this.createRowComponent.bind(this));
this.setComponentUpdater(() => {
});
}
postConstruct() {
super.postConstruct();
this.eLoading = (0, import_ag_grid_community27._createElement)({
tag: "div",
cls: "ag-loading-text",
children: this.getLocaleTextFunc()("loadingOoo", "Loading...")
});
const { cellRowHeight, pickerAriaLabelKey, pickerAriaLabelValue } = this.params;
if (cellRowHeight) {
this.setRowHeight(cellRowHeight);
}
const eGui = this.getGui();
const eListAriaEl = this.getAriaElement();
this.addManagedListeners(eGui, {
mousemove: this.onMouseMove.bind(this),
mouseout: this.onMouseOut.bind(this),
mousedown: this.onMouseDown.bind(this),
click: this.onClick.bind(this)
});
eGui.classList.add(LIST_COMPONENT_NAME);
const listId = `${LIST_COMPONENT_NAME}-${this.getCompId()}`;
eListAriaEl.setAttribute("id", listId);
const translate = this.getLocaleTextFunc();
const ariaLabel = translate(pickerAriaLabelKey, pickerAriaLabelValue);
(0, import_ag_grid_community27._setAriaLabel)(eListAriaEl, ariaLabel);
(0, import_ag_grid_community27._setAriaControlsAndLabel)(this.richSelectWrapper, eListAriaEl);
}
navigateToPage(key) {
const newIndex = super.navigateToPage(key, this.lastRowHovered);
if (newIndex != null) {
(0, import_ag_grid_community27._requestAnimationFrame)(this.beans, () => {
if (!this.isAlive()) {
return null;
}
this.highlightIndex(newIndex);
});
}
return newIndex;
}
drawVirtualRows(softRefresh) {
super.drawVirtualRows(softRefresh);
this.refreshSelectedItems();
}
highlightFilterMatch(searchString) {
this.forEachRenderedRow((cmp) => {
cmp.highlightString(searchString);
});
}
onNavigationKeyDown(key, announceItem) {
(0, import_ag_grid_community27._requestAnimationFrame)(this.beans, () => {
if (!this.currentList || !this.isAlive()) {
return;
}
const len = this.currentList.length;
const oldIndex = this.lastRowHovered;
const diff = key === import_ag_grid_community27.KeyCode.DOWN ? 1 : -1;
const newIndex = Math.min(Math.max(oldIndex === -1 ? 0 : oldIndex + diff, 0), len - 1);
this.highlightIndex(newIndex);
announceItem();
});
}
selectValue(value) {
if (!this.currentList) {
if (this.eLoading) {
this.appendChild(this.eLoading);
}
return false;
}
if (this.eLoading?.offsetParent) {
this.eLoading.parentElement?.removeChild(this.eLoading);
}
if (value == null) {
return false;
}
const selectedPositions = this.getIndicesForValues(value);
const refresh = selectedPositions.length > 0;
if (refresh) {
this.refresh();
this.ensureIndexVisible(selectedPositions[0]);
this.refresh(true);
}
this.selectListItems(Array.isArray(value) ? value : [value]);
return refresh;
}
selectListItems(values, append = false) {
if (!append) {
this.selectedItems.clear();
}
for (let i = 0; i < values.length; i++) {
const currentItem = values[i];
if (this.findItemInSelected(currentItem) !== void 0) {
continue;
}
this.selectedItems.add(currentItem);
}
this.refreshSelectedItems();
}
getCurrentList() {
return this.currentList;
}
setCurrentList(list) {
this.currentList = list;
this.setModel({
getRowCount: () => list.length,
getRow: (index) => list[index],
areRowsEqual: (oldRow, newRow) => oldRow === newRow
});
}
getSelectedItems() {
return this.selectedItems;
}
getLastItemHovered() {
return this.currentList[this.lastRowHovered];
}
highlightIndex(index, preventUnnecessaryScroll) {
if (!this.currentList) {
return;
}
if (index < 0 || index >= this.currentList.length) {
this.lastRowHovered = -1;
} else {
this.lastRowHovered = index;
const wasScrolled = this.ensureIndexVisible(index, !preventUnnecessaryScroll);
if (wasScrolled && !preventUnnecessaryScroll) {
this.refresh(true);
}
}
this.forEachRenderedRow((cmp, idx) => {
const highlighted = index === idx;
cmp.toggleHighlighted(highlighted);
if (highlighted) {
const idForParent = `${ROW_COMPONENT_NAME}-${cmp.getCompId()}`;
(0, import_ag_grid_community27._setAriaActiveDescendant)(this.richSelectWrapper, idForParent);
this.richSelectWrapper.setAttribute("data-active-option", idForParent);
}
});
}
getIndicesForValues(values) {
const { currentList } = this;
if (!currentList || currentList.length === 0 || values == null) {
return [];
}
if (!Array.isArray(values)) {
values = [values];
}
if (values.length === 0) {
return [];
}
const { valueFormatter } = this.params;
const positions = [];
const isObject = typeof values[0] === "object";
const formattedList = currentList.map(valueFormatter);
for (const value of values) {
let idx = -1;
if (isObject) {
idx = formattedList.indexOf(valueFormatter(value));
} else {
idx = currentList.indexOf(value);
}
if (idx >= 0) {
positions.push(idx);
}
}
return positions;
}
toggleListItemSelection(value) {
const item = this.findItemInSelected(value);
if (item !== void 0) {
this.selectedItems.delete(item);
} else {
this.selectedItems.add(value);
}
this.refreshSelectedItems();
this.dispatchValueSelected();
}
refreshSelectedItems() {
this.forEachRenderedRow((cmp) => {
const selected = this.findItemInSelected(cmp.getValue()) !== void 0;
cmp.updateSelected(selected);
});
}
findItemInSelected(value) {
if (typeof value === "object") {
const valueFormatter = this.params.valueFormatter;
const valueFormatted = valueFormatter(value);
for (const item of this.selectedItems) {
if (valueFormatter(item) === valueFormatted) {
return item;
}
}
} else {
return this.selectedItems.has(value) ? value : void 0;
}
}
createRowComponent(value, listItemElement) {
const row = new RichSelectRow(this.params);
listItemElement.setAttribute("id", `${ROW_COMPONENT_NAME}-${row.getCompId()}`);
row.setParentComponent(this);
this.createBean(row);
row.setState(value);
const { highlightMatch, searchType = "fuzzy" } = this.params;
if (highlightMatch && searchType !== "fuzzy") {
row.highlightString(this.getSearchString());
}
return row;
}
getRowForMouseEvent(e) {
if (!this.model) {
return -1;
}
const eGui = this.getGui();
const rect = eGui.getBoundingClientRect();
const scrollTop = this.getScrollTop();
const mouseY = e.clientY - rect.top + scrollTop;
return Math.min(Math.floor(mouseY / this.getRowHeight()), this.model.getRowCount() - 1);
}
onMouseMove(e) {
const row = this.getRowForMouseEvent(e);
if (row !== -1 && row != this.lastRowHovered) {
this.lastRowHovered = row;
this.highlightIndex(row, true);
}
}
onMouseDown(e) {
e.preventDefault();
}
onMouseOut(e) {
if (!this.getGui().contains(e.relatedTarget)) {
this.highlightIndex(-1);
}
}
onClick(e) {
const { multiSelect } = this.params;
if (!this.currentList) {
return;
}
const row = this.getRowForMouseEvent(e);
const item = this.currentList[row];
if (multiSelect) {
this.toggleListItemSelection(item);
} else {
this.selectListItems([item]);
this.dispatchValueSelected();
}
}
dispatchValueSelected() {
this.dispatchLocalEvent({
type: "richSelectListRowSelected",
fromEnterKey: false,
value: this.selectedItems
});
}
destroy() {
super.destroy();
this.eLoading = void 0;
}
};
// packages/ag-grid-enterprise/src/widgets/agRichSelect.ts
var AgRichSelectElement = {
tag: "div",
cls: "ag-picker-field",
role: "presentation",
children: [
{ tag: "div", ref: "eLabel" },
{
tag: "div",
ref: "eWrapper",
cls: "ag-wrapper ag-picker-field-wrapper ag-rich-select-value ag-picker-collapsed",
children: [
{ tag: "span", ref: "eDisplayField", cls: "ag-picker-field-display" },
{ tag: "ag-input-text-field", ref: "eInput", cls: "ag-rich-select-field-input" },
{
tag: "span",
ref: "eDeselect",
cls: "ag-rich-select-deselect-button ag-picker-field-icon",
role: "presentation"
},
{ tag: "span", ref: "eIcon", cls: "ag-picker-field-icon", attrs: { "aria-hidden": "true" } }
]
}
]
};
var AgRichSelect = class extends import_ag_grid_community28.AgPickerField {
constructor(config) {
super({
pickerAriaLabelKey: "ariaLabelRichSelectField",
pickerAriaLabelValue: "Rich Select Field",
pickerType: "ag-list",
className: "ag-rich-select",
pickerIcon: "richSelectOpen",
ariaRole: "combobox",
template: config?.template ?? AgRichSelectElement,
agComponents: [import_ag_grid_community28.AgInputTextFieldSelector],
modalPicker: false,
...config,
// maxPickerHeight needs to be set after expanding `config`
maxPickerHeight: config?.maxPickerHeight ?? "calc(var(--ag-row-height) * 6.5)"
});
this.searchString = "";
this.searchStringCreator = null;
this.eInput = import_ag_grid_community28.RefPlaceholder;
this.eDeselect = import_ag_grid_community28.RefPlaceholder;
this.skipWrapperAnnouncement = false;
const { value, valueList, searchStringCreator } = config || {};
if (value !== void 0) {
this.value = value;
}
if (searchStringCreator) {
this.searchStringCreator = searchStringCreator;
}
if (valueList != null) {
this.setValues(valueList);
}
this.registerCSS(agRichSelectCSS);
}
wireBeans(beans) {
this.userCompFactory = beans.userCompFactory;
this.ariaAnnounce = beans.ariaAnnounce;
this.registry = beans.registry;
}
postConstruct() {
this.tooltipFeature = this.createOptionalManagedBean(
this.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.getGui(),
shouldDisplayTooltip: () => this.shouldDisplayTooltip?.() ?? true
})
);
super.postConstruct();
this.createListComponent();
this.eDeselect.appendChild((0, import_ag_grid_community28._createIconNoSpan)("richSelectRemove", this.beans));
const { allowTyping, placeholder, suppressDeselectAll } = this.config;
this.eDeselect.classList.add("ag-hidden");
if (allowTyping) {
this.eInput.setAutoComplete(false).setInputPlaceholder(placeholder);
this.eDisplayField.classList.add("ag-hidden");
} else {
this.eInput.setDisplayed(false);
}
this.setupAriaProperties();
const { searchDebounceDelay = 300 } = this.config;
this.clearSearchString = (0, import_ag_grid_community28._debounce)(this, this.clearSearchString.bind(this), searchDebounceDelay);
this.renderSelectedValue();
if (allowTyping) {
this.eInput.onValueChange((value) => this.searchTextFromString(value));
}
this.addManagedElementListeners(this.eWrapper, { focus: this.onWrapperFocus.bind(this) });
this.addManagedElementListeners(this.eWrapper, { focusout: this.onWrapperFocusOut.bind(this) });
if (!suppressDeselectAll) {
this.addManagedElementListeners(this.eDeselect, {
mousedown: this.onDeselectAllMouseDown.bind(this),
click: this.onDeselectAllClick.bind(this)
});
}
}
setupAriaProperties() {
const { eWrapper, gos } = this;
eWrapper.tabIndex = gos.get("tabIndex");
const translate = this.getLocaleTextFunc();
this.ariaDeleteSelection = translate("ariaLabelRichSelectDeleteSelection", "Press DELETE to deselect item");
this.ariaDeselectAllItems = translate(
"ariaLabelRichSelectDeselectAllItems",
"Press DELETE to deselect all items"
);
this.ariaToggleSelection = translate("ariaLabelRichSelectToggleSelection", "Press SPACE to toggle selection");
}
createListComponent() {
this.listComponent = this.createBean(
new AgRichSelectList(this.config, this.getFocusableElement(), () => this.searchString)
);
this.listComponent.setParentComponent(this);
this.addManagedListeners(this.listComponent, {
richSelectListRowSelected: (e) => {
this.onListValueSelected(e.value, e.fromEnterKey);
}
});
}
renderSelectedValue() {
const { value, eDisplayField, config, gos } = this;
const {
allowTyping,
cellRenderer,
initialInputValue,
multiSelect,
suppressDeselectAll,
suppressMultiSelectPillRenderer,
valueFormatter
} = config;
const valueFormatted = formatValueFn(value, valueFormatter);
if (allowTyping) {
this.eInput.setValue(initialInputValue ?? valueFormatted);
return;
}
if (multiSelect && !suppressDeselectAll) {
const isEmpty = value == null || Array.isArray(value) && value.length === 0;
this.eDeselect.classList.toggle("ag-hidden", isEmpty);
}
let userCompDetails;
if (multiSelect && !suppressMultiSelectPillRenderer) {
this.createOrUpdatePillContainer(eDisplayField);
return;
}
if (cellRenderer) {
userCompDetails = (0, import_ag_grid_community28._getEditorRendererDetails)(
this.userCompFactory,
config,
(0, import_ag_grid_community28._addGridCommonParams)(this.gos, {
value,
valueFormatted,
getValue: () => this.getValue(),
setValue: (value2) => {
this.setValue(value2, true);
},
setTooltip: (value2, shouldDisplayTooltip) => {
gos.assertModuleRegistered("Tooltip", 3);
this.shouldDisplayTooltip = shouldDisplayTooltip;
this.tooltipFeature?.setTooltipAndRefresh(value2);
}
})
);
}
let userCompDetailsPromise;
if (userCompDetails) {
userCompDetailsPromise = userCompDetails.newAgStackInstance();
}
if (userCompDetailsPromise) {
(0, import_ag_grid_community28._clearElement)(eDisplayField);
_bindCellRendererToHtmlElement(userCompDetailsPromise, eDisplayField);
userCompDetailsPromise.then((renderer) => {
this.addDestroyFunc(() => this.destroyBean(renderer));
});
} else {
if ((0, import_ag_grid_community28._exists)(this.value)) {
eDisplayField.innerText = valueFormatted;
eDisplayField.classList.remove("ag-display-as-placeholder");
} else {
const { placeholder } = config;
if ((0, import_ag_grid_community28._exists)(placeholder)) {
eDisplayField.textContent = placeholder;
eDisplayField.classList.add("ag-display-as-placeholder");
} else {
(0, import_ag_grid_community28._clearElement)(eDisplayField);
}
}
this.shouldDisplayTooltip = (0, import_ag_grid_community28._isElementOverflowingCallback)(() => this.eDisplayField);
this.tooltipFeature?.setTooltipAndRefresh(valueFormatted ?? null);
}
}
createPickerComponent() {
const { values } = this;
if (values) {
this.setValueList({ valueList: values });
}
return this.listComponent;
}
setSearchStringCreator(searchStringFn) {
this.searchStringCreator = searchStringFn;
}
setValueList(params) {
const { valueList, refresh } = params;
if (!this.listComponent || this.listComponent.getCurrentList() === valueList) {
return;
}
this.listComponent.setCurrentList(valueList);
if (refresh) {
if (!this.values) {
this.setValues(valueList);
if (this.isPickerDisplayed) {
const hasRefreshed = this.listComponent.selectValue(this.value);
if (!hasRefreshed) {
this.listComponent.refresh();
}
}
} else {
this.listComponent.refresh(true);
}
this.alignPickerToComponent();
}
}
/**
* This method updates the list of values
*/
setValues(values) {
this.values = values;
this.searchStrings = this.getSearchStringsFromValues(values);
}
showPicker() {
super.showPicker();
const { listComponent, value } = this;
if (!listComponent) {
return;
}
let idx = null;
listComponent.selectValue(this.value);
if (this.value != null) {
idx = listComponent.getIndicesForValues(Array.isArray(value) ? value : [value])[0];
}
if (idx != null) {
listComponent.highlightIndex(idx);
} else {
listComponent.refresh();
}
this.displayOrHidePicker();
}
beforeHidePicker() {
super.beforeHidePicker();
}
createOrUpdatePillContainer(container) {
if (!this.pillContainer) {
const pillContainer = this.pillContainer = this.createBean(new AgPillContainer());
this.addDestroyFunc(() => {
this.destroyBean(this.pillContainer);
this.pillContainer = null;
});
(0, import_ag_grid_community28._clearElement)(container);
container.appendChild(pillContainer.getGui());
const { config, eWrapper, ariaDeleteSelection } = this;
const { valueFormatter } = config;
pillContainer.init({
eWrapper,
valueFormatter,
onPillMouseDown: (e) => {
e.stopImmediatePropagation();
},
announceItemFocus: () => {
this.announceAriaValue(ariaDeleteSelection);
},
getValue: () => this.getValue(),
setValue: (value) => this.setValue(value, true)
});
}
this.doWhileBlockingAnnouncement(() => this.pillContainer?.refresh());
}
doWhileBlockingAnnouncement(func) {
this.skipWrapperAnnouncement = true;
func();
this.skipWrapperAnnouncement = false;
}
onWrapperFocus() {
const { eInput, config } = this;
const { allowTyping, multiSelect, suppressDeselectAll } = config;
if (allowTyping) {
const focusableEl = eInput.getFocusableElement();
focusableEl.focus();
focusableEl.select();
} else if (multiSelect && !suppressDeselectAll && !this.skipWrapperAnnouncement) {
this.announceAriaValue(this.ariaDeselectAllItems);
}
}
onWrapperFocusOut(e) {
if (!this.eWrapper.contains(e.relatedTarget)) {
this.hidePicker();
}
}
onDeselectAllMouseDown(e) {
e.stopImmediatePropagation();
}
onDeselectAllClick() {
this.setValue([], true);
}
buildSearchStringFromKeyboardEvent(searchKey) {
let { key } = searchKey;
if (key === import_ag_grid_community28.KeyCode.BACKSPACE) {
this.searchString = this.searchString.slice(0, -1);
key = "";
} else if (!(0, import_ag_grid_community28._isEventFromPrintableCharacter)(searchKey)) {
return;
}
searchKey.preventDefault();
this.searchTextFromCharacter(key);
}
searchTextFromCharacter(char) {
this.searchString += char;
this.runSearch();
this.clearSearchString();
}
searchTextFromString(str) {
if (str == null) {
str = "";
}
this.searchString = str;
this.runSearch();
}
getSearchStringsFromValues(values) {
const {
config: { valueFormatter }
} = this;
if (typeof values[0] === "object" && this.searchStringCreator) {
return this.searchStringCreator(values);
}
return values.map((value) => formatValueFn(value, valueFormatter));
}
filterListModel(filteredValues) {
const { filterList } = this.config;
if (!filterList) {
return;
}
this.setValueList({ valueList: filteredValues, refresh: true });
}
runSearch() {
if (!this.listComponent) {
return;
}
const { values } = this;
const searchStrings = this.searchStrings;
if (!searchStrings) {
this.listComponent.highlightIndex(-1);
return;
}
const { suggestions, filteredValues } = this.getSuggestionsAndFilteredValues(this.searchString, searchStrings);
const { filterList, highlightMatch, searchType = "fuzzy" } = this.config;
const shouldFilter = !!(filterList && this.searchString !== "");
this.filterListModel(shouldFilter ? filteredValues : values);
if (!this.highlightEmptyValue()) {
this.highlightListValue(suggestions, filteredValues, shouldFilter);
}
if (highlightMatch && searchType !== "fuzzy") {
this.listComponent?.highlightFilterMatch(this.searchString);
}
this.displayOrHidePicker();
}
highlightEmptyValue() {
if (this.searchString === "") {
const emptyIdx = this.searchStrings?.indexOf("");
if (emptyIdx !== void 0 && emptyIdx !== -1) {
this.listComponent?.highlightIndex(emptyIdx);
return true;
}
}
return false;
}
highlightListValue(suggestions, filteredValues, shouldFilter) {
if (suggestions.length) {
const topSuggestionIndex = shouldFilter ? 0 : this.searchStrings?.indexOf(suggestions[0]);
if (topSuggestionIndex !== void 0) {
this.listComponent?.highlightIndex(topSuggestionIndex);
}
} else {
this.listComponent?.highlightIndex(-1);
if (!shouldFilter || filteredValues.length) {
this.listComponent?.ensureIndexVisible(0);
} else if (shouldFilter) {
this.getAriaElement().removeAttribute("data-active-option");
const eListAriaEl = this.listComponent?.getAriaElement();
if (eListAriaEl) {
(0, import_ag_grid_community28._setAriaActiveDescendant)(eListAriaEl, null);
}
}
}
}
getSuggestionsAndFilteredValues(searchValue, valueList) {
let suggestions = [];
const filteredValues = [];
if (!searchValue.length) {
return { suggestions, filteredValues };
}
const { searchType = "fuzzy", filterList } = this.config;
if (searchType === "fuzzy") {
const fuzzySearchResult = (0, import_ag_grid_community28._fuzzySuggestions)({
inputValue: searchValue,
allSuggestions: valueList,
hideIrrelevant: true
});
suggestions = fuzzySearchResult.values;
const indices = fuzzySearchResult.indices;
if (filterList && indices.length) {
for (let i = 0; i < indices.length; i++) {
filteredValues.push(this.values[indices[i]]);
}
}
} else {
suggestions = valueList.filter((val, idx) => {
const currentValue = val.toLocaleLowerCase();
const valueToMatch = this.searchString.toLocaleLowerCase();
const isMatch = searchType === "match" ? currentValue.startsWith(valueToMatch) : currentValue.indexOf(valueToMatch) !== -1;
if (filterList && isMatch) {
filteredValues.push(this.values[idx]);
}
return isMatch;
});
}
return { suggestions, filteredValues };
}
displayOrHidePicker() {
if (!this.listComponent) {
return;
}
const eListGui = this.listComponent.getGui();
const list = this.listComponent.getCurrentList();
const toggleValue = list ? list.length === 0 : false;
eListGui.classList.toggle("ag-hidden", toggleValue);
}
clearSearchString() {
this.searchString = "";
}
setValue(value, silent, fromPicker, skipRendering) {
if (this.value === value) {
return this;
}
const isArray = Array.isArray(value);
if (value != null) {
if (!isArray) {
const list = this.listComponent?.getCurrentList();
const index = list ? list.indexOf(value) : -1;
if (index === -1) {
return this;
}
}
if (!fromPicker) {
this.listComponent?.selectValue(value);
}
}
super.setValue(value, silent);
if (!skipRendering) {
this.renderSelectedValue();
}
return this;
}
onNavigationKeyDown(event, key, announceItem) {
event.preventDefault();
const isDown = key === import_ag_grid_community28.KeyCode.DOWN;
if (!this.isPickerDisplayed && isDown) {
this.showPicker();
return;
}
this.listComponent?.onNavigationKeyDown(key, announceItem);
}
onEnterKeyDown(e) {
if (!this.isPickerDisplayed) {
return;
}
e.preventDefault();
if (this.listComponent?.getCurrentList()) {
const lastRowHovered = this.listComponent.getLastItemHovered();
if (this.config.multiSelect || lastRowHovered == null) {
this.dispatchPickerEventAndHidePicker(this.value, true);
} else {
this.onListValueSelected(/* @__PURE__ */ new Set([lastRowHovered]), true);
}
}
}
onDeleteKeyDown(e) {
const { eWrapper, beans } = this;
const activeEl = (0, import_ag_grid_community28._getActiveDomElement)(beans);
if (activeEl === eWrapper) {
e.preventDefault();
this.setValue([], true);
}
}
onTabKeyDown() {
const { config, isPickerDisplayed, listComponent } = this;
const { multiSelect } = config;
if (!isPickerDisplayed || !listComponent) {
return;
}
if (multiSelect) {
const values = this.getValueFromSet(listComponent.getSelectedItems());
if (values) {
this.setValue(values, false, true, true);
}
} else {
const lastItemHovered = listComponent.getLastItemHovered();
if (lastItemHovered) {
this.setValue(lastItemHovered, false, true);
}
}
this.hidePicker();
}
getValueFromSet(valueSet) {
const { multiSelect } = this.config;
let newValue = null;
for (const value of valueSet) {
if (valueSet.size === 1 && !multiSelect) {
newValue = value;
break;
}
if (!newValue) {
newValue = [];
}
newValue.push(value);
}
if (Array.isArray(newValue)) {
newValue.sort();
}
return newValue;
}
onListValueSelected(valueSet, fromEnterKey) {
const newValue = this.getValueFromSet(valueSet);
this.setValue(newValue, false, true);
if (!this.config.multiSelect) {
this.dispatchPickerEventAndHidePicker(newValue, fromEnterKey);
}
}
dispatchPickerEventAndHidePicker(value, fromEnterKey) {
const event = {
type: "fieldPickerValueSelected",
fromEnterKey,
value
};
this.dispatchLocalEvent(event);
this.hidePicker();
}
getFocusableElement() {
const { allowTyping } = this.config;
if (allowTyping) {
return this.eInput.getFocusableElement();
}
return super.getFocusableElement();
}
onKeyDown(e) {
const { key, isComposing } = e;
const {
isPickerDisplayed,
config: { allowTyping, multiSelect, suppressDeselectAll },
listComponent,
pickerComponent
} = this;
switch (key) {
case import_ag_grid_community28.KeyCode.LEFT:
case import_ag_grid_community28.KeyCode.RIGHT:
if (!allowTyping || this.pillContainer) {
e.preventDefault();
if (this.pillContainer) {
this.listComponent?.highlightIndex(-1);
this.pillContainer.onNavigationKeyDown(e);
}
}
break;
case import_ag_grid_community28.KeyCode.PAGE_HOME:
case import_ag_grid_community28.KeyCode.PAGE_END:
if (allowTyping) {
e.preventDefault();
const inputEl = this.eInput.getInputElement();
const target = key === import_ag_grid_community28.KeyCode.PAGE_HOME ? 0 : inputEl.value.length;
inputEl.setSelectionRange(target, target);
break;
}
case import_ag_grid_community28.KeyCode.PAGE_UP:
case import_ag_grid_community28.KeyCode.PAGE_DOWN:
e.preventDefault();
if (pickerComponent) {
listComponent?.navigateToPage(key);
}
break;
case import_ag_grid_community28.KeyCode.DOWN:
case import_ag_grid_community28.KeyCode.UP:
if (!isComposing) {
this.onNavigationKeyDown(e, key, () => {
if (multiSelect) {
this.doWhileBlockingAnnouncement(() => this.eWrapper.focus());
this.announceAriaValue(this.ariaToggleSelection);
}
});
}
break;
case import_ag_grid_community28.KeyCode.ESCAPE:
if (isPickerDisplayed) {
if ((0, import_ag_grid_community28._isVisible)(this.listComponent.getGui())) {
e.preventDefault();
(0, import_ag_grid_community28._stopPropagationForAgGrid)(e);
}
this.hidePicker();
}
break;
case import_ag_grid_community28.KeyCode.ENTER:
if (isComposing) {
e.preventDefault();
} else {
this.onEnterKeyDown(e);
}
break;
case import_ag_grid_community28.KeyCode.SPACE:
if (!allowTyping || isComposing) {
e.preventDefault();
}
if (!isComposing && isPickerDisplayed && multiSelect && listComponent) {
const lastItemHovered = listComponent.getLastItemHovered();
if (lastItemHovered) {
listComponent.toggleListItemSelection(lastItemHovered);
}
}
break;
case import_ag_grid_community28.KeyCode.TAB:
this.onTabKeyDown();
break;
case import_ag_grid_community28.KeyCode.DELETE:
if (multiSelect && !suppressDeselectAll) {
this.onDeleteKeyDown(e);
}
break;
default:
if (!allowTyping) {
this.buildSearchStringFromKeyboardEvent(e);
}
}
}
announceAriaValue(value) {
this.ariaAnnounce?.announceValue(value, "richSelect");
}
destroy() {
if (this.listComponent) {
this.listComponent = this.destroyBean(this.listComponent);
}
this.searchStrings = void 0;
super.destroy();
}
};
var formatValueFn = (value, valueFormatter) => valueFormatter?.(value) ?? String(value ?? "");
function _bindCellRendererToHtmlElement(cellRendererPromise, eTarget) {
cellRendererPromise.then((cellRenderer) => {
const gui = cellRenderer.getGui();
if (gui != null) {
eTarget.appendChild(gui);
}
});
}
// packages/ag-grid-enterprise/src/advancedFilter/builder/addDropdownComp.ts
var AddDropdownCompElement = {
tag: "div",
cls: "ag-picker-field",
role: "presentation",
children: [
{ tag: "div", ref: "eLabel" },
{
tag: "div",
ref: "eWrapper",
cls: "ag-wrapper ag-picker-collapsed",
children: [
{ tag: "div", ref: "eDisplayField", cls: "ag-picker-field-display" },
{ tag: "ag-input-text-field", ref: "eInput", cls: "ag-rich-select-field-input" },
{
tag: "span",
ref: "eDeselect",
cls: "ag-rich-select-deselect-button ag-picker-field-icon",
role: "presentation"
},
{ tag: "div", ref: "eIcon", cls: "ag-picker-field-icon", attrs: { "aria-hidden": "true" } }
]
}
]
};
var AddDropdownComp = class extends AgRichSelect {
constructor(params) {
super({
...params,
template: AddDropdownCompElement,
agComponents: [import_ag_grid_community29.AgInputTextFieldSelector]
});
this.params = params;
}
showPicker() {
setTimeout(() => super.showPicker());
}
hidePicker() {
setTimeout(() => super.hidePicker());
}
postConstruct() {
super.postConstruct();
const { wrapperClassName, ariaLabel } = this.params;
(0, import_ag_grid_community29._setDisplayed)(this.eDisplayField, false);
if (wrapperClassName) {
this.eWrapper.classList.add(wrapperClassName);
}
(0, import_ag_grid_community29._setAriaLabelledBy)(this.eWrapper, "");
(0, import_ag_grid_community29._setAriaLabel)(this.eWrapper, ariaLabel);
}
onEnterKeyDown(event) {
(0, import_ag_grid_community29._stopPropagationForAgGrid)(event);
if (this.isPickerDisplayed) {
super.onEnterKeyDown(event);
} else {
event.preventDefault();
this.showPicker();
}
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderItemNavigationFeature.ts
var import_ag_grid_community30 = require("ag-grid-community");
var AdvancedFilterBuilderItemNavigationFeature = class extends import_ag_grid_community30.BeanStub {
constructor(eGui, focusWrapper, eFocusableComp) {
super();
this.eGui = eGui;
this.focusWrapper = focusWrapper;
this.eFocusableComp = eFocusableComp;
}
postConstruct() {
this.addManagedElementListeners(this.eGui, {
keydown: (event) => {
switch (event.key) {
case import_ag_grid_community30.KeyCode.TAB:
if (!event.defaultPrevented) {
(0, import_ag_grid_community30._stopPropagationForAgGrid)(event);
}
break;
case import_ag_grid_community30.KeyCode.UP:
case import_ag_grid_community30.KeyCode.DOWN:
(0, import_ag_grid_community30._stopPropagationForAgGrid)(event);
break;
case import_ag_grid_community30.KeyCode.ESCAPE:
if ((0, import_ag_grid_community30._isStopPropagationForAgGrid)(event)) {
return;
}
if (this.eGui.contains((0, import_ag_grid_community30._getActiveDomElement)(this.beans))) {
event.preventDefault();
(0, import_ag_grid_community30._stopPropagationForAgGrid)(event);
this.focusWrapper.focus();
}
break;
}
}
});
const highlightClass = "ag-advanced-filter-builder-virtual-list-item-highlight";
this.addManagedListeners(this.focusWrapper, {
keydown: (event) => {
switch (event.key) {
case import_ag_grid_community30.KeyCode.ENTER:
if ((0, import_ag_grid_community30._isStopPropagationForAgGrid)(event)) {
return;
}
if ((0, import_ag_grid_community30._getActiveDomElement)(this.beans) === this.focusWrapper) {
event.preventDefault();
(0, import_ag_grid_community30._stopPropagationForAgGrid)(event);
this.eFocusableComp.getFocusableElement().focus();
}
break;
}
},
focusin: () => {
this.focusWrapper.classList.add(highlightClass);
},
focusout: (event) => {
if (!this.focusWrapper.contains(event.relatedTarget)) {
this.focusWrapper.classList.remove(highlightClass);
}
}
});
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderUtils.ts
function getAdvancedFilterBuilderAddButtonParams(translate, maxPickerWidth) {
return {
pickerAriaLabelKey: "ariaLabelAdvancedFilterBuilderAddField",
pickerAriaLabelValue: "Advanced Filter Builder Add Field",
pickerType: "ag-list",
valueList: [
{
key: "condition",
displayValue: translate("advancedFilterBuilderAddCondition")
},
{
key: "join",
displayValue: translate("advancedFilterBuilderAddJoin")
}
],
valueFormatter: (value) => value == null ? "" : value.displayValue ?? value.key,
pickerIcon: "advancedFilterBuilderAdd",
maxPickerWidth: `${maxPickerWidth ?? 120}px`,
wrapperClassName: "ag-advanced-filter-builder-item-button",
ariaLabel: translate("advancedFilterBuilderAddButtonTooltip")
};
}
// packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderItemAddComp.ts
var ItemAddElement = {
tag: "div",
cls: "ag-advanced-filter-builder-item-wrapper",
role: "presentation",
children: [
{
tag: "div",
ref: "eItem",
cls: "ag-advanced-filter-builder-item",
role: "presentation",
children: [
{
tag: "div",
cls: "ag-advanced-filter-builder-item-tree-lines",
attrs: { "aria-hidden": "true" },
children: [
{
tag: "div",
cls: "ag-advanced-filter-builder-item-tree-line-vertical-top ag-advanced-filter-builder-item-tree-line-horizontal"
}
]
}
]
}
]
};
var AdvancedFilterBuilderItemAddComp = class extends import_ag_grid_community31.Component {
constructor(item, focusWrapper) {
super(ItemAddElement);
this.item = item;
this.focusWrapper = focusWrapper;
this.eItem = import_ag_grid_community31.RefPlaceholder;
}
wireBeans(beans) {
this.advFilterExpSvc = beans.advFilterExpSvc;
this.registry = beans.registry;
}
postConstruct() {
(0, import_ag_grid_community31._setAriaLevel)(this.focusWrapper, 2);
const addButtonParams = getAdvancedFilterBuilderAddButtonParams(
(key) => this.advFilterExpSvc.translate(key),
this.gos.get("advancedFilterBuilderParams")?.addSelectWidth
);
const eAddButton = this.createManagedBean(new AddDropdownComp(addButtonParams));
this.addManagedListeners(eAddButton, {
fieldPickerValueSelected: ({ value }) => {
this.dispatchLocalEvent({
type: "advancedFilterBuilderAdded",
item: this.item,
isJoin: value.key === "join"
});
}
});
this.eItem.appendChild(eAddButton.getGui());
this.createOptionalManagedBean(
this.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => eAddButton.getGui(),
getLocation: () => "advancedFilter",
getTooltipValue: () => this.advFilterExpSvc.translate("advancedFilterBuilderAddButtonTooltip")
})
);
this.createManagedBean(
new AdvancedFilterBuilderItemNavigationFeature(this.getGui(), this.focusWrapper, eAddButton)
);
(0, import_ag_grid_community31._setAriaLabel)(
this.focusWrapper,
this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderItem", [
this.advFilterExpSvc.translate("advancedFilterBuilderAddButtonTooltip"),
`${this.item.level + 1}`
])
);
}
afterAdd() {
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderItemComp.ts
var import_ag_grid_community36 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/advancedFilter/builder/conditionPillWrapperComp.ts
var import_ag_grid_community32 = require("ag-grid-community");
var ConditionPillWrapperComp = class extends import_ag_grid_community32.Component {
constructor() {
super({ tag: "div", cls: "ag-advanced-filter-builder-item-condition", role: "presentation" });
this.validationMessage = null;
}
wireBeans(beans) {
this.advFilterExpSvc = beans.advFilterExpSvc;
}
init(params) {
const { item, createPill } = params;
this.item = item;
this.createPill = createPill;
this.filterModel = item.filterModel;
this.setupColumnCondition(this.filterModel);
this.validate();
this.addDestroyFunc(() => this.destroyBeans([this.eColumnPill, this.eOperatorPill, this.eOperandPill]));
}
getDragName() {
return this.filterModel.colId ? this.advFilterExpSvc.parseColumnFilterModel(this.filterModel) : this.getDefaultColumnDisplayValue();
}
getAriaLabel() {
return `${this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderFilterItem")} ${this.getDragName()}`;
}
getValidationMessage() {
return this.validationMessage;
}
getFocusableElement() {
return this.eColumnPill.getFocusableElement();
}
setupColumnCondition(filterModel) {
const columnDetails = this.advFilterExpSvc.getColumnDetails(filterModel.colId);
this.baseCellDataType = columnDetails.baseCellDataType;
this.column = columnDetails.column;
this.numOperands = this.getNumOperands(this.getOperatorKey());
this.eColumnPill = this.createPill({
key: this.getColumnKey(),
displayValue: this.getColumnDisplayValue() ?? this.getDefaultColumnDisplayValue(),
cssClass: "ag-advanced-filter-builder-column-pill",
isSelect: true,
getEditorParams: () => ({ values: this.advFilterExpSvc.getColumnAutocompleteEntries() }),
update: (key) => this.setColumnKey(key),
pickerAriaLabelKey: "ariaLabelAdvancedFilterBuilderColumnSelectField",
pickerAriaLabelValue: "Advanced Filter Builder Column Select Field",
ariaLabel: this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderColumn")
});
this.getGui().appendChild(this.eColumnPill.getGui());
if ((0, import_ag_grid_community32._exists)(this.getColumnKey())) {
this.createOperatorPill();
if (this.hasOperand()) {
this.createOperandPill();
}
}
}
createOperatorPill() {
this.eOperatorPill = this.createPill({
key: this.getOperatorKey(),
displayValue: this.getOperatorDisplayValue() ?? this.getDefaultOptionSelectValue(),
cssClass: "ag-advanced-filter-builder-option-pill",
isSelect: true,
getEditorParams: () => ({ values: this.getOperatorAutocompleteEntries() }),
update: (key) => this.setOperatorKey(key),
pickerAriaLabelKey: "ariaLabelAdvancedFilterBuilderOptionSelectField",
pickerAriaLabelValue: "Advanced Filter Builder Option Select Field",
ariaLabel: this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderOption")
});
this.eColumnPill.getGui().insertAdjacentElement("afterend", this.eOperatorPill.getGui());
}
createOperandPill() {
const { filter } = this.filterModel;
const key = (typeof filter === "number" ? (0, import_ag_grid_community32._toStringOrNull)(filter) : filter) ?? "";
this.eOperandPill = this.createPill({
key,
// Convert from the input format to display format.
// Input format matches model format except for numbers, but these get stringified anyway
valueFormatter: (value) => this.advFilterExpSvc.getOperandDisplayValue({ ...this.filterModel, filter: value }, true),
baseCellDataType: this.baseCellDataType,
cssClass: "ag-advanced-filter-builder-value-pill",
isSelect: false,
update: (key2) => this.setOperand(key2),
ariaLabel: this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderValue")
});
this.getGui().appendChild(this.eOperandPill.getGui());
}
getColumnKey() {
return this.filterModel.colId;
}
getColumnDisplayValue() {
return this.advFilterExpSvc.getColumnDisplayValue(this.filterModel);
}
getOperatorKey() {
return this.filterModel.type;
}
getOperatorDisplayValue() {
return this.advFilterExpSvc.getOperatorDisplayValue(this.filterModel);
}
getOperandDisplayValue() {
return this.advFilterExpSvc.getOperandDisplayValue(this.filterModel, true);
}
hasOperand() {
return this.numOperands > 0;
}
getOperatorAutocompleteEntries() {
return this.column ? this.advFilterExpSvc.getOperatorAutocompleteEntries(this.column, this.baseCellDataType) : [];
}
setColumnKey(colId) {
if (!this.eOperatorPill) {
this.createOperatorPill();
}
const newColumnDetails = this.advFilterExpSvc.getColumnDetails(colId);
this.column = newColumnDetails.column;
const newBaseCellDataType = newColumnDetails.baseCellDataType;
if (this.baseCellDataType !== newBaseCellDataType) {
this.baseCellDataType = newBaseCellDataType;
this.setOperatorKey(void 0);
if (this.eOperatorPill) {
(0, import_ag_grid_community32._removeFromParent)(this.eOperatorPill.getGui());
this.destroyBean(this.eOperatorPill);
this.createOperatorPill();
}
this.validate();
}
this.filterModel.colId = colId;
this.filterModel.filterType = this.baseCellDataType;
}
setOperatorKey(operator) {
const newNumOperands = this.getNumOperands(operator);
if (newNumOperands !== this.numOperands) {
this.numOperands = newNumOperands;
if (newNumOperands === 0) {
this.destroyOperandPill();
} else {
this.createOperandPill();
if (this.baseCellDataType !== "number") {
this.setOperand("");
}
}
}
this.filterModel.type = operator;
this.validate();
}
setOperand(operand) {
let parsedOperand = operand;
if (this.baseCellDataType === "number") {
parsedOperand = (0, import_ag_grid_community32._exists)(operand) ? Number(operand) : "";
}
this.filterModel.filter = parsedOperand;
this.validate();
}
getNumOperands(operator) {
return this.advFilterExpSvc.getExpressionOperator(this.baseCellDataType, operator)?.numOperands ?? 0;
}
destroyOperandPill() {
delete this.filterModel.filter;
this.getGui().removeChild(this.eOperandPill.getGui());
this.destroyBean(this.eOperandPill);
this.eOperandPill = void 0;
}
validate() {
let validationMessage = null;
if (!(0, import_ag_grid_community32._exists)(this.getColumnKey())) {
validationMessage = this.advFilterExpSvc.translate("advancedFilterBuilderValidationSelectColumn");
} else if (!(0, import_ag_grid_community32._exists)(this.getOperatorKey())) {
validationMessage = this.advFilterExpSvc.translate("advancedFilterBuilderValidationSelectOption");
} else if (this.numOperands > 0 && !(0, import_ag_grid_community32._exists)(this.getOperandDisplayValue())) {
validationMessage = this.advFilterExpSvc.translate("advancedFilterBuilderValidationEnterValue");
}
this.item.valid = !validationMessage;
if (validationMessage !== this.validationMessage) {
this.validationMessage = validationMessage;
this.dispatchLocalEvent({
type: "advancedFilterBuilderValidChanged"
});
}
}
getDefaultColumnDisplayValue() {
return this.advFilterExpSvc.translate("advancedFilterBuilderSelectColumn");
}
getDefaultOptionSelectValue() {
return this.advFilterExpSvc.translate("advancedFilterBuilderSelectOption");
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/inputPillComp.ts
var import_ag_grid_community33 = require("ag-grid-community");
var inputComponentDescriptors = {
number: [import_ag_grid_community33.AgInputNumberField],
boolean: [import_ag_grid_community33.AgInputTextField],
object: [import_ag_grid_community33.AgInputTextField],
text: [import_ag_grid_community33.AgInputTextField],
date: [import_ag_grid_community33.AgInputDateField],
dateString: [import_ag_grid_community33.AgInputDateField],
dateTime: [import_ag_grid_community33.AgInputDateField, (i) => i.setIncludeTime(true)],
dateTimeString: [import_ag_grid_community33.AgInputDateField, (i) => i.setIncludeTime(true)]
};
var InputPillElement = {
tag: "div",
cls: "ag-advanced-filter-builder-pill-wrapper",
role: "presentation",
children: [
{
tag: "div",
ref: "ePill",
cls: "ag-advanced-filter-builder-pill",
role: "button",
children: [
{
tag: "span",
ref: "eLabel",
cls: "ag-advanced-filter-builder-pill-display"
}
]
}
]
};
var InputPillComp = class extends import_ag_grid_community33.Component {
constructor(params) {
super(InputPillElement);
this.params = params;
this.ePill = import_ag_grid_community33.RefPlaceholder;
this.eLabel = import_ag_grid_community33.RefPlaceholder;
const { value, valueFormatter } = params;
this.value = value;
this.displayValue = valueFormatter(value);
}
wireBeans(beans) {
this.advFilterExpSvc = beans.advFilterExpSvc;
}
postConstruct() {
const { cssClass, ariaLabel } = this.params;
this.ePill.classList.add(cssClass);
this.activateTabIndex([this.ePill]);
this.eLabel.id = `${this.getCompId()}`;
(0, import_ag_grid_community33._setAriaDescribedBy)(this.ePill, this.eLabel.id);
(0, import_ag_grid_community33._setAriaLabel)(this.ePill, ariaLabel);
this.renderValue();
this.addManagedListeners(this.ePill, {
click: (event) => {
event.preventDefault();
this.showEditor();
},
keydown: (event) => {
switch (event.key) {
case import_ag_grid_community33.KeyCode.ENTER:
event.preventDefault();
(0, import_ag_grid_community33._stopPropagationForAgGrid)(event);
this.showEditor();
break;
}
}
});
this.addDestroyFunc(() => this.destroyBean(this.eEditor));
}
getFocusableElement() {
return this.ePill;
}
showEditor() {
if (this.eEditor) {
return;
}
(0, import_ag_grid_community33._setDisplayed)(this.ePill, false);
this.eEditor = this.createEditorComp(this.params.type);
this.eEditor.setValue(this.value);
const eEditorGui = this.eEditor.getGui();
this.eEditor.addManagedElementListeners(eEditorGui, {
keydown: (event) => {
switch (event.key) {
case import_ag_grid_community33.KeyCode.ENTER:
event.preventDefault();
(0, import_ag_grid_community33._stopPropagationForAgGrid)(event);
this.updateValue(true);
break;
case import_ag_grid_community33.KeyCode.ESCAPE:
event.preventDefault();
(0, import_ag_grid_community33._stopPropagationForAgGrid)(event);
this.hideEditor(true);
break;
}
},
focusout: () => this.updateValue(false)
});
this.getGui().appendChild(eEditorGui);
this.eEditor.getFocusableElement().focus();
}
/**
* Responsible for instantiating an InputField and calling some of the setup methods
*/
createEditorComp(type) {
const [Comp, postConstruct] = inputComponentDescriptors[type];
const instance = this.createBean(new Comp());
if (postConstruct)
postConstruct(instance);
return instance;
}
hideEditor(keepFocus) {
const { eEditor } = this;
if (!eEditor) {
return;
}
this.eEditor = void 0;
this.getGui().removeChild(eEditor.getGui());
this.destroyBean(eEditor);
(0, import_ag_grid_community33._setDisplayed)(this.ePill, true);
if (keepFocus) {
this.ePill.focus();
}
}
renderValue() {
let value;
const { displayValue, eLabel } = this;
const { classList } = eLabel;
classList.remove(
"ag-advanced-filter-builder-value-empty",
"ag-advanced-filter-builder-value-number",
"ag-advanced-filter-builder-value-text"
);
if (!(0, import_ag_grid_community33._exists)(displayValue)) {
value = this.advFilterExpSvc.translate("advancedFilterBuilderEnterValue");
classList.add("ag-advanced-filter-builder-value-empty");
} else if (this.params.type === "number") {
value = displayValue;
classList.add("ag-advanced-filter-builder-value-number");
} else {
value = `"${displayValue}"`;
classList.add("ag-advanced-filter-builder-value-text");
}
eLabel.textContent = value;
}
updateValue(keepFocus) {
if (!this.eEditor) {
return;
}
const value = this.eEditor.getValue() ?? "";
this.dispatchLocalEvent({
type: "fieldValueChanged",
value
});
this.value = value;
this.displayValue = this.params.valueFormatter(value);
this.renderValue();
this.hideEditor(keepFocus);
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/joinPillWrapperComp.ts
var import_ag_grid_community34 = require("ag-grid-community");
var JoinPillWrapperComp = class extends import_ag_grid_community34.Component {
wireBeans(beans) {
this.advFilterExpSvc = beans.advFilterExpSvc;
}
constructor() {
super({
tag: "div",
cls: "ag-advanced-filter-builder-item-condition",
role: "presentation"
});
}
init(params) {
const { item, createPill } = params;
const filterModel = item.filterModel;
this.filterModel = filterModel;
this.ePill = createPill({
key: filterModel.type,
displayValue: this.advFilterExpSvc.parseJoinOperator(filterModel),
cssClass: "ag-advanced-filter-builder-join-pill",
isSelect: true,
getEditorParams: () => ({
values: this.advFilterExpSvc.getJoinOperatorAutocompleteEntries()
}),
update: (key) => filterModel.type = key,
pickerAriaLabelKey: "ariaLabelAdvancedFilterBuilderJoinSelectField",
pickerAriaLabelValue: "Advanced Filter Builder Join Operator Select Field",
ariaLabel: this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderJoinOperator")
});
this.getGui().appendChild(this.ePill.getGui());
this.addDestroyFunc(() => this.destroyBean(this.ePill));
}
getDragName() {
return this.advFilterExpSvc.parseJoinOperator(this.filterModel);
}
getAriaLabel() {
return `${this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderGroupItem")} ${this.getDragName()}`;
}
getValidationMessage() {
return null;
}
getFocusableElement() {
return this.ePill.getFocusableElement();
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/selectPillComp.ts
var import_ag_grid_community35 = require("ag-grid-community");
var SelectPillElement = {
tag: "div",
cls: "ag-picker-field ag-advanced-filter-builder-pill-wrapper",
role: "presentation",
children: [
{ tag: "div", ref: "eLabel" },
{
tag: "div",
ref: "eWrapper",
cls: "ag-wrapper ag-advanced-filter-builder-pill ag-picker-collapsed",
children: [
{
tag: "div",
ref: "eDisplayField",
cls: "ag-picker-field-display ag-advanced-filter-builder-pill-display"
},
{ tag: "ag-input-text-field", ref: "eInput", cls: "ag-rich-select-field-input" },
{
tag: "span",
ref: "eDeselect",
cls: "ag-rich-select-deselect-button ag-picker-field-icon",
role: "presentation"
},
{ tag: "div", ref: "eIcon", cls: "ag-picker-field-icon", attrs: { "aria-hidden": "true" } }
]
}
]
};
var SelectPillComp = class extends AgRichSelect {
constructor(params) {
super({
...params,
template: SelectPillElement,
agComponents: [import_ag_grid_community35.AgInputTextFieldSelector]
});
this.params = params;
}
getFocusableElement() {
return this.eWrapper;
}
showPicker() {
setTimeout(() => super.showPicker());
}
hidePicker() {
setTimeout(() => super.hidePicker());
}
postConstruct() {
super.postConstruct();
const { wrapperClassName, ariaLabel } = this.params;
this.eWrapper.classList.add(wrapperClassName);
(0, import_ag_grid_community35._setAriaLabelledBy)(this.eWrapper, "");
(0, import_ag_grid_community35._setAriaLabel)(this.eWrapper, ariaLabel);
}
createPickerComponent() {
if (!this.values) {
const { values } = this.params.getEditorParams();
this.values = values;
const key = this.value.key;
const value = values.find((value2) => value2.key === key) ?? {
key,
displayValue: this.value.displayValue
};
this.value = value;
}
return super.createPickerComponent();
}
onEnterKeyDown(event) {
(0, import_ag_grid_community35._stopPropagationForAgGrid)(event);
if (this.isPickerDisplayed) {
super.onEnterKeyDown(event);
} else {
event.preventDefault();
this.showPicker();
}
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderItemComp.ts
var AdvancedFilterBuilderItemElement = {
tag: "div",
cls: "ag-advanced-filter-builder-item-wrapper",
role: "presentation",
children: [
{
tag: "div",
cls: "ag-advanced-filter-builder-item",
role: "presentation",
children: [
{
tag: "div",
ref: "eTreeLines",
cls: "ag-advanced-filter-builder-item-tree-lines",
attrs: { "aria-hidden": "true" }
},
{
tag: "span",
ref: "eDragHandle",
cls: "ag-drag-handle",
attrs: { "aria-hidden": "true" }
},
{
tag: "span",
ref: "eValidation",
cls: "ag-advanced-filter-builder-item-button ag-advanced-filter-builder-invalid",
attrs: { "aria-hidden": "true" }
}
]
},
{
tag: "div",
ref: "eButtons",
cls: "ag-advanced-filter-builder-item-buttons",
children: [
{ tag: "span", ref: "eMoveUpButton", cls: "ag-advanced-filter-builder-item-button", role: "button" },
{ tag: "span", ref: "eMoveDownButton", cls: "ag-advanced-filter-builder-item-button", role: "button" },
{ tag: "div", ref: "eAddButton", role: "presentation" },
{ tag: "span", ref: "eRemoveButton", cls: "ag-advanced-filter-builder-item-button", role: "button" }
]
}
]
};
var AdvancedFilterBuilderItemComp = class extends import_ag_grid_community36.TabGuardComp {
constructor(item, dragFeature, focusWrapper) {
super(AdvancedFilterBuilderItemElement);
this.item = item;
this.dragFeature = dragFeature;
this.focusWrapper = focusWrapper;
this.eTreeLines = import_ag_grid_community36.RefPlaceholder;
this.eDragHandle = import_ag_grid_community36.RefPlaceholder;
this.eButtons = import_ag_grid_community36.RefPlaceholder;
this.eValidation = import_ag_grid_community36.RefPlaceholder;
this.eMoveUpButton = import_ag_grid_community36.RefPlaceholder;
this.eMoveDownButton = import_ag_grid_community36.RefPlaceholder;
this.eAddButton = import_ag_grid_community36.RefPlaceholder;
this.eRemoveButton = import_ag_grid_community36.RefPlaceholder;
this.moveUpDisabled = false;
this.moveDownDisabled = false;
}
wireBeans(beans) {
this.dragAndDrop = beans.dragAndDrop;
this.advFilterExpSvc = beans.advFilterExpSvc;
this.registry = beans.registry;
}
postConstruct() {
const { filterModel, level, showMove } = this.item;
const isJoin = filterModel.filterType === "join";
this.ePillWrapper = this.createManagedBean(isJoin ? new JoinPillWrapperComp() : new ConditionPillWrapperComp());
this.ePillWrapper.init({ item: this.item, createPill: (params) => this.createPill(params) });
this.eDragHandle.insertAdjacentElement("afterend", this.ePillWrapper.getGui());
if (level === 0) {
const eTreeLine = (0, import_ag_grid_community36._createElement)({
tag: "div",
cls: "ag-advanced-filter-builder-item-tree-line-vertical-bottom ag-advanced-filter-builder-item-tree-line-root"
});
this.eTreeLines.appendChild(eTreeLine);
(0, import_ag_grid_community36._setDisplayed)(this.eDragHandle, false);
(0, import_ag_grid_community36._setDisplayed)(this.eButtons, false);
(0, import_ag_grid_community36._setAriaExpanded)(this.focusWrapper, true);
} else {
this.setupTreeLines(level);
this.eDragHandle.appendChild((0, import_ag_grid_community36._createIconNoSpan)("advancedFilterBuilderDrag", this.beans));
this.setupValidation();
this.setupMoveButtons(showMove);
this.setupAddButton();
this.setupRemoveButton();
this.setupDragging();
this.updateAriaExpanded();
}
(0, import_ag_grid_community36._setAriaLevel)(this.focusWrapper, level + 1);
this.initialiseTabGuard({});
this.createManagedBean(
new AdvancedFilterBuilderItemNavigationFeature(this.getGui(), this.focusWrapper, this.ePillWrapper)
);
this.updateAriaLabel();
this.addManagedListeners(this.ePillWrapper, {
advancedFilterBuilderValueChanged: () => this.dispatchLocalEvent({
type: "advancedFilterBuilderValueChanged"
}),
advancedFilterBuilderValidChanged: () => this.updateValidity()
});
}
setState(params) {
const { level } = this.item;
if (level === 0) {
return;
}
const { showMove } = this.item;
const { disableMoveUp, disableMoveDown, treeLines, showStartTreeLine } = params;
this.updateTreeLines(treeLines, showStartTreeLine);
this.updateAriaExpanded();
if (showMove) {
this.moveUpDisabled = !!disableMoveUp;
this.moveDownDisabled = !!disableMoveDown;
this.eMoveUpButton.classList.toggle("ag-advanced-filter-builder-item-button-disabled", disableMoveUp);
this.eMoveDownButton.classList.toggle("ag-advanced-filter-builder-item-button-disabled", disableMoveDown);
(0, import_ag_grid_community36._setAriaDisabled)(this.eMoveUpButton, !!disableMoveUp);
(0, import_ag_grid_community36._setAriaDisabled)(this.eMoveDownButton, !!disableMoveDown);
this.moveUpTooltipFeature?.refreshTooltip();
this.moveDownTooltipFeature?.refreshTooltip();
}
}
focusMoveButton(backwards) {
(backwards ? this.eMoveUpButton : this.eMoveDownButton).focus();
}
afterAdd() {
this.ePillWrapper.getFocusableElement().focus();
}
setupTreeLines(level) {
for (let i = 0; i < level; i++) {
this.eTreeLines.appendChild((0, import_ag_grid_community36._createElement)({ tag: "div" }));
}
}
updateTreeLines(treeLines, showStartTreeLine) {
const lastTreeLineIndex = treeLines.length - 1;
const { children } = this.eTreeLines;
for (let i = 0; i < lastTreeLineIndex; i++) {
const eTreeLine2 = children.item(i);
if (eTreeLine2) {
eTreeLine2.classList.toggle("ag-advanced-filter-builder-item-tree-line-vertical", !treeLines[i]);
}
}
const eTreeLine = children.item(lastTreeLineIndex);
if (eTreeLine) {
eTreeLine.classList.add("ag-advanced-filter-builder-item-tree-line-horizontal");
const isLastChild = treeLines[lastTreeLineIndex];
eTreeLine.classList.toggle("ag-advanced-filter-builder-item-tree-line-vertical-top", isLastChild);
eTreeLine.classList.toggle("ag-advanced-filter-builder-item-tree-line-vertical", !isLastChild);
}
this.eDragHandle.classList.toggle(
"ag-advanced-filter-builder-item-tree-line-vertical-bottom",
showStartTreeLine
);
}
setupValidation() {
this.eValidation.appendChild((0, import_ag_grid_community36._createIconNoSpan)("advancedFilterBuilderInvalid", this.beans));
this.validationTooltipFeature = this.createOptionalManagedBean(
this.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.eValidation,
getLocation: () => "advancedFilter",
getTooltipValue: () => this.ePillWrapper.getValidationMessage(),
getTooltipShowDelayOverride: () => 1e3
})
);
this.updateValidity();
}
setupAddButton() {
const addButtonParams = getAdvancedFilterBuilderAddButtonParams(
(key) => this.advFilterExpSvc.translate(key),
this.gos.get("advancedFilterBuilderParams")?.addSelectWidth
);
const eAddButton = this.createManagedBean(new AddDropdownComp(addButtonParams));
this.addManagedListeners(eAddButton, {
fieldPickerValueSelected: ({ value }) => this.dispatchLocalEvent({
type: "advancedFilterBuilderAdded",
item: this.item,
isJoin: value.key === "join"
})
});
this.eAddButton.appendChild(eAddButton.getGui());
this.createOptionalManagedBean(
this.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.eAddButton,
getLocation: () => "advancedFilter",
getTooltipValue: () => this.advFilterExpSvc.translate("advancedFilterBuilderAddButtonTooltip")
})
);
}
setupRemoveButton() {
this.eRemoveButton.appendChild((0, import_ag_grid_community36._createIconNoSpan)("advancedFilterBuilderRemove", this.beans));
this.addManagedListeners(this.eRemoveButton, {
click: () => this.removeItem(),
keydown: (event) => {
switch (event.key) {
case import_ag_grid_community36.KeyCode.ENTER:
event.preventDefault();
(0, import_ag_grid_community36._stopPropagationForAgGrid)(event);
this.removeItem();
break;
}
}
});
this.createOptionalManagedBean(
this.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.eRemoveButton,
getLocation: () => "advancedFilter",
getTooltipValue: () => this.advFilterExpSvc.translate("advancedFilterBuilderRemoveButtonTooltip")
})
);
(0, import_ag_grid_community36._setAriaLabel)(this.eRemoveButton, this.advFilterExpSvc.translate("advancedFilterBuilderRemoveButtonTooltip"));
this.activateTabIndex([this.eRemoveButton]);
}
setupMoveButtons(showMove) {
if (showMove) {
this.eMoveUpButton.appendChild((0, import_ag_grid_community36._createIconNoSpan)("advancedFilterBuilderMoveUp", this.beans));
this.addManagedListeners(this.eMoveUpButton, {
click: () => this.moveItem(true),
keydown: (event) => {
switch (event.key) {
case import_ag_grid_community36.KeyCode.ENTER:
event.preventDefault();
(0, import_ag_grid_community36._stopPropagationForAgGrid)(event);
this.moveItem(true);
break;
}
}
});
this.moveUpTooltipFeature = this.createOptionalManagedBean(
this.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.eMoveUpButton,
getLocation: () => "advancedFilter",
getTooltipValue: () => this.moveUpDisabled ? null : this.advFilterExpSvc.translate("advancedFilterBuilderMoveUpButtonTooltip")
})
);
(0, import_ag_grid_community36._setAriaLabel)(
this.eMoveUpButton,
this.advFilterExpSvc.translate("advancedFilterBuilderMoveUpButtonTooltip")
);
this.eMoveDownButton.appendChild((0, import_ag_grid_community36._createIconNoSpan)("advancedFilterBuilderMoveDown", this.beans));
this.addManagedListeners(this.eMoveDownButton, {
click: () => this.moveItem(false),
keydown: (event) => {
switch (event.key) {
case import_ag_grid_community36.KeyCode.ENTER:
event.preventDefault();
(0, import_ag_grid_community36._stopPropagationForAgGrid)(event);
this.moveItem(false);
break;
}
}
});
this.moveDownTooltipFeature = this.createOptionalManagedBean(
this.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.eMoveDownButton,
getLocation: () => "advancedFilter",
getTooltipValue: () => this.moveDownDisabled ? null : this.advFilterExpSvc.translate("advancedFilterBuilderMoveDownButtonTooltip")
})
);
(0, import_ag_grid_community36._setAriaLabel)(
this.eMoveDownButton,
this.advFilterExpSvc.translate("advancedFilterBuilderMoveDownButtonTooltip")
);
this.activateTabIndex([this.eMoveUpButton, this.eMoveDownButton]);
} else {
(0, import_ag_grid_community36._setDisplayed)(this.eMoveUpButton, false);
(0, import_ag_grid_community36._setDisplayed)(this.eMoveDownButton, false);
}
}
updateValidity() {
(0, import_ag_grid_community36._setVisible)(this.eValidation, !this.item.valid);
this.validationTooltipFeature?.refreshTooltip();
this.updateAriaLabel();
}
createPill(params) {
const { key, cssClass, update, ariaLabel } = params;
const onUpdated = (key2) => {
if (key2 == null) {
return;
}
update(key2);
this.dispatchLocalEvent({
type: "advancedFilterBuilderValueChanged"
});
};
if (params.isSelect) {
const { getEditorParams, pickerAriaLabelKey, pickerAriaLabelValue, displayValue } = params;
const advancedFilterBuilderParams = this.gos.get("advancedFilterBuilderParams");
const minPickerWidth = `${advancedFilterBuilderParams?.pillSelectMinWidth ?? 140}px`;
const maxPickerWidth = `${advancedFilterBuilderParams?.pillSelectMaxWidth ?? 200}px`;
const comp = this.createBean(
new SelectPillComp({
pickerAriaLabelKey,
pickerAriaLabelValue,
pickerType: "ag-list",
value: {
key,
displayValue
},
valueFormatter: (value) => value == null ? "" : value.displayValue ?? value.key,
variableWidth: true,
minPickerWidth,
maxPickerWidth,
getEditorParams,
wrapperClassName: cssClass,
ariaLabel,
pickerIcon: "advancedFilterBuilderSelectOpen"
})
);
this.addManagedListeners(comp, {
fieldPickerValueSelected: ({ value }) => onUpdated(value?.key)
});
return comp;
} else {
const { baseCellDataType, valueFormatter } = params;
const comp = this.createBean(
new InputPillComp({
value: key,
valueFormatter,
cssClass,
type: baseCellDataType,
ariaLabel
})
);
this.addManagedListeners(comp, { fieldValueChanged: ({ value }) => onUpdated(value) });
return comp;
}
}
setupDragging() {
const dragSource = {
type: import_ag_grid_community36.DragSourceType.AdvancedFilterBuilder,
eElement: this.eDragHandle,
dragItemName: () => this.ePillWrapper.getDragName(),
getDefaultIconName: () => "notAllowed",
getDragItem: () => ({}),
onDragStarted: () => this.dragFeature.dispatchLocalEvent({
type: "advancedFilterBuilderDragStarted",
item: this.item
}),
onDragStopped: () => this.dragFeature.dispatchLocalEvent({
type: "advancedFilterBuilderDragEnded"
})
};
this.dragAndDrop.addDragSource(dragSource, true);
this.addDestroyFunc(() => this.dragAndDrop.removeDragSource(dragSource));
}
updateAriaLabel() {
const wrapperLabel = this.ePillWrapper.getAriaLabel();
const level = `${this.item.level + 1}`;
const validationMessage = this.ePillWrapper.getValidationMessage();
let ariaLabel;
if (validationMessage) {
ariaLabel = this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderItemValidation", [
wrapperLabel,
level,
validationMessage
]);
} else {
ariaLabel = this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderItem", [wrapperLabel, level]);
}
(0, import_ag_grid_community36._setAriaLabel)(this.focusWrapper, ariaLabel);
}
updateAriaExpanded() {
(0, import_ag_grid_community36._removeAriaExpanded)(this.focusWrapper);
const { filterModel } = this.item;
if (filterModel?.filterType === "join" && filterModel.conditions.length) {
(0, import_ag_grid_community36._setAriaExpanded)(this.focusWrapper, true);
}
}
removeItem() {
this.dispatchLocalEvent({
type: "advancedFilterBuilderRemoved",
item: this.item
});
}
moveItem(backwards) {
this.dispatchLocalEvent({
type: "advancedFilterBuilderMoved",
item: this.item,
backwards
});
}
};
// packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderComp.ts
var ButtonLocaleMap2 = {
apply: "advancedFilterBuilderApply",
clear: "advancedFilterBuilderClear",
cancel: "advancedFilterBuilderCancel",
reset: "advancedFilterBuilderReset"
};
var AdvancedFilterBuilderElement = {
tag: "div",
cls: "ag-advanced-filter-builder",
role: "presentation",
attrs: { tabindex: "-1" },
children: [
{
tag: "div",
ref: "eList",
cls: "ag-advanced-filter-builder-list",
role: "presentation"
}
]
};
var AdvancedFilterBuilderComp = class extends import_ag_grid_community37.Component {
constructor() {
super(AdvancedFilterBuilderElement);
this.eList = import_ag_grid_community37.RefPlaceholder;
}
wireBeans(beans) {
this.filterManager = beans.filterManager;
this.advancedFilter = beans.advancedFilter;
this.advFilterExpSvc = beans.advFilterExpSvc;
}
postConstruct() {
const params = this.gos.get("advancedFilterBuilderParams");
this.params = { buttons: ["apply", "cancel"], ...params };
this.addManagedPropertyListener("advancedFilterBuilderParams", ({ currentValue }) => {
this.params.showMoveButtons = !!currentValue?.showMoveButtons;
this.params.buttons = currentValue?.buttons ?? ["apply", "cancel"];
this.refreshList(false);
});
this.filterModel = this.setupFilterModel();
this.setupVirtualList();
this.dragFeature = this.createManagedBean(new AdvancedFilterBuilderDragFeature(this, this.virtualList));
this.resetButtonsPanel(this.params.buttons);
}
refresh() {
const virtualList = this.virtualList;
let indexToFocus = virtualList.getLastFocusedRow();
this.setupFilterModel();
this.validateItems();
this.refreshList(false);
if (indexToFocus != null) {
if (!virtualList.getComponentAt(indexToFocus)) {
indexToFocus = 0;
}
virtualList.focusRow(indexToFocus);
}
}
getNumItems() {
return this.items.length;
}
moveItem(item, destination) {
if (!destination || !item) {
return;
}
this.moveItemToIndex(item, destination.rowIndex, destination.position);
}
afterGuiAttached() {
this.virtualList.awaitStable(() => this.virtualList.focusRow(0));
}
setupVirtualList() {
const virtualList = this.virtualList = this.createManagedBean(
new VirtualList({
cssIdentifier: "advanced-filter-builder",
ariaRole: "tree",
listName: this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderList"),
moveItemCallback: this.virtualListMoveItemCallback.bind(this)
})
);
virtualList.setComponentCreator(this.createItemComponent.bind(this));
virtualList.setComponentUpdater(this.updateItemComponent.bind(this));
virtualList.setRowHeight(40);
this.eList.appendChild(virtualList.getGui());
virtualList.setModel({
getRowCount: () => this.items?.length || 0,
getRow: (index) => this.items[index],
areRowsEqual: (oldRow, newRow) => oldRow === newRow
});
this.buildList();
virtualList.refresh();
}
resetButtonsPanel(actions) {
const hasButtons = actions && actions.length > 0;
let eButtonsPanel = this.eButtons;
if (hasButtons) {
const buttons = actions.map((type) => ({
type,
label: this.advFilterExpSvc.translate(ButtonLocaleMap2[type])
}));
if (!eButtonsPanel) {
eButtonsPanel = this.createBean(new import_ag_grid_community37.FilterButtonComp());
this.appendChild(eButtonsPanel.getGui());
const getListener = (action) => ({ event }) => {
this.updateModel(action);
this.afterAction(action, event);
};
eButtonsPanel.addManagedListeners(eButtonsPanel, {
apply: getListener("apply"),
clear: getListener("clear"),
reset: getListener("reset"),
cancel: getListener("cancel")
});
this.eButtons = eButtonsPanel;
}
eButtonsPanel.updateButtons(buttons);
const applyButton = eButtonsPanel.getApplyButton();
if (applyButton) {
const mouseListener = (isEnter) => this.toggleCss("ag-advanced-filter-builder-validation", isEnter);
this.addManagedElementListeners(applyButton, {
mouseenter: () => mouseListener(true),
mouseleave: () => mouseListener(false)
});
}
} else {
if (eButtonsPanel) {
(0, import_ag_grid_community37._removeFromParent)(eButtonsPanel.getGui());
this.eButtons = this.destroyBean(eButtonsPanel);
}
}
}
updateModel(action) {
switch (action) {
case "apply":
this.advancedFilter.setModel(this.filterModel);
this.filterManager?.onFilterChanged({ source: "advancedFilter" });
break;
case "reset":
this.advancedFilter.setModel(null);
this.filterManager?.onFilterChanged({ source: "advancedFilter" });
break;
case "cancel":
break;
case "clear":
this.filterModel = this.formatFilterModel(null);
this.refreshList(false);
break;
}
}
afterAction(action, event) {
switch (action) {
case "apply": {
event?.preventDefault();
this.close();
break;
}
case "reset": {
this.close();
break;
}
case "cancel": {
this.close();
break;
}
}
}
removeItemFromParent(item) {
const sourceParentIndex = item.parent.conditions.indexOf(item.filterModel);
item.parent.conditions.splice(sourceParentIndex, 1);
return sourceParentIndex;
}
moveItemToIndex(item, destinationRowIndex, destinationPosition) {
const destinationItem = this.items[destinationRowIndex];
const destinationIsParent = destinationItem.filterModel?.filterType === "join" && destinationPosition === "bottom";
const destinationParent = destinationIsParent ? destinationItem.filterModel : destinationItem.parent;
if (!destinationParent) {
return;
}
if (this.isChildOrSelf(destinationParent, item.filterModel) || destinationItem === item) {
return;
}
this.removeItemFromParent(item);
let destinationParentIndex;
if (destinationIsParent) {
destinationParentIndex = 0;
} else {
destinationParentIndex = destinationParent.conditions.indexOf(destinationItem.filterModel);
if (destinationParentIndex === -1) {
destinationParentIndex = destinationParent.conditions.length;
} else if (destinationPosition === "bottom") {
destinationParentIndex += 1;
}
}
destinationParent.conditions.splice(destinationParentIndex, 0, item.filterModel);
this.refreshList(false);
}
isChildOrSelf(modelToCheck, potentialParentModel) {
return modelToCheck === potentialParentModel || potentialParentModel.filterType === "join" && potentialParentModel.conditions.some((condition) => this.isChildOrSelf(modelToCheck, condition));
}
setupFilterModel() {
const filterModel = this.formatFilterModel(this.advancedFilter.getModel());
this.stringifiedModel = JSON.stringify(filterModel);
return filterModel;
}
formatFilterModel(filterModel) {
filterModel = filterModel ?? {
filterType: "join",
type: "AND",
conditions: []
};
if (filterModel.filterType !== "join") {
filterModel = {
filterType: "join",
type: "AND",
conditions: [filterModel]
};
}
return filterModel;
}
buildList() {
const parseFilterModel = (filterModel, items, level, parent) => {
items.push({ filterModel, level, parent, valid: true, showMove: this.params.showMoveButtons });
if (filterModel.filterType === "join") {
filterModel.conditions.forEach(
(childFilterModel) => parseFilterModel(childFilterModel, items, level + 1, filterModel)
);
if (level === 0) {
items.push({ filterModel: null, level: level + 1, parent: filterModel, valid: true });
}
}
};
this.items = [];
parseFilterModel(this.filterModel, this.items, 0);
}
refreshList(softRefresh) {
if (!softRefresh) {
const invalidModels = [];
this.items.forEach((item) => {
if (!item.valid) {
invalidModels.push(item.filterModel);
}
});
this.buildList();
if (invalidModels.length) {
this.items.forEach((item) => {
if (item.filterModel && invalidModels.includes(item.filterModel)) {
item.valid = false;
}
});
}
}
this.virtualList.refresh(softRefresh);
this.validate();
}
updateItemComponent(item, comp) {
const index = this.items.indexOf(item);
const populateTreeLines = (filterModel2, treeLines2) => {
const parentItem = this.items.find((itemToCheck) => itemToCheck.filterModel === filterModel2);
const parentFilterModel = parentItem?.parent;
if (parentFilterModel) {
const { conditions } = parentFilterModel;
populateTreeLines(parentFilterModel, treeLines2);
treeLines2.push(conditions[conditions.length - 1] === filterModel2);
}
};
const treeLines = [];
const { filterModel } = item;
if (filterModel) {
populateTreeLines(filterModel, treeLines);
treeLines[0] = false;
}
const showStartTreeLine = filterModel?.filterType === "join" && !!filterModel.conditions.length;
comp.setState({
disableMoveUp: index === 1,
disableMoveDown: !this.canMoveDown(item, index),
treeLines,
showStartTreeLine
});
}
createItemComponent(item, focusWrapper) {
const itemComp = this.createBean(
item.filterModel ? new AdvancedFilterBuilderItemComp(item, this.dragFeature, focusWrapper) : new AdvancedFilterBuilderItemAddComp(item, focusWrapper)
);
itemComp.addManagedListeners(itemComp, {
advancedFilterBuilderRemoved: ({ item: item2 }) => this.removeItem(item2),
advancedFilterBuilderValueChanged: () => this.validate(),
advancedFilterBuilderAdded: ({ item: item2, isJoin }) => this.addItem(item2, isJoin),
advancedFilterBuilderMoved: ({ item: item2, backwards }) => this.moveItemUpDown(item2, backwards)
});
if (itemComp instanceof AdvancedFilterBuilderItemComp) {
this.updateItemComponent(item, itemComp);
}
return itemComp;
}
addItem(item, isJoin) {
const { parent: itemParent, level, filterModel: itemFilterModel } = item;
const itemIsJoin = itemFilterModel?.filterType === "join";
const filterModel = isJoin ? {
filterType: "join",
type: "AND",
conditions: []
} : {};
const parent = itemIsJoin ? itemFilterModel : itemParent;
let insertIndex = itemIsJoin ? 0 : parent.conditions.indexOf(itemFilterModel);
if (insertIndex >= 0) {
if (!itemIsJoin) {
insertIndex += 1;
}
parent.conditions.splice(insertIndex, 0, filterModel);
} else {
parent.conditions.push(filterModel);
}
let index = this.items.indexOf(item);
const softRefresh = index >= 0;
if (softRefresh) {
if (item.filterModel) {
index++;
}
const newItems = [
{
filterModel,
level: itemIsJoin ? level + 1 : level,
parent,
valid: isJoin,
showMove: this.params.showMoveButtons
}
];
this.items.splice(index, 0, ...newItems);
}
this.refreshList(softRefresh);
if (softRefresh) {
this.virtualList.getComponentAt(index)?.afterAdd();
}
}
removeItem(item) {
const parent = item.parent;
const { filterModel } = item;
const parentIndex = parent.conditions.indexOf(filterModel);
parent.conditions.splice(parentIndex, 1);
const isJoin = item.filterModel?.filterType === "join";
const index = this.items.indexOf(item);
const softRefresh = !isJoin && index >= 0;
if (softRefresh) {
this.items.splice(index, 1);
}
this.refreshList(softRefresh);
if (index >= 0) {
this.virtualList.focusRow(index);
}
}
moveItemUpDown(item, backwards, fromVirtualList) {
const itemIndex = this.items.indexOf(item);
const destinationIndex = backwards ? itemIndex - 1 : itemIndex + 1;
if (destinationIndex === 0 || !backwards && !this.canMoveDown(item, itemIndex)) {
return;
}
const destinationItem = this.items[destinationIndex];
const indexInParent = this.removeItemFromParent(item);
const { level, filterModel, parent } = item;
const {
level: destinationLevel,
filterModel: destinationFilterModel,
parent: destinationParent
} = destinationItem;
if (backwards) {
if (destinationLevel === level && destinationFilterModel.filterType === "join") {
destinationFilterModel.conditions.push(filterModel);
} else if (destinationLevel <= level) {
const destinationIndex2 = destinationParent.conditions.indexOf(destinationFilterModel);
destinationParent.conditions.splice(destinationIndex2, 0, filterModel);
} else {
const newParentItem = parent.conditions[indexInParent - 1];
newParentItem.conditions.push(filterModel);
}
} else {
if (destinationLevel === level) {
if (destinationFilterModel.filterType === "join") {
destinationFilterModel.conditions.splice(0, 0, filterModel);
} else {
const destinationIndex2 = destinationParent.conditions.indexOf(destinationFilterModel);
destinationParent.conditions.splice(destinationIndex2 + 1, 0, filterModel);
}
} else {
if (indexInParent < parent.conditions.length) {
parent.conditions.splice(indexInParent + 1, 0, filterModel);
} else {
const parentItem = this.items.find((itemToCheck) => itemToCheck.filterModel === parent);
const destinationIndex2 = parentItem.parent.conditions.indexOf(parentItem.filterModel) + 1;
parentItem.parent.conditions.splice(destinationIndex2, 0, filterModel);
}
}
}
this.refreshList(false);
const newIndex = this.items.findIndex(
({ filterModel: filterModelToCheck }) => filterModelToCheck === filterModel
);
if (newIndex < 0) {
return;
}
const comp = this.virtualList.getComponentAt(newIndex);
if (!(comp instanceof AdvancedFilterBuilderItemComp)) {
return;
}
if (!fromVirtualList) {
comp.focusMoveButton(backwards);
}
}
virtualListMoveItemCallback(itemComp, isUp) {
const item = itemComp.item;
const from = this.items.indexOf(item);
if (from <= 0 || from === this.items.length - 1) {
return;
}
if (isUp && from === 1 || !isUp && !this.canMoveDown(item, from)) {
return;
}
this.moveItemUpDown(item, isUp, true);
this.virtualList.focusRow(from + (isUp ? -1 : 1));
}
canMoveDown(item, index) {
return !(item.level === 1 && index === this.items.length - 2 || item.level === 1 && item.parent.conditions[item.parent.conditions.length - 1] === item.filterModel);
}
close() {
this.advancedFilter.getCtrl().toggleFilterBuilder({ source: "ui" });
}
validate() {
let isValid = this.items.every(({ valid }) => valid);
let validationMessage = null;
if (isValid) {
isValid = JSON.stringify(this.filterModel) !== this.stringifiedModel;
if (!isValid) {
validationMessage = this.advFilterExpSvc.translate("advancedFilterBuilderValidationAlreadyApplied");
} else {
validationMessage = null;
}
} else {
validationMessage = this.advFilterExpSvc.translate("advancedFilterBuilderValidationIncomplete");
}
this.eButtons?.updateValidity(isValid, validationMessage);
}
validateItems() {
const clearOperator = (filterModel) => {
filterModel.type = void 0;
};
const clearOperand = (filterModel) => {
delete filterModel.filter;
};
this.items.forEach((item) => {
if (!item.valid || !item.filterModel || item.filterModel.filterType === "join") {
return;
}
const { filterModel } = item;
const { colId } = filterModel;
const hasColumn = this.advFilterExpSvc.getColumnAutocompleteEntries().find(({ key }) => key === colId);
const columnDetails = this.advFilterExpSvc.getColumnDetails(filterModel.colId);
if (!hasColumn || !columnDetails.column) {
item.valid = false;
filterModel.colId = void 0;
clearOperator(filterModel);
clearOperand(filterModel);
return;
}
const operatorForType = this.advFilterExpSvc.getDataTypeExpressionOperator(columnDetails.baseCellDataType);
const operator = operatorForType.operators[filterModel.type];
if (!operator) {
item.valid = false;
clearOperator(filterModel);
clearOperand(filterModel);
return;
}
if (operator.numOperands > 0 && !(0, import_ag_grid_community37._exists)(filterModel.filter)) {
item.valid = false;
return;
}
});
}
};
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterCtrl.ts
var AdvancedFilterCtrl = class extends import_ag_grid_community38.BeanStub {
constructor(enabled) {
super();
this.enabled = enabled;
}
wireBeans(beans) {
this.ctrlsSvc = beans.ctrlsSvc;
this.popupSvc = beans.popupSvc;
this.advFilterExpSvc = beans.advFilterExpSvc;
this.environment = beans.environment;
}
postConstruct() {
this.hasAdvancedFilterParent = !!this.gos.get("advancedFilterParent");
this.ctrlsSvc.whenReady(this, () => this.setAdvancedFilterComp());
this.addManagedEventListeners({
advancedFilterEnabledChanged: ({ enabled }) => this.onEnabledChanged(enabled)
});
this.addManagedPropertyListener("advancedFilterParent", () => this.updateComps());
this.addManagedPropertyListener("advancedFilterBuilderParams", (event) => {
if (event.currentValue?.suppressFullScreenButton !== event.previousValue?.suppressFullScreenButton) {
this.eBuilderDialog?.setMaximizable(event.currentValue?.suppressFullScreenButton ?? true);
}
});
this.addDestroyFunc(() => {
this.destroyAdvancedFilterComp();
this.destroyBean(this.eBuilderComp);
if (this.eBuilderDialog && this.eBuilderDialog.isAlive()) {
this.destroyBean(this.eBuilderDialog);
}
});
}
setupHeaderComp(eCompToInsertBefore) {
if (this.eHeaderComp) {
this.eHeaderComp?.getGui().remove();
this.destroyBean(this.eHeaderComp);
}
this.eHeaderComp = this.createManagedBean(
new AdvancedFilterHeaderComp(this.enabled && !this.hasAdvancedFilterParent)
);
eCompToInsertBefore.insertAdjacentElement("beforebegin", this.eHeaderComp.getGui());
}
focusHeaderComp() {
if (this.eHeaderComp) {
this.eHeaderComp.getFocusableElement().focus();
return true;
}
return false;
}
refreshComp() {
this.eFilterComp?.refresh();
this.eHeaderComp?.refresh();
}
refreshBuilderComp() {
this.eBuilderComp?.refresh();
}
getHeaderHeight() {
return this.eHeaderComp?.getHeight() ?? 0;
}
setInputDisabled(disabled) {
this.eFilterComp?.setInputDisabled(disabled);
this.eHeaderComp?.setInputDisabled(disabled);
}
toggleFilterBuilder(params) {
const { source, force, eventSource } = params;
if (force && this.eBuilderDialog || force === false && !this.eBuilderDialog) {
return;
}
if (this.eBuilderDialog) {
this.builderDestroySource = source;
this.destroyBean(this.eBuilderDialog);
return;
}
this.setInputDisabled(true);
const { width, height, minWidth } = this.getBuilderDialogSize();
const { suppressFullScreenButton } = {
suppressFullScreenButton: false,
...this.gos.get("advancedFilterBuilderParams")
};
this.eBuilderComp = this.createBean(new AdvancedFilterBuilderComp());
this.eBuilderDialog = this.createBean(
new AgDialog({
title: this.advFilterExpSvc.translate("advancedFilterBuilderTitle"),
component: this.eBuilderComp,
width,
height,
resizable: true,
movable: true,
maximizable: !suppressFullScreenButton,
centered: true,
closable: true,
minWidth,
afterGuiAttached: () => this.eBuilderComp?.afterGuiAttached(),
postProcessPopupParams: {
type: "advancedFilterBuilder",
eventSource
}
})
);
this.dispatchFilterBuilderVisibleChangedEvent(source, true);
this.eBuilderDialog.addEventListener("destroyed", () => {
this.destroyBean(this.eBuilderComp);
this.eBuilderComp = void 0;
this.eBuilderDialog = void 0;
this.setInputDisabled(false);
this.dispatchLocalEvent({
type: "advancedFilterBuilderClosed"
});
this.dispatchFilterBuilderVisibleChangedEvent(this.builderDestroySource ?? "ui", false);
this.builderDestroySource = void 0;
});
}
dispatchFilterBuilderVisibleChangedEvent(source, visible) {
this.eventSvc.dispatchEvent({
type: "advancedFilterBuilderVisibleChanged",
source,
visible
});
}
getBuilderDialogSize() {
const minWidth = this.gos.get("advancedFilterBuilderParams")?.minWidth ?? 500;
const popupParent = this.popupSvc.getPopupParent();
const maxWidth = Math.round((0, import_ag_grid_community38._getAbsoluteWidth)(popupParent)) - 2;
const maxHeight = Math.round((0, import_ag_grid_community38._getAbsoluteHeight)(popupParent) * 0.75) - 2;
const width = Math.min(Math.max(700, minWidth), maxWidth);
const height = Math.min(600, maxHeight);
return { width, height, minWidth };
}
onEnabledChanged(enabled) {
this.enabled = enabled;
this.updateComps();
}
updateComps() {
this.setAdvancedFilterComp();
this.setHeaderCompEnabled();
this.eventSvc.dispatchEvent({
type: "headerHeightChanged"
});
}
setAdvancedFilterComp() {
this.destroyAdvancedFilterComp();
if (!this.enabled) {
return;
}
const advancedFilterParent = this.gos.get("advancedFilterParent");
this.hasAdvancedFilterParent = !!advancedFilterParent;
if (advancedFilterParent) {
const eAdvancedFilterComp = this.createBean(new AdvancedFilterComp());
const eAdvancedFilterCompGui = eAdvancedFilterComp.getGui();
this.environment.applyThemeClasses(eAdvancedFilterCompGui);
eAdvancedFilterCompGui.classList.add(this.gos.get("enableRtl") ? "ag-rtl" : "ag-ltr");
advancedFilterParent.appendChild(eAdvancedFilterCompGui);
this.eFilterComp = eAdvancedFilterComp;
}
}
setHeaderCompEnabled() {
this.eHeaderComp?.setEnabled(this.enabled && !this.hasAdvancedFilterParent);
}
destroyAdvancedFilterComp() {
if (this.eFilterComp) {
(0, import_ag_grid_community38._removeFromParent)(this.eFilterComp.getGui());
this.destroyBean(this.eFilterComp);
}
}
};
// packages/ag-grid-enterprise/src/advancedFilter/joinFilterExpressionParser.ts
var OperatorParser2 = class {
constructor(params) {
this.params = params;
this.operators = [];
this.operatorStartPositions = [];
this.operatorEndPositions = [];
this.activeOperator = 0;
this.validationError = null;
}
parseExpression(i) {
this.operators.push("");
this.operatorStartPositions.push(i);
this.operatorEndPositions.push(void 0);
const { expression } = this.params;
while (i < expression.length) {
const char = expression[i];
if (char === " ") {
const isComplete = this.parseOperator(i - 1);
if (isComplete) {
this.activeOperator++;
return i - 1;
} else {
this.operators[this.activeOperator] += char;
}
} else {
this.operators[this.activeOperator] += char;
}
i++;
}
this.parseOperator(i - 1);
return i;
}
isValid() {
return !this.validationError && (!this.operators.length || !!this.parsedOperator);
}
getValidationError() {
return this.validationError;
}
getFunction() {
return this.parsedOperator === "OR" ? "||" : "&&";
}
getModel() {
return this.parsedOperator === "OR" ? "OR" : "AND";
}
getAutocompleteListParams(position, operatorIndex) {
let searchString;
if (operatorIndex == null) {
searchString = "";
} else {
const operator = this.operators[operatorIndex];
const operatorEndPosition = this.operatorEndPositions[operatorIndex];
searchString = getSearchString(
operator,
position,
operatorEndPosition == null ? this.params.expression.length : operatorEndPosition + 1
);
}
let entries = this.params.advFilterExpSvc.getJoinOperatorAutocompleteEntries();
if (operatorIndex || operatorIndex == null && this.activeOperator) {
entries = entries.filter(({ key }) => key === this.parsedOperator);
}
return this.params.advFilterExpSvc.generateAutocompleteListParams(entries, "join", searchString);
}
updateExpression(position, updateEntry, operatorIndex) {
let { expression } = this.params;
const updatedValuePart = updateEntry.displayValue ?? updateEntry.key;
if (operatorIndex === 0) {
for (let i = this.operatorEndPositions.length - 1; i > 0; i--) {
const operatorEndPosition = this.operatorEndPositions[i];
if (operatorEndPosition == null) {
continue;
}
expression = updateExpression(
expression,
this.operatorStartPositions[i],
operatorEndPosition,
updatedValuePart
).updatedValue;
}
}
const startPosition = this.operatorStartPositions.length > operatorIndex ? this.operatorStartPositions[operatorIndex] : position;
const endPosition = (this.operatorEndPositions.length > operatorIndex ? this.operatorEndPositions[operatorIndex] : void 0) ?? findEndPosition(expression, position, true).endPosition;
return updateExpression(expression, startPosition, endPosition, updatedValuePart, true);
}
getNumOperators() {
return this.operators.length;
}
getLastOperatorEndPosition() {
return this.operatorEndPositions[this.operatorEndPositions.length - 1];
}
parseOperator(endPosition) {
const operator = this.operators.length > this.activeOperator ? this.operators[this.activeOperator] : "";
const joinOperators = this.params.advFilterExpSvc.getExpressionJoinOperators();
const parsedValue = findMatch(operator, joinOperators, (v) => v);
if (parsedValue) {
this.operatorEndPositions[this.activeOperator] = endPosition;
const displayValue = joinOperators[parsedValue];
if (this.activeOperator) {
if (parsedValue !== this.parsedOperator) {
if (!this.validationError) {
this.validationError = {
message: this.params.advFilterExpSvc.translate(
"advancedFilterValidationJoinOperatorMismatch"
),
startPosition: endPosition - operator.length + 1,
endPosition
};
}
return false;
}
} else {
this.parsedOperator = parsedValue;
}
if (operator !== displayValue) {
checkAndUpdateExpression(this.params, operator, displayValue, endPosition);
this.operators[this.activeOperator] = displayValue;
}
return true;
} else if (parsedValue === null) {
return false;
} else {
if (!this.validationError) {
this.validationError = {
message: this.params.advFilterExpSvc.translate("advancedFilterValidationInvalidJoinOperator"),
startPosition: endPosition - operator.length + 1,
endPosition
};
}
return true;
}
}
};
var JoinFilterExpressionParser = class _JoinFilterExpressionParser {
constructor(params, startPosition) {
this.params = params;
this.startPosition = startPosition;
this.expectingExpression = true;
this.expectingOperator = false;
this.expressionParsers = [];
this.operatorParser = new OperatorParser2(this.params);
this.missingEndBracket = false;
this.extraEndBracket = false;
}
parseExpression() {
let i = this.startPosition;
const { expression } = this.params;
while (i < expression.length) {
const char = expression[i];
if (char === "(" && !this.expectingOperator) {
const nestedParser = new _JoinFilterExpressionParser(this.params, i + 1);
i = nestedParser.parseExpression();
this.expressionParsers.push(nestedParser);
this.expectingExpression = false;
this.expectingOperator = true;
} else if (char === ")") {
this.endPosition = i - 1;
if (this.startPosition === 0) {
this.extraEndBracket = true;
}
return i;
} else if (char === " ") {
} else if (this.expectingExpression) {
const nestedParser = new ColFilterExpressionParser(this.params, i);
i = nestedParser.parseExpression();
this.expressionParsers.push(nestedParser);
this.expectingExpression = false;
this.expectingOperator = true;
} else if (this.expectingOperator) {
i = this.operatorParser.parseExpression(i);
this.expectingOperator = false;
this.expectingExpression = true;
}
i++;
}
if (this.startPosition > 0) {
this.missingEndBracket = true;
}
return i;
}
isValid() {
return !this.missingEndBracket && !this.extraEndBracket && this.expressionParsers.length === this.operatorParser.getNumOperators() + 1 && this.operatorParser.isValid() && this.expressionParsers.every((expressionParser) => expressionParser.isValid());
}
getValidationError() {
const operatorError = this.operatorParser.getValidationError();
for (let i = 0; i < this.expressionParsers.length; i++) {
const expressionError = this.expressionParsers[i].getValidationError();
if (expressionError) {
return operatorError && operatorError.startPosition < expressionError.startPosition ? operatorError : expressionError;
}
}
if (operatorError) {
return operatorError;
}
if (this.extraEndBracket) {
return {
message: this.params.advFilterExpSvc.translate("advancedFilterValidationExtraEndBracket"),
startPosition: this.endPosition + 1,
endPosition: this.endPosition + 1
};
}
let translateKey;
if (this.expressionParsers.length === this.operatorParser.getNumOperators()) {
translateKey = "advancedFilterValidationMissingCondition";
} else if (this.missingEndBracket) {
translateKey = "advancedFilterValidationMissingEndBracket";
}
if (translateKey) {
return {
message: this.params.advFilterExpSvc.translate(translateKey),
startPosition: this.params.expression.length,
endPosition: this.params.expression.length
};
}
return null;
}
getFunction(params) {
const operator = this.operatorParser.getFunction();
const funcs = this.expressionParsers.map((expressionParser) => expressionParser.getFunction(params));
const arrayFunc = operator === "&&" ? "every" : "some";
return (expressionProxy, node, p) => funcs[arrayFunc]((func) => func(expressionProxy, node, p));
}
getAutocompleteListParams(position) {
if (this.endPosition != null && position > this.endPosition + 1) {
return void 0;
}
if (!this.expressionParsers.length) {
return this.getColumnAutocompleteListParams();
}
const expressionParserIndex = this.getExpressionParserIndex(position);
if (expressionParserIndex == null) {
if (this.params.expression[position] === "(") {
return { enabled: false };
}
return this.getColumnAutocompleteListParams();
}
const expressionParser = this.expressionParsers[expressionParserIndex];
const autocompleteType = expressionParser.getAutocompleteListParams(position);
if (!autocompleteType) {
if (expressionParserIndex < this.expressionParsers.length - 1) {
return this.operatorParser.getAutocompleteListParams(position, expressionParserIndex);
}
if (this.expressionParsers.length === this.operatorParser.getNumOperators()) {
const operatorEndPosition = this.operatorParser.getLastOperatorEndPosition();
return operatorEndPosition == null || position <= operatorEndPosition + 1 ? this.operatorParser.getAutocompleteListParams(position, this.operatorParser.getNumOperators() - 1) : this.getColumnAutocompleteListParams();
}
if (this.params.expression[position - 1] === ")") {
return { enabled: false };
}
return this.operatorParser.getAutocompleteListParams(position);
}
return autocompleteType;
}
updateExpression(position, updateEntry, type) {
const expression = this.params.expression;
const expressionParserIndex = this.getExpressionParserIndex(position);
if (expressionParserIndex == null) {
const updatedValuePart = type === "column" ? this.params.advFilterExpSvc.getColumnValue(updateEntry) : updateEntry.displayValue ?? updateEntry.key;
return updateExpression(expression, this.startPosition, this.startPosition, updatedValuePart, true);
}
const expressionParser = this.expressionParsers[expressionParserIndex];
const updatedExpression = expressionParser.updateExpression(position, updateEntry, type);
if (updatedExpression == null) {
if (type === "column") {
return updateExpression(
expression,
position,
expression.length - 1,
this.params.advFilterExpSvc.getColumnValue(updateEntry),
true
);
} else if (this.endPosition != null && position > this.endPosition + 1) {
return null;
} else {
return this.operatorParser.updateExpression(position, updateEntry, expressionParserIndex);
}
}
return updatedExpression;
}
getModel() {
if (this.expressionParsers.length > 1) {
return {
filterType: "join",
type: this.operatorParser.getModel(),
conditions: this.expressionParsers.map((parser) => parser.getModel())
};
} else {
return this.expressionParsers[0].getModel();
}
}
getColumnAutocompleteListParams() {
return this.params.advFilterExpSvc.generateAutocompleteListParams(
this.params.advFilterExpSvc.getColumnAutocompleteEntries(),
"column",
""
);
}
getExpressionParserIndex(position) {
let expressionParserIndex;
for (let i = 0; i < this.expressionParsers.length; i++) {
const expressionParserToCheck = this.expressionParsers[i];
if (expressionParserToCheck.startPosition > position) {
break;
}
expressionParserIndex = i;
}
return expressionParserIndex;
}
};
// packages/ag-grid-enterprise/src/advancedFilter/filterExpressionParser.ts
var FilterExpressionParser = class {
constructor(params) {
this.params = params;
this.valid = false;
}
parseExpression() {
this.joinExpressionParser = new JoinFilterExpressionParser(this.params, 0);
const i = this.joinExpressionParser.parseExpression();
this.valid = i >= this.params.expression.length - 1 && this.joinExpressionParser.isValid();
return this.params.expression;
}
isValid() {
return this.valid;
}
getValidationMessage() {
const error = this.joinExpressionParser.getValidationError();
if (!error) {
return null;
}
const { message, startPosition, endPosition } = error;
return startPosition < this.params.expression.length ? this.params.advFilterExpSvc.translate("advancedFilterValidationMessage", [
message,
this.params.expression.slice(startPosition, endPosition + 1).trim()
]) : this.params.advFilterExpSvc.translate("advancedFilterValidationMessageAtEnd", [message]);
}
getFunction() {
const params = this.createFunctionParams();
return {
expressionFunction: this.joinExpressionParser.getFunction(params),
params
};
}
getAutocompleteListParams(position) {
return this.joinExpressionParser.getAutocompleteListParams(position) ?? { enabled: false };
}
updateExpression(position, updateEntry, type) {
return this.joinExpressionParser.updateExpression(position, updateEntry, type);
}
getModel() {
return this.isValid() ? this.joinExpressionParser.getModel() : null;
}
createFunctionParams() {
return {
operands: [],
operators: [],
evaluatorParams: []
};
}
};
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterService.ts
var AdvancedFilterService = class extends import_ag_grid_community39.BeanStub {
constructor() {
super(...arguments);
this.beanName = "advancedFilter";
this.appliedExpression = null;
/** The value displayed in the input, which may be invalid */
this.expression = null;
this.isValid = true;
}
wireBeans(beans) {
this.valueSvc = beans.valueSvc;
this.colModel = beans.colModel;
this.dataTypeSvc = beans.dataTypeSvc;
this.advFilterExpSvc = beans.advFilterExpSvc;
this.filterValueSvc = beans.filterValueSvc;
}
postConstruct() {
this.setEnabled(this.gos.get("enableAdvancedFilter"), true);
this.ctrl = this.createManagedBean(new AdvancedFilterCtrl(this.enabled));
this.expressionProxy = {
getValue: (colId, node) => {
const column = this.colModel.getColDefCol(colId);
return column ? this.filterValueSvc.getValue(column, node) : void 0;
}
};
this.addManagedPropertyListener("enableAdvancedFilter", (event) => this.setEnabled(!!event.currentValue));
this.addManagedEventListeners({
newColumnsLoaded: (event) => this.onNewColumnsLoaded(event)
});
this.addManagedPropertyListener("includeHiddenColumnsInAdvancedFilter", () => this.updateValidity());
}
isEnabled() {
return this.enabled;
}
isFilterPresent() {
return !!this.expressionFunction;
}
doesFilterPass(node) {
return this.expressionFunction(this.expressionProxy, node, this.expressionParams);
}
getModel() {
const expressionParser = this.createExpressionParser(this.appliedExpression);
expressionParser?.parseExpression();
return expressionParser?.getModel() ?? null;
}
setModel(model) {
const parseModel = (model2, isFirstParent) => {
if (model2.filterType === "join") {
const operator = this.advFilterExpSvc.parseJoinOperator(model2);
const expression2 = model2.conditions.map((condition) => parseModel(condition)).filter((condition) => (0, import_ag_grid_community39._exists)(condition)).join(` ${operator} `);
return isFirstParent || model2.conditions.length <= 1 ? expression2 : `(${expression2})`;
} else {
return this.advFilterExpSvc.parseColumnFilterModel(model2);
}
};
const expression = model ? parseModel(model, true) : null;
this.setExpressionDisplayValue(expression);
this.applyExpression();
this.ctrl.refreshComp();
this.ctrl.refreshBuilderComp();
}
getExpressionDisplayValue() {
return this.expression;
}
setExpressionDisplayValue(expression) {
this.expression = expression;
}
isCurrentExpressionApplied() {
return this.appliedExpression === this.expression;
}
createExpressionParser(expression) {
if (!expression) {
return null;
}
return new FilterExpressionParser({
expression,
colModel: this.colModel,
dataTypeSvc: this.dataTypeSvc,
valueSvc: this.valueSvc,
advFilterExpSvc: this.advFilterExpSvc
});
}
getDefaultExpression(updateEntry) {
const updatedValue = this.advFilterExpSvc.getColumnValue(updateEntry) + " ";
return {
updatedValue,
updatedPosition: updatedValue.length
};
}
isHeaderActive() {
return !this.gos.get("advancedFilterParent");
}
getCtrl() {
return this.ctrl;
}
setEnabled(enabled, silent) {
const previousValue = this.enabled;
const isValidRowModel = (0, import_ag_grid_community39._isClientSideRowModel)(this.gos) || (0, import_ag_grid_community39._isServerSideRowModel)(this.gos);
if (enabled && !isValidRowModel) {
(0, import_ag_grid_community39._warn)(123);
}
this.enabled = enabled && isValidRowModel;
if (!silent && this.enabled !== previousValue) {
this.eventSvc.dispatchEvent({
type: "advancedFilterEnabledChanged",
enabled: this.enabled
});
}
}
applyExpression() {
const expressionParser = this.createExpressionParser(this.expression);
expressionParser?.parseExpression();
this.applyExpressionFromParser(expressionParser);
}
getAppliedExpressionDisplayValue() {
return this.appliedExpression;
}
applyExpressionFromParser(expressionParser) {
this.isValid = !expressionParser || expressionParser.isValid();
if (!expressionParser || !this.isValid) {
this.expressionFunction = null;
this.expressionParams = null;
this.appliedExpression = null;
return;
}
const { expressionFunction, params } = expressionParser.getFunction();
this.expressionFunction = expressionFunction;
this.expressionParams = params;
this.appliedExpression = this.expression;
}
updateValidity() {
this.advFilterExpSvc.resetColumnCaches();
const expressionParser = this.createExpressionParser(this.expression);
expressionParser?.parseExpression();
const isValid = !expressionParser || expressionParser.isValid();
const updatedValidity = isValid !== this.isValid;
this.applyExpressionFromParser(expressionParser);
this.ctrl.refreshComp();
this.ctrl.refreshBuilderComp();
return updatedValidity;
}
onNewColumnsLoaded(event) {
if (event.source !== "gridInitializing" || !this.dataTypeSvc?.isPendingInference) {
return;
}
this.ctrl.setInputDisabled(true);
const [destroyFunc] = this.addManagedEventListeners({
dataTypesInferred: () => {
destroyFunc?.();
this.ctrl.setInputDisabled(false);
}
});
}
};
// packages/ag-grid-enterprise/src/advancedFilter/advancedFilterModule.ts
var AdvancedFilterModule = {
moduleName: "AdvancedFilter",
version: VERSION,
beans: [AdvancedFilterService, AdvancedFilterExpressionService],
icons: {
// Builder button in Advanced Filter
advancedFilterBuilder: "group",
// drag handle used to pick up Advanced Filter Builder rows
advancedFilterBuilderDrag: "grip",
// Advanced Filter Builder row validation error
advancedFilterBuilderInvalid: "not-allowed",
// shown on Advanced Filter Builder rows to move them up
advancedFilterBuilderMoveUp: "up",
// shown on Advanced Filter Builder rows to move them down
advancedFilterBuilderMoveDown: "down",
// shown on Advanced Filter Builder rows to add new rows
advancedFilterBuilderAdd: "plus",
// shown on Advanced Filter Builder rows to remove row
advancedFilterBuilderRemove: "minus",
// shown on Advanced Filter Builder selection pills
advancedFilterBuilderSelectOpen: "small-down",
// remove for rich select editor pills
richSelectRemove: "cancel"
},
apiFunctions: {
getAdvancedFilterModel,
setAdvancedFilterModel,
showAdvancedFilterBuilder,
hideAdvancedFilterBuilder
},
dependsOn: [
EnterpriseCoreModule,
import_ag_grid_community40._FilterCoreModule,
import_ag_grid_community40._SharedDragAndDropModule,
import_ag_grid_community40._PopupModule,
import_ag_grid_community40._FilterValueModule,
import_ag_grid_community40.TooltipModule
],
css: [advancedFilterCSS]
};
// packages/ag-grid-enterprise/src/columnToolPanel/columnsToolPanelModule.ts
var import_ag_grid_community77 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/sideBar/sideBarModule.ts
var import_ag_grid_community50 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/sideBar/sideBarApi.ts
var import_ag_grid_community41 = require("ag-grid-community");
function isSideBarVisible(beans) {
return beans.sideBar?.comp.isDisplayed() ?? false;
}
function setSideBarVisible(beans, show) {
beans.sideBar?.comp.setDisplayed(show);
}
function setSideBarPosition(beans, position) {
beans.sideBar?.comp.setSideBarPosition(position);
}
function openToolPanel(beans, key) {
beans.sideBar?.comp.openToolPanel(key, "api");
}
function closeToolPanel(beans) {
beans.sideBar?.comp.close("api");
}
function getOpenedToolPanel(beans) {
return beans.sideBar?.comp.openedItem() ?? null;
}
function refreshToolPanel(beans) {
beans.sideBar?.comp.refresh();
}
function isToolPanelShowing(beans) {
return beans.sideBar?.comp.isToolPanelShowing() ?? false;
}
function getToolPanelInstance(beans, id) {
const comp = beans.sideBar?.comp.getToolPanelInstance(id);
return (0, import_ag_grid_community41._unwrapUserComp)(comp);
}
function getSideBar(beans) {
return beans.sideBar?.comp.getDef();
}
// packages/ag-grid-enterprise/src/sideBar/sideBarService.ts
var import_ag_grid_community49 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/sideBar/agSideBar.ts
var import_ag_grid_community48 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/misc/enterpriseFocusUtils.ts
var import_ag_grid_community42 = require("ag-grid-community");
function findFocusableElementBeforeTabGuard(rootNode, referenceElement) {
if (!referenceElement) {
return null;
}
const focusableElements = (0, import_ag_grid_community42._findFocusableElements)(rootNode);
const referenceIndex = focusableElements.indexOf(referenceElement);
if (referenceIndex === -1) {
return null;
}
let lastTabGuardIndex = -1;
for (let i = referenceIndex - 1; i >= 0; i--) {
if (focusableElements[i].classList.contains(import_ag_grid_community42.TabGuardClassNames.TAB_GUARD_TOP)) {
lastTabGuardIndex = i;
break;
}
}
if (lastTabGuardIndex <= 0) {
return null;
}
return focusableElements[lastTabGuardIndex - 1];
}
function isTargetUnderManagedComponent(rootNode, target) {
if (!target) {
return false;
}
const managedContainers = rootNode.querySelectorAll(`.${import_ag_grid_community42._FOCUS_MANAGED_CLASS}`);
if (!managedContainers.length) {
return false;
}
for (let i = 0; i < managedContainers.length; i++) {
if (managedContainers[i].contains(target)) {
return true;
}
}
return false;
}
// packages/ag-grid-enterprise/src/sideBar/agSideBar.css-GENERATED.ts
var agSideBarCSS = (
/*css*/
`.ag-tool-panel-wrapper{display:flex;overflow:hidden auto;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:var(--ag-side-bar-panel-width)}.ag-select-agg-func-item{align-items:center;display:flex;flex:1 1 auto;flex-flow:row nowrap;height:100%;overflow:hidden;position:relative;text-overflow:ellipsis;white-space:nowrap;>*{flex:none}}.ag-tool-panel-horizontal-resize{cursor:ew-resize;height:100%;position:absolute;top:0;width:5px;z-index:1}.ag-side-bar{background-color:var(--ag-side-bar-background-color);display:flex;flex-direction:row-reverse;position:relative}:where(.ag-ltr) :where(.ag-side-bar-left) .ag-tool-panel-horizontal-resize{right:-3px}:where(.ag-rtl) :where(.ag-side-bar-left) .ag-tool-panel-horizontal-resize{left:-3px}:where(.ag-ltr) :where(.ag-side-bar-right) .ag-tool-panel-horizontal-resize{left:-3px}:where(.ag-rtl) :where(.ag-side-bar-right) .ag-tool-panel-horizontal-resize{right:-3px}.ag-side-bar-left{flex-direction:row;order:-1}.ag-side-buttons{background-color:var(--ag-side-button-bar-background-color);padding-top:var(--ag-side-button-bar-top-padding);position:relative}.ag-side-button{background-color:var(--ag-side-button-background-color);border-bottom:var(--ag-side-button-border);border-top:var(--ag-side-button-border);color:var(--ag-side-button-text-color);margin-top:-1px;position:relative;&:before{background-color:transparent;bottom:0;content:"";display:block;position:absolute;top:0;transition:background-color var(--ag-side-button-selected-underline-transition-duration);width:var(--ag-side-button-selected-underline-width)}&:hover{background-color:var(--ag-side-button-hover-background-color);color:var(--ag-side-button-hover-text-color)}&.ag-selected{background-color:var(--ag-side-button-selected-background-color);border-bottom:var(--ag-side-button-selected-border);border-top:var(--ag-side-button-selected-border);color:var(--ag-side-button-selected-text-color);&:before{background-color:var(--ag-side-button-selected-underline-color)}}}:where(.ag-ltr) .ag-side-button{&:before{left:0}}:where(.ag-rtl) .ag-side-button{&:before{right:0}}.ag-side-button-button{align-items:center;display:flex;flex-direction:column;gap:var(--ag-spacing);position:relative;white-space:nowrap;width:100%;&:focus{box-shadow:none}}:where(.ag-ltr) .ag-side-button-button{padding:var(--ag-side-button-vertical-padding) var(--ag-side-button-right-padding) var(--ag-side-button-vertical-padding) var(--ag-side-button-left-padding)}:where(.ag-rtl) .ag-side-button-button{padding:var(--ag-side-button-vertical-padding) var(--ag-side-button-left-padding) var(--ag-side-button-vertical-padding) var(--ag-side-button-right-padding)}.ag-side-button-button:focus-visible{box-shadow:inset var(--ag-focus-shadow)}.ag-side-button-label{writing-mode:vertical-lr}@media (resolution <= 1.5x){.ag-side-button-label{font-family:"Segoe UI",var(--ag-font-family)}:where(.ag-ltr) .ag-side-button-label{transform:rotate(.05deg)}:where(.ag-rtl) .ag-side-button-label{transform:rotate(-.05deg)}}:where(.ag-ltr) .ag-side-bar-left,:where(.ag-rtl) .ag-side-bar-right{border-right:var(--ag-side-panel-border);:where(.ag-tool-panel-wrapper){border-left:var(--ag-side-panel-border)}}:where(.ag-ltr) .ag-side-bar-right,:where(.ag-rtl) .ag-side-bar-left{border-left:var(--ag-side-panel-border);:where(.ag-tool-panel-wrapper){border-right:var(--ag-side-panel-border)}}`
);
// packages/ag-grid-enterprise/src/sideBar/agSideBarButtons.ts
var import_ag_grid_community44 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/sideBar/sideBarButtonComp.ts
var import_ag_grid_community43 = require("ag-grid-community");
var SideBarButtonElement = {
tag: "div",
cls: "ag-side-button",
role: "presentation",
children: [
{
tag: "button",
ref: "eToggleButton",
cls: "ag-button ag-side-button-button",
role: "tab",
attrs: { type: "button", tabindex: "-1", "aria-expanded": "false" },
children: [
{
tag: "div",
ref: "eIconWrapper",
cls: "ag-side-button-icon-wrapper",
attrs: { "aria-hidden": "true" }
},
{ tag: "span", ref: "eLabel", cls: "ag-side-button-label" }
]
}
]
};
var SideBarButtonComp = class extends import_ag_grid_community43.Component {
constructor(toolPanelDef) {
super();
this.toolPanelDef = toolPanelDef;
this.eToggleButton = import_ag_grid_community43.RefPlaceholder;
this.eIconWrapper = import_ag_grid_community43.RefPlaceholder;
this.eLabel = import_ag_grid_community43.RefPlaceholder;
}
getToolPanelId() {
return this.toolPanelDef.id;
}
postConstruct() {
this.setTemplate(SideBarButtonElement, []);
this.setLabel();
this.setIcon();
this.addManagedElementListeners(this.eToggleButton, { click: this.onButtonPressed.bind(this) });
this.eToggleButton.setAttribute("id", `ag-${this.getCompId()}-button`);
}
setLabel() {
const def = this.toolPanelDef;
const label = this.getLocaleTextFunc()(def.labelKey, def.labelDefault);
this.eLabel.textContent = label;
}
setIcon() {
this.eIconWrapper.insertAdjacentElement(
"afterbegin",
(0, import_ag_grid_community43._createIconNoSpan)(this.toolPanelDef.iconKey, this.beans)
);
}
onButtonPressed() {
this.dispatchLocalEvent({ type: "toggleButtonClicked" });
}
setSelected(selected) {
this.toggleCss("ag-selected", selected);
(0, import_ag_grid_community43._setAriaExpanded)(this.eToggleButton, selected);
}
};
// packages/ag-grid-enterprise/src/sideBar/agSideBarButtons.ts
var SideBarElement = { tag: "div", cls: "ag-side-buttons", role: "tablist" };
var AgSideBarButtons = class extends import_ag_grid_community44.Component {
constructor() {
super(SideBarElement);
this.buttonComps = [];
}
postConstruct() {
this.addManagedElementListeners(this.getFocusableElement(), { keydown: this.handleKeyDown.bind(this) });
}
handleKeyDown(e) {
if (e.key !== import_ag_grid_community44.KeyCode.TAB || !e.shiftKey) {
return;
}
if ((0, import_ag_grid_community44._focusNextGridCoreContainer)(this.beans, true)) {
e.preventDefault();
return;
}
(0, import_ag_grid_community44._stopPropagationForAgGrid)(e);
}
setActiveButton(id) {
this.buttonComps.forEach((comp) => {
comp.setSelected(id === comp.getToolPanelId());
});
}
addButtonComp(def) {
const buttonComp = this.createBean(new SideBarButtonComp(def));
this.buttonComps.push(buttonComp);
this.appendChild(buttonComp);
buttonComp.addEventListener("toggleButtonClicked", () => {
this.dispatchLocalEvent({
type: "sideBarButtonClicked",
toolPanelId: def.id
});
});
return buttonComp;
}
clearButtons() {
this.buttonComps = this.destroyBeans(this.buttonComps);
(0, import_ag_grid_community44._clearElement)(this.getGui());
super.destroy();
}
destroy() {
this.clearButtons();
super.destroy();
}
};
var AgSideBarButtonsSelector = {
selector: "AG-SIDE-BAR-BUTTONS",
component: AgSideBarButtons
};
// packages/ag-grid-enterprise/src/sideBar/sideBarDefParser.ts
var import_ag_grid_community45 = require("ag-grid-community");
var DEFAULT_COLUMN_COMP = {
id: "columns",
labelDefault: "Columns",
labelKey: "columns",
iconKey: "columnsToolPanel",
toolPanel: "agColumnsToolPanel"
};
var DEFAULT_FILTER_COMP = {
id: "filters",
labelDefault: "Filters",
labelKey: "filters",
iconKey: "filtersToolPanel",
toolPanel: "agFiltersToolPanel"
};
var DEFAULT_NEW_FILTER_COMP = {
id: "filters-new",
labelDefault: "Filters",
labelKey: "filters",
iconKey: "filtersToolPanel",
toolPanel: "agNewFiltersToolPanel"
};
var DEFAULT_BY_KEY = {
columns: DEFAULT_COLUMN_COMP,
filters: DEFAULT_FILTER_COMP,
"filters-new": DEFAULT_NEW_FILTER_COMP
};
function parseSideBarDef(toParse) {
if (!toParse) {
return void 0;
}
if (toParse === true) {
return {
toolPanels: [DEFAULT_COLUMN_COMP, DEFAULT_FILTER_COMP],
defaultToolPanel: "columns"
};
}
if (typeof toParse === "string") {
return parseSideBarDef([toParse]);
}
if (Array.isArray(toParse)) {
const comps = [];
toParse.forEach((key) => {
const lookupResult = DEFAULT_BY_KEY[key];
if (!lookupResult) {
(0, import_ag_grid_community45._warn)(215, { key, defaultByKey: DEFAULT_BY_KEY });
return;
}
comps.push(lookupResult);
});
if (comps.length === 0) {
return void 0;
}
return {
toolPanels: comps,
defaultToolPanel: comps[0].id
};
}
const result = {
toolPanels: parseComponents(toParse.toolPanels),
defaultToolPanel: toParse.defaultToolPanel,
hiddenByDefault: toParse.hiddenByDefault,
position: toParse.position
};
return result;
}
function parseComponents(from) {
const result = [];
if (!from) {
return result;
}
from.forEach((it) => {
let toAdd = null;
if (typeof it === "string") {
const lookupResult = DEFAULT_BY_KEY[it];
if (!lookupResult) {
(0, import_ag_grid_community45._warn)(215, { key: it, defaultByKey: DEFAULT_BY_KEY });
return;
}
toAdd = lookupResult;
} else {
toAdd = it;
}
result.push(toAdd);
});
return result;
}
// packages/ag-grid-enterprise/src/sideBar/toolPanelWrapper.ts
var import_ag_grid_community47 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/sideBar/agHorizontalResize.ts
var import_ag_grid_community46 = require("ag-grid-community");
var AgHorizontalResize = class extends import_ag_grid_community46.Component {
constructor() {
super({ tag: "div", cls: "ag-tool-panel-horizontal-resize" });
this.minWidth = 100;
this.maxWidth = null;
}
postConstruct() {
const finishedWithResizeFunc = this.beans.horizontalResizeSvc.addResizeBar({
eResizeBar: this.getGui(),
dragStartPixels: 1,
onResizeStart: this.onResizeStart.bind(this),
onResizing: this.onResizing.bind(this),
onResizeEnd: this.onResizeEnd.bind(this)
});
this.addDestroyFunc(finishedWithResizeFunc);
this.inverted = this.gos.get("enableRtl");
}
dispatchResizeEvent(start, end, width) {
this.eventSvc.dispatchEvent({
type: "toolPanelSizeChanged",
width,
started: start,
ended: end
});
}
onResizeStart() {
this.startingWidth = this.elementToResize.offsetWidth;
this.dispatchResizeEvent(true, false, this.startingWidth);
}
onResizeEnd(delta) {
return this.onResizing(delta, true);
}
onResizing(delta, isEnd = false) {
const direction = this.inverted ? -1 : 1;
let newWidth = Math.max(this.minWidth, Math.floor(this.startingWidth - delta * direction));
if (this.maxWidth != null) {
newWidth = Math.min(this.maxWidth, newWidth);
}
this.elementToResize.style.width = `${newWidth}px`;
this.dispatchResizeEvent(false, isEnd, newWidth);
}
};
// packages/ag-grid-enterprise/src/sideBar/toolPanelWrapper.ts
function getToolPanelCompDetails(userCompFactory, toolPanelDef, params) {
return userCompFactory.getCompDetails(toolPanelDef, ToolPanelComponent, void 0, params, true);
}
var ToolPanelComponent = {
name: "toolPanel",
optionalMethods: ["refresh", "getState"]
};
var ToolPanelElement = {
tag: "div",
cls: "ag-tool-panel-wrapper",
role: "tabpanel"
};
var ToolPanelWrapper = class extends import_ag_grid_community47.Component {
constructor() {
super(ToolPanelElement);
}
postConstruct() {
const eGui = this.getGui();
const resizeBar = this.resizeBar = this.createManagedBean(new AgHorizontalResize());
eGui.setAttribute("id", `ag-${this.getCompId()}`);
resizeBar.elementToResize = eGui;
this.appendChild(resizeBar);
}
getToolPanelId() {
return this.toolPanelId;
}
setToolPanelDef(toolPanelDef, params) {
const { id, minWidth, maxWidth, width } = toolPanelDef;
this.toolPanelId = id;
this.width = width;
const compDetails = getToolPanelCompDetails(this.beans.userCompFactory, toolPanelDef, params);
if (compDetails == null) {
return false;
}
const componentPromise = compDetails.newAgStackInstance();
this.params = compDetails.params;
componentPromise.then(this.setToolPanelComponent.bind(this));
const resizeBar = this.resizeBar;
if (minWidth != null) {
resizeBar.minWidth = minWidth;
}
if (maxWidth != null) {
resizeBar.maxWidth = maxWidth;
}
return true;
}
setToolPanelComponent(compInstance) {
this.toolPanelCompInstance = compInstance;
this.appendChild(compInstance.getGui());
this.addDestroyFunc(() => {
this.destroyBean(compInstance);
});
const width = this.width;
if (width) {
this.getGui().style.width = `${width}px`;
}
}
getToolPanelInstance() {
return this.toolPanelCompInstance;
}
setResizerSizerSide(side) {
const isRtl = this.gos.get("enableRtl");
const isLeft = side === "left";
const inverted = isRtl ? isLeft : !isLeft;
this.resizeBar.inverted = inverted;
}
refresh() {
this.toolPanelCompInstance?.refresh(this.params);
}
};
// packages/ag-grid-enterprise/src/sideBar/agSideBar.ts
var AgSideBarElement = {
tag: "div",
cls: "ag-side-bar ag-unselectable",
children: [
{
tag: "ag-side-bar-buttons",
ref: "sideBarButtons"
}
]
};
var AgSideBar = class extends import_ag_grid_community48.Component {
constructor() {
super(AgSideBarElement, [AgSideBarButtonsSelector]);
this.sideBarButtons = import_ag_grid_community48.RefPlaceholder;
this.toolPanelWrappers = [];
this.registerCSS(agSideBarCSS);
}
postConstruct() {
this.sideBarButtons.addEventListener("sideBarButtonClicked", this.onToolPanelButtonClicked.bind(this));
const { beans, gos } = this;
const { sideBar: sideBarState } = gos.get("initialState") ?? {};
this.setSideBarDef({
sideBarDef: parseSideBarDef(gos.get("sideBar")),
sideBarState
});
this.addManagedPropertyListener("sideBar", () => this.setState());
beans.sideBar.comp = this;
const eGui = this.getFocusableElement();
this.createManagedBean(
new import_ag_grid_community48.ManagedFocusFeature(eGui, {
onTabKeyDown: this.onTabKeyDown.bind(this),
handleKeyDown: this.handleKeyDown.bind(this)
})
);
(0, import_ag_grid_community48._addFocusableContainerListener)(beans, this, eGui);
}
onTabKeyDown(e) {
if (e.defaultPrevented) {
return;
}
const { beans, sideBarButtons } = this;
const eGui = this.getGui();
const sideBarGui = sideBarButtons.getGui();
const activeElement = (0, import_ag_grid_community48._getActiveDomElement)(beans);
const openPanel = eGui.querySelector(".ag-tool-panel-wrapper:not(.ag-hidden)");
const target = e.target;
const backwards = e.shiftKey;
if (!openPanel) {
if ((0, import_ag_grid_community48._focusNextGridCoreContainer)(beans, backwards)) {
e.preventDefault();
return true;
}
return (0, import_ag_grid_community48._focusNextGridCoreContainer)(beans, backwards, true);
}
if (sideBarGui.contains(activeElement)) {
if ((0, import_ag_grid_community48._focusInto)(openPanel, backwards)) {
e.preventDefault();
}
return;
}
if (!backwards) {
return;
}
let nextEl = null;
if (openPanel.contains(activeElement)) {
nextEl = (0, import_ag_grid_community48._findNextFocusableElement)(beans, openPanel, void 0, true);
} else if (isTargetUnderManagedComponent(openPanel, target) && backwards) {
nextEl = findFocusableElementBeforeTabGuard(openPanel, target);
}
if (!nextEl) {
nextEl = sideBarGui.querySelector(".ag-selected button");
}
if (nextEl && nextEl !== e.target) {
e.preventDefault();
nextEl.focus();
}
}
handleKeyDown(e) {
const currentButton = (0, import_ag_grid_community48._getActiveDomElement)(this.beans);
const sideBarButtons = this.sideBarButtons;
if (!sideBarButtons.getGui().contains(currentButton)) {
return;
}
const sideBarGui = sideBarButtons.getGui();
const buttons = Array.prototype.slice.call(sideBarGui.querySelectorAll(".ag-side-button"));
const currentPos = buttons.findIndex((button) => button.contains(currentButton));
let nextPos = null;
switch (e.key) {
case import_ag_grid_community48.KeyCode.LEFT:
case import_ag_grid_community48.KeyCode.UP:
nextPos = Math.max(0, currentPos - 1);
break;
case import_ag_grid_community48.KeyCode.RIGHT:
case import_ag_grid_community48.KeyCode.DOWN:
nextPos = Math.min(currentPos + 1, buttons.length - 1);
break;
}
if (nextPos === null) {
return;
}
const innerButton = buttons[nextPos].querySelector("button");
if (innerButton) {
innerButton.focus();
e.preventDefault();
}
}
onToolPanelButtonClicked(event) {
const id = event.toolPanelId;
const openedItem = this.openedItem();
if (openedItem === id) {
this.openToolPanel(void 0, "sideBarButtonClicked");
} else {
this.openToolPanel(id, "sideBarButtonClicked");
}
}
clearDownUi() {
this.sideBarButtons.clearButtons();
this.destroyToolPanelWrappers();
}
setSideBarDef({
sideBarDef,
sideBarState,
existingToolPanelWrappers
}) {
this.setDisplayed(false);
this.sideBar = sideBarDef;
if (!!sideBarDef && !!sideBarDef.toolPanels) {
const toolPanelDefs = sideBarDef.toolPanels;
this.createToolPanelsAndSideButtons(toolPanelDefs, sideBarState, existingToolPanelWrappers);
if (!this.toolPanelWrappers.length) {
return;
}
const shouldDisplaySideBar = sideBarState ? sideBarState.visible : !sideBarDef.hiddenByDefault;
this.setDisplayed(shouldDisplaySideBar);
this.setSideBarPosition(sideBarState ? sideBarState.position : sideBarDef.position);
if (shouldDisplaySideBar) {
if (sideBarState) {
const { openToolPanel: openToolPanel2 } = sideBarState;
if (openToolPanel2) {
this.openToolPanel(openToolPanel2, "sideBarInitializing");
}
} else {
this.openToolPanel(sideBarDef.defaultToolPanel, "sideBarInitializing");
}
}
}
}
getDef() {
return this.sideBar;
}
setSideBarPosition(position) {
if (!position) {
position = "right";
}
this.position = position;
const isLeft = position === "left";
const resizerSide = isLeft ? "right" : "left";
this.toggleCss("ag-side-bar-left", isLeft);
this.toggleCss("ag-side-bar-right", !isLeft);
this.toolPanelWrappers.forEach((wrapper) => {
wrapper.setResizerSizerSide(resizerSide);
});
this.dispatchSideBarUpdated();
return this;
}
setDisplayed(displayed, options) {
super.setDisplayed(displayed, options);
this.dispatchSideBarUpdated();
}
getState() {
const toolPanels = {};
this.toolPanelWrappers.forEach((wrapper) => {
toolPanels[wrapper.getToolPanelId()] = wrapper.getToolPanelInstance()?.getState?.();
});
return {
visible: this.isDisplayed(),
position: this.position,
openToolPanel: this.openedItem(),
toolPanels
};
}
createToolPanelsAndSideButtons(defs, sideBarState, existingToolPanelWrappers) {
for (const def of defs) {
this.createToolPanelAndSideButton(
def,
sideBarState?.toolPanels?.[def.id],
existingToolPanelWrappers?.[def.id]
);
}
}
validateDef(def) {
const { id, toolPanel } = def;
if (id == null) {
(0, import_ag_grid_community48._warn)(212);
return false;
}
if (toolPanel === "agFiltersToolPanel" || toolPanel === "agNewFiltersToolPanel") {
if (this.beans.filterManager?.isAdvFilterEnabled()) {
(0, import_ag_grid_community48._warn)(213);
return false;
}
}
return true;
}
createToolPanelAndSideButton(def, initialState, existingToolPanelWrapper) {
if (!this.validateDef(def)) {
return;
}
let wrapper;
if (existingToolPanelWrapper) {
wrapper = existingToolPanelWrapper;
} else {
wrapper = this.createBean(new ToolPanelWrapper());
const created = wrapper.setToolPanelDef(
def,
(0, import_ag_grid_community48._addGridCommonParams)(this.gos, {
initialState,
onStateUpdated: () => this.dispatchSideBarUpdated()
})
);
if (!created) {
return;
}
}
wrapper.setDisplayed(false);
const wrapperGui = wrapper.getGui();
this.appendChild(wrapperGui);
this.toolPanelWrappers.push(wrapper);
const button = this.sideBarButtons.addButtonComp(def);
(0, import_ag_grid_community48._setAriaControlsAndLabel)(button.eToggleButton, wrapperGui);
}
refresh() {
this.toolPanelWrappers.forEach((wrapper) => wrapper.refresh());
}
openToolPanel(key, source = "api") {
const currentlyOpenedKey = this.openedItem();
if (currentlyOpenedKey === key) {
return;
}
this.toolPanelWrappers.forEach((wrapper) => {
const show = key === wrapper.getToolPanelId();
wrapper.setDisplayed(show);
});
const newlyOpenedKey = this.openedItem();
const openToolPanelChanged = currentlyOpenedKey !== newlyOpenedKey;
if (openToolPanelChanged) {
this.sideBarButtons.setActiveButton(key);
this.raiseToolPanelVisibleEvent(key, currentlyOpenedKey ?? void 0, source);
}
}
getToolPanelInstance(key) {
const toolPanelWrapper = this.toolPanelWrappers.filter((toolPanel) => toolPanel.getToolPanelId() === key)[0];
if (!toolPanelWrapper) {
(0, import_ag_grid_community48._warn)(214, { key });
return;
}
return toolPanelWrapper.getToolPanelInstance();
}
raiseToolPanelVisibleEvent(key, previousKey, source) {
const switchingToolPanel = !!key && !!previousKey;
const eventSvc = this.eventSvc;
if (previousKey) {
eventSvc.dispatchEvent({
type: "toolPanelVisibleChanged",
source,
key: previousKey,
visible: false,
switchingToolPanel
});
}
if (key) {
eventSvc.dispatchEvent({
type: "toolPanelVisibleChanged",
source,
key,
visible: true,
switchingToolPanel
});
}
}
close(source = "api") {
this.openToolPanel(void 0, source);
}
isToolPanelShowing() {
return !!this.openedItem();
}
openedItem() {
let activeToolPanel = null;
this.toolPanelWrappers.forEach((wrapper) => {
if (wrapper.isDisplayed()) {
activeToolPanel = wrapper.getToolPanelId();
}
});
return activeToolPanel;
}
setState(sideBarState) {
const sideBarDef = parseSideBarDef(this.gos.get("sideBar"));
const existingToolPanelWrappers = {};
if (sideBarDef && this.sideBar) {
sideBarDef.toolPanels?.forEach((toolPanelDef) => {
const { id } = toolPanelDef;
if (!id) {
return;
}
const existingToolPanelDef = this.sideBar.toolPanels?.find(
(toolPanelDefToCheck) => toolPanelDefToCheck.id === id
);
if (!existingToolPanelDef || toolPanelDef.toolPanel !== existingToolPanelDef.toolPanel) {
return;
}
const toolPanelWrapper = this.toolPanelWrappers.find((toolPanel) => toolPanel.getToolPanelId() === id);
if (!toolPanelWrapper) {
return;
}
const params = (0, import_ag_grid_community48._addGridCommonParams)(this.gos, {
...toolPanelDef.toolPanelParams ?? {},
onStateUpdated: () => this.dispatchSideBarUpdated()
});
const hasRefreshed = toolPanelWrapper.getToolPanelInstance()?.refresh(params);
if (hasRefreshed !== true) {
return;
}
this.toolPanelWrappers = this.toolPanelWrappers.filter((toolPanel) => toolPanel !== toolPanelWrapper);
(0, import_ag_grid_community48._removeFromParent)(toolPanelWrapper.getGui());
existingToolPanelWrappers[id] = toolPanelWrapper;
});
}
this.clearDownUi();
this.setSideBarDef({ sideBarDef, sideBarState, existingToolPanelWrappers });
}
dispatchSideBarUpdated() {
this.eventSvc.dispatchEvent({ type: "sideBarUpdated" });
}
destroyToolPanelWrappers() {
this.toolPanelWrappers.forEach((wrapper) => {
(0, import_ag_grid_community48._removeFromParent)(wrapper.getGui());
this.destroyBean(wrapper);
});
this.toolPanelWrappers.length = 0;
}
destroy() {
this.destroyToolPanelWrappers();
super.destroy();
}
};
var AgSideBarSelector = {
selector: "AG-SIDE-BAR",
component: AgSideBar
};
// packages/ag-grid-enterprise/src/sideBar/sideBarService.ts
var SideBarService = class extends import_ag_grid_community49.BeanStub {
constructor() {
super(...arguments);
this.beanName = "sideBar";
}
getSelector() {
return AgSideBarSelector;
}
};
// packages/ag-grid-enterprise/src/sideBar/sideBarModule.ts
var SideBarModule = {
moduleName: "SideBar",
version: VERSION,
beans: [SideBarService],
apiFunctions: {
isSideBarVisible,
setSideBarVisible,
setSideBarPosition,
openToolPanel,
closeToolPanel,
getOpenedToolPanel,
refreshToolPanel,
isToolPanelShowing,
getToolPanelInstance,
getSideBar
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community50._HorizontalResizeModule]
};
// packages/ag-grid-enterprise/src/widgets/agMenuItemRenderer.ts
var import_ag_grid_community51 = require("ag-grid-community");
var MenuItemElement = { tag: "div" };
var AgMenuItemRenderer = class extends import_ag_grid_community51.Component {
constructor() {
super(MenuItemElement);
}
init(params) {
this.params = params;
this.cssClassPrefix = this.params.cssClassPrefix ?? "ag-menu-option";
this.addAriaAttributes();
this.addIcon();
this.addName();
this.addShortcut();
this.addSubMenu();
}
configureDefaults() {
return true;
}
addAriaAttributes() {
const { checked, subMenu } = this.params;
const eGui = this.getGui();
if (checked) {
(0, import_ag_grid_community51._setAriaChecked)(eGui, checked);
}
if (subMenu) {
(0, import_ag_grid_community51._setAriaExpanded)(eGui, false);
}
}
addIcon() {
if (this.params.isCompact) {
return;
}
const iconWrapper = (0, import_ag_grid_community51._createElement)({
tag: "span",
ref: "eIcon",
cls: `${this.getClassName("part")} ${this.getClassName("icon")}`,
role: "presentation"
});
const { checked, icon } = this.params;
if (checked) {
iconWrapper.appendChild((0, import_ag_grid_community51._createIconNoSpan)("check", this.beans));
} else if (icon) {
if ((0, import_ag_grid_community51._isNodeOrElement)(icon)) {
iconWrapper.appendChild(icon);
} else if (typeof icon === "string") {
iconWrapper.innerHTML = icon;
} else {
(0, import_ag_grid_community51._warn)(227);
}
}
this.getGui().appendChild(iconWrapper);
}
addName() {
const name = (0, import_ag_grid_community51._createElement)({
tag: "span",
ref: "eName",
cls: `${this.getClassName("part")} ${this.getClassName("text")}`,
children: this.params.name || ""
});
this.getGui().appendChild(name);
}
addShortcut() {
if (this.params.isCompact) {
return;
}
const shortcut = (0, import_ag_grid_community51._createElement)({
tag: "span",
ref: "eShortcut",
cls: `${this.getClassName("part")} ${this.getClassName("shortcut")}`,
children: this.params.shortcut || ""
});
this.getGui().appendChild(shortcut);
}
addSubMenu() {
const pointer = (0, import_ag_grid_community51._createElement)({
tag: "span",
ref: "ePopupPointer",
cls: `${this.getClassName("part")} ${this.getClassName("popup-pointer")}`
});
const eGui = this.getGui();
if (this.params.subMenu) {
const iconName = this.gos.get("enableRtl") ? "subMenuOpenRtl" : "subMenuOpen";
pointer.appendChild((0, import_ag_grid_community51._createIconNoSpan)(iconName, this.beans));
}
eGui.appendChild(pointer);
}
getClassName(suffix) {
return `${this.cssClassPrefix}-${suffix}`;
}
};
// packages/ag-grid-enterprise/src/widgets/menu.css-GENERATED.ts
var menuCSS = (
/*css*/
`.ag-menu-list{cursor:default;display:table;padding:var(--ag-spacing) 0;width:100%}.ag-menu-option,.ag-menu-separator{display:table-row}.ag-menu-option-part,.ag-menu-separator-part{display:table-cell;vertical-align:middle}.ag-menu-option{cursor:pointer;font-weight:500}:where(.ag-ltr) :where(.ag-menu-option-popup-pointer) .ag-icon{text-align:right}:where(.ag-rtl) :where(.ag-menu-option-popup-pointer) .ag-icon{text-align:left}.ag-menu-option-text{white-space:nowrap}.ag-menu-option-custom{display:contents}.ag-compact-menu-option{display:flex;flex-wrap:nowrap;width:100%}.ag-compact-menu-option-text{flex:1 1 auto;white-space:nowrap}.ag-menu-separator{height:calc(var(--ag-spacing)*2 + 1px)}.ag-menu-separator-part:after{border-top:solid var(--ag-border-width) var(--ag-menu-separator-color);content:"";display:block}.ag-compact-menu-option-active,.ag-menu-option-active{background-color:var(--ag-row-hover-color)}.ag-compact-menu-option-part,.ag-menu-option-part{line-height:var(--ag-icon-size);padding:calc(var(--ag-spacing) + 2px) 0}.ag-compact-menu-option-disabled,.ag-menu-option-disabled{cursor:not-allowed;opacity:.5}.ag-compact-menu-option-icon,.ag-menu-option-icon{width:var(--ag-icon-size)}:where(.ag-ltr) .ag-compact-menu-option-icon,:where(.ag-ltr) .ag-menu-option-icon{padding-left:calc(var(--ag-spacing)*2)}:where(.ag-rtl) .ag-compact-menu-option-icon,:where(.ag-rtl) .ag-menu-option-icon{padding-right:calc(var(--ag-spacing)*2)}.ag-compact-menu-option-text,.ag-menu-option-text{padding-left:calc(var(--ag-spacing)*2);padding-right:calc(var(--ag-spacing)*2)}:where(.ag-ltr) .ag-compact-menu-option-shortcut,:where(.ag-ltr) .ag-menu-option-shortcut{padding-right:var(--ag-spacing)}:where(.ag-rtl) .ag-compact-menu-option-shortcut,:where(.ag-rtl) .ag-menu-option-shortcut{padding-left:var(--ag-spacing)}:where(.ag-ltr) .ag-compact-menu-option-popup-pointer,:where(.ag-ltr) .ag-menu-option-popup-pointer{padding-right:var(--ag-spacing)}:where(.ag-rtl) .ag-compact-menu-option-popup-pointer,:where(.ag-rtl) .ag-menu-option-popup-pointer{padding-left:var(--ag-spacing)}.ag-menu-column-select-wrapper{height:265px;overflow:auto;:where(.ag-column-select){height:100%}}.ag-menu:where(.ag-tabs){min-width:290px}.ag-context-menu-loading-icon{pointer-events:none;position:absolute}`
);
// packages/ag-grid-enterprise/src/widgets/menuItemModule.ts
var MenuItemModule = {
moduleName: "MenuItem",
version: VERSION,
userComponents: {
agMenuItem: AgMenuItemRenderer
},
icons: {
// indicates the currently active pin state in the "Pin column" sub-menu of the column menu
check: "tick",
// icon for sub menu item
subMenuOpen: "small-right",
// version of subMenuOpen used in RTL mode
subMenuOpenRtl: "small-left"
},
css: [menuCSS]
};
// packages/ag-grid-enterprise/src/columnToolPanel/columnToolPanel.ts
var import_ag_grid_community67 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/columnToolPanel/agPrimaryCols.ts
var import_ag_grid_community66 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/columnToolPanel/agPrimaryCols.css-GENERATED.ts
var agPrimaryColsCSS = (
/*css*/
`.ag-column-select{display:flex;flex:3 1 0px;flex-direction:column;overflow:hidden;position:relative}.ag-column-select-header{align-items:center;display:flex;flex:none;gap:var(--ag-widget-horizontal-spacing);height:var(--ag-header-height);padding-left:var(--ag-widget-container-horizontal-padding);padding-right:var(--ag-widget-container-horizontal-padding);position:relative}.ag-column-select-column,.ag-column-select-column-group{align-items:center;display:flex;gap:var(--ag-widget-horizontal-spacing);height:100%;position:relative;&:where(:not(:last-child)){margin-bottom:var(--ag-widget-vertical-spacing)}}:where(.ag-ltr) .ag-column-select-column,:where(.ag-ltr) .ag-column-select-column-group{padding-left:calc(var(--ag-indentation-level)*var(--ag-column-select-indent-size))}:where(.ag-rtl) .ag-column-select-column,:where(.ag-rtl) .ag-column-select-column-group{padding-right:calc(var(--ag-indentation-level)*var(--ag-column-select-indent-size))}.ag-column-select-header-icon{border-radius:var(--ag-border-radius);cursor:pointer;height:var(--ag-icon-size);position:relative;width:var(--ag-icon-size);&:focus-visible{box-shadow:var(--ag-focus-shadow)}}.ag-column-select-header-filter-wrapper{flex:1 1 auto}.ag-column-select-header-filter{width:100%}.ag-column-select-list{flex:1 1 0px;overflow:hidden}:where(.ag-ltr) .ag-column-select-add-group-indent{margin-left:calc(var(--ag-icon-size) + var(--ag-spacing)*1.5)}:where(.ag-rtl) .ag-column-select-add-group-indent{margin-right:calc(var(--ag-icon-size) + var(--ag-spacing)*1.5)}.ag-column-select-column-group-readonly,.ag-column-select-column-readonly{opacity:.5;pointer-events:none}.ag-column-select-virtual-list-viewport{padding:calc(var(--ag-widget-container-vertical-padding)*.5) 0}.ag-column-select-virtual-list-item{padding:0 var(--ag-widget-container-horizontal-padding)}.ag-column-select-column-label{flex:1 1 auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ag-column-select-checkbox{display:flex}`
);
// packages/ag-grid-enterprise/src/columnToolPanel/agPrimaryColsHeader.ts
var import_ag_grid_community52 = require("ag-grid-community");
var DEBOUNCE_DELAY = 300;
var AgPrimaryColsHeaderElement = {
tag: "div",
cls: "ag-column-select-header",
role: "presentation",
children: [
{ tag: "div", ref: "eExpand", cls: "ag-column-select-header-icon" },
{ tag: "ag-checkbox", ref: "eSelect", cls: "ag-column-select-header-checkbox" },
{ tag: "ag-input-text-field", ref: "eFilterTextField", cls: "ag-column-select-header-filter-wrapper" }
]
};
var AgPrimaryColsHeader = class extends import_ag_grid_community52.Component {
constructor() {
super(AgPrimaryColsHeaderElement, [import_ag_grid_community52.AgCheckboxSelector, import_ag_grid_community52.AgInputTextFieldSelector]);
this.eExpand = import_ag_grid_community52.RefPlaceholder;
this.eSelect = import_ag_grid_community52.RefPlaceholder;
this.eFilterTextField = import_ag_grid_community52.RefPlaceholder;
}
postConstruct() {
this.createExpandIcons();
this.addManagedListeners(this.eExpand, {
click: this.onExpandClicked.bind(this),
keydown: (e) => {
if (e.key === import_ag_grid_community52.KeyCode.SPACE) {
e.preventDefault();
this.onExpandClicked();
}
}
});
this.addManagedElementListeners(this.eSelect.getInputElement(), { click: this.onSelectClicked.bind(this) });
this.addManagedPropertyListener("functionsReadOnly", () => this.onFunctionsReadOnlyPropChanged());
this.eFilterTextField.setAutoComplete(false).onValueChange(() => this.onFilterTextChanged());
this.addManagedEventListeners({ newColumnsLoaded: this.showOrHideOptions.bind(this) });
const translate = this.getLocaleTextFunc();
this.eSelect.setInputAriaLabel(translate("ariaColumnSelectAll", "Toggle All Columns Visibility"));
this.eFilterTextField.setInputAriaLabel(translate("ariaFilterColumnsInput", "Filter Columns Input"));
this.activateTabIndex([this.eExpand]);
}
onFunctionsReadOnlyPropChanged() {
const readOnly = this.gos.get("functionsReadOnly");
this.eSelect.setReadOnly(readOnly);
this.eSelect.toggleCss("ag-column-select-column-readonly", readOnly);
}
init(params) {
this.params = params;
const readOnly = this.gos.get("functionsReadOnly");
this.eSelect.setReadOnly(readOnly);
this.eSelect.toggleCss("ag-column-select-column-readonly", readOnly);
if (this.beans.colModel.ready) {
this.showOrHideOptions();
}
}
createExpandIcons() {
const beans = this.beans;
this.eExpand.appendChild(this.eExpandChecked = (0, import_ag_grid_community52._createIconNoSpan)("columnSelectOpen", beans));
this.eExpand.appendChild(this.eExpandUnchecked = (0, import_ag_grid_community52._createIconNoSpan)("columnSelectClosed", beans));
this.eExpand.appendChild(this.eExpandIndeterminate = (0, import_ag_grid_community52._createIconNoSpan)("columnSelectIndeterminate", beans));
this.setExpandState(0 /* EXPANDED */);
}
// we only show expand / collapse if we are showing columns
showOrHideOptions() {
const params = this.params;
const showFilter = !params.suppressColumnFilter;
const showSelect = !params.suppressColumnSelectAll;
const showExpand = !params.suppressColumnExpandAll;
const groupsPresent = !!this.beans.colModel.colDefCols?.treeDepth;
const translate = this.getLocaleTextFunc();
this.eFilterTextField.setInputPlaceholder(translate("searchOoo", "Search..."));
(0, import_ag_grid_community52._setDisplayed)(this.eFilterTextField.getGui(), showFilter);
(0, import_ag_grid_community52._setDisplayed)(this.eSelect.getGui(), showSelect);
(0, import_ag_grid_community52._setDisplayed)(this.eExpand, showExpand && groupsPresent);
}
onFilterTextChanged() {
if (!this.onFilterTextChangedDebounced) {
this.onFilterTextChangedDebounced = (0, import_ag_grid_community52._debounce)(
this,
() => {
const filterText = this.eFilterTextField.getValue();
this.dispatchLocalEvent({ type: "filterChanged", filterText });
},
DEBOUNCE_DELAY
);
}
this.onFilterTextChangedDebounced();
}
onSelectClicked() {
this.dispatchLocalEvent({ type: this.selectState ? "unselectAll" : "selectAll" });
}
onExpandClicked() {
this.dispatchLocalEvent({ type: this.expandState === 0 /* EXPANDED */ ? "collapseAll" : "expandAll" });
}
setExpandState(state) {
this.expandState = state;
(0, import_ag_grid_community52._setDisplayed)(this.eExpandChecked, state === 0 /* EXPANDED */);
(0, import_ag_grid_community52._setDisplayed)(this.eExpandUnchecked, state === 1 /* COLLAPSED */);
(0, import_ag_grid_community52._setDisplayed)(this.eExpandIndeterminate, state === 2 /* INDETERMINATE */);
}
setSelectionState(state) {
this.selectState = state;
this.eSelect.setValue(this.selectState);
}
};
var AgPrimaryColsHeaderSelector = {
selector: "AG-PRIMARY-COLS-HEADER",
component: AgPrimaryColsHeader
};
// packages/ag-grid-enterprise/src/columnToolPanel/agPrimaryColsList.ts
var import_ag_grid_community64 = require("ag-grid-community");
var import_ag_grid_community65 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/sideBar/common/toolPanelColDefService.ts
var import_ag_grid_community54 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/sideBar/common/sideBarUtils.ts
var import_ag_grid_community53 = require("ag-grid-community");
function isColGroupDef(colDef) {
return !!colDef && typeof colDef.children !== "undefined";
}
function getId(colDef) {
return isColGroupDef(colDef) ? colDef.groupId : colDef.colId;
}
function addChildrenToGroup(tree, groupId, colDef) {
const subGroupIsSplit = (currentSubGroup, currentSubGroupToAdd) => {
const existingChildIds = currentSubGroup.children.map(getId);
const childGroupAlreadyExists = existingChildIds.includes(getId(currentSubGroupToAdd));
const lastChild = (0, import_ag_grid_community53._last)(currentSubGroup.children);
const lastChildIsDifferent = lastChild && getId(lastChild) !== getId(currentSubGroupToAdd);
return childGroupAlreadyExists && lastChildIsDifferent;
};
if (!isColGroupDef(tree)) {
return true;
}
const currentGroup = tree;
const groupToAdd = colDef;
if (subGroupIsSplit(currentGroup, groupToAdd)) {
currentGroup.children.push(groupToAdd);
return true;
}
if (currentGroup.groupId === groupId) {
const existingChildIds = currentGroup.children.map(getId);
const colDefAlreadyPresent = existingChildIds.includes(getId(groupToAdd));
if (!colDefAlreadyPresent) {
currentGroup.children.push(groupToAdd);
return true;
}
}
for (let i = currentGroup.children.length - 1; i >= 0; i--) {
if (addChildrenToGroup(currentGroup.children[i], groupId, colDef)) {
break;
}
}
return false;
}
function mergeLeafPathTrees(leafPathTrees) {
const matchingRootGroupIds = (pathA, pathB) => {
const bothPathsAreGroups = isColGroupDef(pathA) && isColGroupDef(pathB);
return bothPathsAreGroups && getId(pathA) === getId(pathB);
};
const mergeTrees = (treeA, treeB) => {
if (!isColGroupDef(treeB)) {
return treeA;
}
const mergeResult = treeA;
const groupToMerge = treeB;
if (groupToMerge.children && groupToMerge.groupId) {
const added = addChildrenToGroup(mergeResult, groupToMerge.groupId, groupToMerge.children[0]);
if (added) {
return mergeResult;
}
}
groupToMerge.children.forEach((child) => mergeTrees(mergeResult, child));
return mergeResult;
};
const mergeColDefs = [];
for (let i = 1; i <= leafPathTrees.length; i++) {
const first = leafPathTrees[i - 1];
const second = leafPathTrees[i];
if (matchingRootGroupIds(first, second)) {
leafPathTrees[i] = mergeTrees(first, second);
} else {
mergeColDefs.push(first);
}
}
return mergeColDefs;
}
// packages/ag-grid-enterprise/src/sideBar/common/toolPanelColDefService.ts
function toolPanelCreateColumnTree(colModel, colDefs) {
const invalidColIds = [];
const createDummyColGroup = (abstractColDef, depth) => {
if (isColGroupDef(abstractColDef)) {
const groupDef = abstractColDef;
const groupId = typeof groupDef.groupId !== "undefined" ? groupDef.groupId : groupDef.headerName;
const group = new import_ag_grid_community54.AgProvidedColumnGroup(groupDef, groupId, false, depth);
const children = [];
groupDef.children.forEach((def) => {
const child = createDummyColGroup(def, depth + 1);
if (child) {
children.push(child);
}
});
group.setChildren(children);
return group;
} else {
const colDef = abstractColDef;
const key = colDef.colId ? colDef.colId : colDef.field;
const column = colModel.getColDefCol(key);
if (!column) {
invalidColIds.push(colDef);
}
return column;
}
};
const mappedResults = [];
colDefs.forEach((colDef) => {
const result = createDummyColGroup(colDef, 0);
if (result) {
mappedResults.push(result);
}
});
if (invalidColIds.length > 0) {
(0, import_ag_grid_community54._warn)(217, { invalidColIds });
}
return mappedResults;
}
function syncLayoutWithGrid(colModel, syncLayoutCallback) {
const leafPathTrees = getLeafPathTrees(colModel);
const mergedColumnTrees = mergeLeafPathTrees(leafPathTrees);
syncLayoutCallback(mergedColumnTrees);
}
function getLeafPathTrees(colModel) {
const getLeafPathTree = (node, childDef) => {
let leafPathTree;
if ((0, import_ag_grid_community54.isProvidedColumnGroup)(node)) {
if (node.isPadding()) {
leafPathTree = childDef;
} else {
const groupDef = Object.assign({}, node.getColGroupDef());
groupDef.groupId = node.getGroupId();
groupDef.children = [childDef];
leafPathTree = groupDef;
}
} else {
const colDef = Object.assign({}, node.getColDef());
colDef.colId = node.getColId();
leafPathTree = colDef;
}
const parent = node.getOriginalParent();
if (parent) {
return getLeafPathTree(parent, leafPathTree);
} else {
return leafPathTree;
}
};
const allGridColumns = colModel.getCols();
const allPrimaryGridColumns = allGridColumns.filter((column) => {
const colDef = column.getColDef();
return column.isPrimary() && !colDef.showRowGroup;
});
return allPrimaryGridColumns.map((col) => getLeafPathTree(col, col.getColDef()));
}
// packages/ag-grid-enterprise/src/columnToolPanel/columnModelItem.ts
var import_ag_grid_community55 = require("ag-grid-community");
var ColumnModelItem = class {
constructor(displayName, columnOrGroup, depth, group = false, expanded) {
this.displayName = displayName;
this.depth = depth;
this.group = group;
this.localEventService = new import_ag_grid_community55.LocalEventService();
if (group) {
this.columnGroup = columnOrGroup;
this._expanded = expanded;
this.children = [];
} else {
this.column = columnOrGroup;
}
}
get expanded() {
return !!this._expanded;
}
set expanded(expanded) {
if (expanded === this._expanded) {
return;
}
this._expanded = expanded;
this.localEventService.dispatchEvent({ type: "expandedChanged" });
}
addEventListener(eventType, listener) {
this.localEventService.addEventListener(eventType, listener);
}
removeEventListener(eventType, listener) {
this.localEventService.removeEventListener(eventType, listener);
}
};
// packages/ag-grid-enterprise/src/columnToolPanel/columnMoveUtils.ts
var import_ag_grid_community62 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/columnToolPanel/toolPanelColumnGroupComp.ts
var import_ag_grid_community61 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/columnToolPanel/modelItemUtils.ts
var import_ag_grid_community56 = require("ag-grid-community");
function selectAllChildren(beans, colTree, selectAllChecked, eventType) {
const cols = extractAllLeafColumns(colTree);
setAllColumns(beans, cols, selectAllChecked, eventType);
}
function setAllColumns(beans, cols, selectAllChecked, eventType) {
if (beans.colModel.isPivotMode()) {
setAllPivot(beans, cols, selectAllChecked, eventType);
} else {
setAllVisible(beans, cols, selectAllChecked, eventType);
}
}
function extractAllLeafColumns(allItems) {
const res = [];
const recursiveFunc = (items) => {
items.forEach((item) => {
if (!item.passesFilter) {
return;
}
if (item.group) {
recursiveFunc(item.children);
} else {
res.push(item.column);
}
});
};
recursiveFunc(allItems);
return res;
}
function setAllVisible(beans, columns, visible, eventType) {
const colStateItems = [];
columns.forEach((col) => {
if (col.getColDef().lockVisible) {
return;
}
if (col.isVisible() != visible) {
colStateItems.push({
colId: col.getId(),
hide: !visible
});
}
});
if (colStateItems.length > 0) {
(0, import_ag_grid_community56._applyColumnState)(beans, { state: colStateItems }, eventType);
}
}
function setAllPivot(beans, columns, value, eventType) {
setAllPivotActive(beans, columns, value, eventType);
}
function setAllPivotActive(beans, columns, value, eventType) {
const colStateItems = [];
const turnOnAction = (col) => {
if (col.isAnyFunctionActive()) {
return;
}
if (col.isAllowValue()) {
const aggFunc = typeof col.getAggFunc() === "string" ? col.getAggFunc() : beans.aggFuncSvc?.getDefaultAggFunc(col);
colStateItems.push({
colId: col.getId(),
aggFunc
});
} else if (col.isAllowRowGroup()) {
colStateItems.push({
colId: col.getId(),
rowGroup: true
});
} else if (col.isAllowPivot()) {
colStateItems.push({
colId: col.getId(),
pivot: true
});
}
};
const turnOffAction = (col) => {
const isActive = col.isPivotActive() || col.isRowGroupActive() || col.isValueActive();
if (isActive) {
colStateItems.push({
colId: col.getId(),
pivot: false,
rowGroup: false,
aggFunc: null
});
}
};
const action = value ? turnOnAction : turnOffAction;
columns.forEach(action);
if (colStateItems.length > 0) {
(0, import_ag_grid_community56._applyColumnState)(beans, { state: colStateItems }, eventType);
}
}
function updateColumns(beans, params) {
const { columns, visibleState, pivotState, eventType } = params;
const state = columns.map((column) => {
const colId = column.getColId();
if (beans.colModel.isPivotMode()) {
const pivotStateForColumn = pivotState?.[colId];
return {
colId,
pivot: pivotStateForColumn?.pivot,
rowGroup: pivotStateForColumn?.rowGroup,
aggFunc: pivotStateForColumn?.aggFunc
};
} else {
return {
colId,
hide: !visibleState?.[colId]
};
}
});
(0, import_ag_grid_community56._applyColumnState)(beans, { state }, eventType);
}
function createPivotState(column) {
return {
pivot: column.isPivotActive(),
rowGroup: column.isRowGroupActive(),
aggFunc: column.isValueActive() ? column.getAggFunc() : void 0
};
}
// packages/ag-grid-enterprise/src/columnToolPanel/toolPanelContextMenu.ts
var import_ag_grid_community60 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowGrouping/rowGroupingUtils.ts
function setRowNodeGroupValue(rowNode, colModel, colKey, newValue) {
const column = colModel.getCol(colKey);
if (!rowNode.groupData) {
rowNode.groupData = {};
}
const columnId = column.getColId();
const oldValue = rowNode.groupData[columnId];
if (oldValue === newValue) {
return;
}
rowNode.groupData[columnId] = newValue;
rowNode.dispatchCellChangedEvent(column, newValue, oldValue);
}
function setRowNodeGroup(rowNode, beans, group) {
if (rowNode.group === group) {
return;
}
if (rowNode.group && !group) {
rowNode.expanded = false;
}
rowNode.group = group;
rowNode.updateHasChildren();
beans.selectionSvc?.updateRowSelectable(rowNode);
rowNode.dispatchRowEvent("groupChanged");
}
function isRowGroupColLocked(column, beans) {
const { gos, rowGroupColsSvc } = beans;
if (!rowGroupColsSvc || !column) {
return false;
}
const groupLockGroupColumns = gos.get("groupLockGroupColumns");
if (!column.isRowGroupActive() || groupLockGroupColumns === 0) {
return false;
}
if (groupLockGroupColumns === -1) {
return true;
}
const colIndex = rowGroupColsSvc.columns.findIndex((groupCol) => groupCol.getColId() === column.getColId());
return groupLockGroupColumns > colIndex;
}
// packages/ag-grid-enterprise/src/widgets/agMenuList.ts
var import_ag_grid_community59 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/agMenuItemComponent.ts
var import_ag_grid_community58 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/agMenuPanel.ts
var import_ag_grid_community57 = require("ag-grid-community");
var AgMenuPanel = class extends import_ag_grid_community57.TabGuardComp {
constructor(wrappedComponent) {
super();
this.setTemplateFromElement(wrappedComponent.getGui(), void 0, void 0, true);
}
postConstruct() {
this.initialiseTabGuard({
onTabKeyDown: (e) => this.onTabKeyDown(e),
handleKeyDown: (e) => this.handleKeyDown(e)
});
}
handleKeyDown(e) {
if (e.key === import_ag_grid_community57.KeyCode.ESCAPE) {
this.closePanel();
}
}
onTabKeyDown(e) {
if (e.defaultPrevented) {
return;
}
this.closePanel();
e.preventDefault();
}
closePanel() {
const menuItem = this.parentComponent;
menuItem.closeSubMenu();
setTimeout(() => menuItem.getGui().focus(), 0);
}
};
// packages/ag-grid-enterprise/src/widgets/agMenuItemComponent.ts
function getMenuItemCompDetails(userCompFactory, def, params) {
return userCompFactory.getCompDetails(def, MenuItemComponent, "agMenuItem", params, true);
}
var MenuItemComponent = {
name: "menuItem",
optionalMethods: ["setActive", "select", "setExpanded", "configureDefaults"]
};
var MenuItemElement2 = { tag: "div", cls: "ag-menu", role: "presentation" };
var AgMenuItemComponent = class extends import_ag_grid_community58.BeanStub {
constructor() {
super(...arguments);
this.ACTIVATION_DELAY = 80;
this.isActive = false;
this.subMenuIsOpen = false;
this.subMenuIsOpening = false;
this.suppressRootStyles = true;
this.suppressAria = true;
this.suppressFocus = true;
}
wireBeans(beans) {
this.popupSvc = beans.popupSvc;
this.userCompFactory = beans.userCompFactory;
this.registry = beans.registry;
}
init(params) {
const { menuItemDef, isAnotherSubMenuOpen, level, childComponent, contextParams } = params;
this.params = params.menuItemDef;
this.level = level;
this.isAnotherSubMenuOpen = isAnotherSubMenuOpen;
this.childComponent = childComponent;
this.contextParams = contextParams;
this.cssClassPrefix = this.params.menuItemParams?.cssClassPrefix ?? "ag-menu-option";
const compDetails = getMenuItemCompDetails(
this.userCompFactory,
this.params,
(0, import_ag_grid_community58._addGridCommonParams)(this.gos, {
...menuItemDef,
level,
isAnotherSubMenuOpen,
openSubMenu: (activateFirstItem) => this.openSubMenu(activateFirstItem),
closeSubMenu: () => this.closeSubMenu(),
closeMenu: (event) => this.closeMenu(event),
updateTooltip: (tooltip, shouldDisplayTooltip) => this.refreshTooltip(tooltip, shouldDisplayTooltip),
onItemActivated: () => this.onItemActivated()
})
);
return compDetails?.newAgStackInstance().then((comp) => {
this.menuItemComp = comp;
const configureDefaults = comp.configureDefaults?.();
if (configureDefaults) {
this.configureDefaults(configureDefaults === true ? void 0 : configureDefaults);
}
}) ?? import_ag_grid_community58.AgPromise.resolve();
}
addListeners(eGui, params) {
if (!params?.suppressClick) {
this.addManagedElementListeners(eGui, { click: (e) => this.onItemSelected(e) });
}
if (!params?.suppressKeyboardSelect) {
this.addManagedElementListeners(eGui, {
keydown: (e) => {
if (e.key === import_ag_grid_community58.KeyCode.ENTER || e.key === import_ag_grid_community58.KeyCode.SPACE) {
e.preventDefault();
this.onItemSelected(e);
}
}
});
}
if (!params?.suppressMouseDown) {
this.addManagedElementListeners(eGui, {
mousedown: (e) => {
e.stopPropagation();
e.preventDefault();
}
});
}
if (!params?.suppressMouseOver) {
this.addManagedElementListeners(eGui, {
mouseenter: () => this.onMouseEnter(),
mouseleave: () => this.onMouseLeave()
});
}
}
isDisabled() {
return !!this.params.disabled;
}
openSubMenu(activateFirstItem = false, event) {
this.closeSubMenu();
if (!this.params.subMenu) {
return;
}
this.subMenuIsOpening = true;
const ePopup = (0, import_ag_grid_community58._createElement)(MenuItemElement2);
this.eSubMenuGui = ePopup;
let destroySubMenu;
let afterGuiAttached = () => {
this.subMenuIsOpening = false;
};
if (this.childComponent) {
const menuPanel = this.createBean(new AgMenuPanel(this.childComponent));
menuPanel.setParentComponent(this);
const subMenuGui = menuPanel.getGui();
const mouseEvent = "mouseenter";
const mouseEnterListener = () => this.cancelDeactivate();
subMenuGui.addEventListener(mouseEvent, mouseEnterListener);
destroySubMenu = () => {
subMenuGui.removeEventListener(mouseEvent, mouseEnterListener);
this.destroyBean(menuPanel);
};
ePopup.appendChild(subMenuGui);
if (this.childComponent.afterGuiAttached) {
afterGuiAttached = () => {
this.childComponent.afterGuiAttached();
this.subMenuIsOpening = false;
};
}
} else if (this.params.subMenu) {
const childMenu = this.createBean(new AgMenuList(this.level + 1, this.contextParams));
childMenu.setParentComponent(this);
childMenu.addMenuItems(this.params.subMenu);
ePopup.appendChild(childMenu.getGui());
this.addManagedListeners(childMenu, { closeMenu: (e) => this.dispatchLocalEvent(e) });
childMenu.addGuiEventListener("mouseenter", () => this.cancelDeactivate());
destroySubMenu = () => this.destroyBean(childMenu);
if (activateFirstItem) {
afterGuiAttached = () => {
childMenu.activateFirstItem();
this.subMenuIsOpening = false;
};
}
}
const { popupSvc } = this;
const positionCallback = () => {
const eventSource = this.eGui;
const { column, node } = this.contextParams;
popupSvc?.positionPopupForMenu({
eventSource,
ePopup,
event: event instanceof MouseEvent ? event : void 0,
column,
node
});
};
const translate = this.getLocaleTextFunc();
const addPopupRes = popupSvc?.addPopup({
modal: true,
eChild: ePopup,
positionCallback,
anchorToElement: this.eGui,
ariaLabel: translate("ariaLabelSubMenu", "SubMenu"),
afterGuiAttached
});
this.subMenuIsOpen = true;
this.setAriaExpanded(true);
this.hideSubMenu = () => {
if (addPopupRes) {
addPopupRes.hideFunc();
}
this.subMenuIsOpen = false;
this.setAriaExpanded(false);
destroySubMenu();
this.menuItemComp.setExpanded?.(false);
this.eSubMenuGui = void 0;
};
this.menuItemComp.setExpanded?.(true);
}
setAriaExpanded(expanded) {
if (!this.suppressAria) {
(0, import_ag_grid_community58._setAriaExpanded)(this.eGui, expanded);
}
}
closeSubMenu() {
if (!this.hideSubMenu) {
return;
}
this.hideSubMenu();
this.hideSubMenu = null;
this.setAriaExpanded(false);
}
isSubMenuOpen() {
return this.subMenuIsOpen;
}
isSubMenuOpening() {
return this.subMenuIsOpening;
}
activate(openSubMenu, fromKeyNav) {
this.cancelActivate();
if (this.params.disabled && !fromKeyNav) {
return;
}
this.isActive = true;
if (!this.suppressRootStyles) {
this.eGui.classList.add(`${this.cssClassPrefix}-active`);
}
this.menuItemComp.setActive?.(true);
if (!this.suppressFocus) {
(0, import_ag_grid_community58._preserveRangesWhile)(this.beans, () => this.eGui.focus({ preventScroll: !fromKeyNav }));
}
if (openSubMenu && this.params.subMenu) {
window.setTimeout(() => {
if (this.isAlive() && this.isActive) {
this.openSubMenu();
}
}, 300);
}
this.onItemActivated();
}
deactivate() {
this.cancelDeactivate();
if (!this.suppressRootStyles) {
this.eGui.classList.remove(`${this.cssClassPrefix}-active`);
}
this.menuItemComp.setActive?.(false);
this.isActive = false;
if (this.subMenuIsOpen) {
this.closeSubMenu();
}
}
getGui() {
return this.menuItemComp.getGui();
}
getParentComponent() {
return this.parentComponent;
}
setParentComponent(component) {
this.parentComponent = component;
}
getSubMenuGui() {
return this.eSubMenuGui;
}
onItemSelected(event) {
this.menuItemComp.select?.();
if (this.params.action) {
this.beans.frameworkOverrides.wrapOutgoing(
() => this.params.action(
(0, import_ag_grid_community58._addGridCommonParams)(this.gos, {
...this.contextParams
})
)
);
} else {
this.openSubMenu(event && event.type === "keydown", event);
}
if (this.params.subMenu && !this.params.action || this.params.suppressCloseOnSelect) {
return;
}
this.closeMenu(event);
}
closeMenu(event) {
const e = {
type: "closeMenu"
};
if (event) {
if (event instanceof MouseEvent) {
e.mouseEvent = event;
} else {
e.keyboardEvent = event;
}
}
this.dispatchLocalEvent(e);
}
onItemActivated() {
const event = {
type: "menuItemActivated",
menuItem: this
};
this.dispatchLocalEvent(event);
}
cancelActivate() {
if (this.activateTimeoutId) {
window.clearTimeout(this.activateTimeoutId);
this.activateTimeoutId = 0;
}
}
cancelDeactivate() {
if (this.deactivateTimeoutId) {
window.clearTimeout(this.deactivateTimeoutId);
this.deactivateTimeoutId = 0;
}
}
onMouseEnter() {
this.cancelDeactivate();
if (this.isAnotherSubMenuOpen()) {
this.activateTimeoutId = window.setTimeout(() => this.activate(true), this.ACTIVATION_DELAY);
} else {
this.activate(true);
}
}
onMouseLeave() {
this.cancelActivate();
if (this.isSubMenuOpen()) {
this.deactivateTimeoutId = window.setTimeout(() => this.deactivate(), this.ACTIVATION_DELAY);
} else {
this.deactivate();
}
}
refreshRootElementGui(suppressRootStyles) {
let eGui = this.menuItemComp.getGui();
const {
cssClassPrefix,
params: { cssClasses, disabled }
} = this;
const rootElement = this.menuItemComp.getRootElement?.();
if (rootElement) {
if (!suppressRootStyles) {
eGui.classList.add("ag-menu-option-custom");
}
eGui = rootElement;
}
this.suppressRootStyles = !!suppressRootStyles;
if (!this.suppressRootStyles) {
eGui.classList.add(cssClassPrefix);
cssClasses?.forEach((it) => eGui.classList.add(it));
if (disabled) {
eGui.classList.add(`${cssClassPrefix}-disabled`);
}
}
return eGui;
}
applyAriaProperties(eGui) {
const {
params: { checked, subMenu, subMenuRole, disabled }
} = this;
const hasCheck = checked != null;
(0, import_ag_grid_community58._setAriaRole)(eGui, hasCheck ? "menuitemcheckbox" : "menuitem");
if (subMenu) {
(0, import_ag_grid_community58._setAriaHasPopup)(eGui, subMenuRole ?? "menu");
}
if (disabled) {
(0, import_ag_grid_community58._setAriaDisabled)(eGui, true);
}
}
configureDefaults(configParams) {
if (!this.menuItemComp) {
setTimeout(() => this.configureDefaults(configParams));
return;
}
const { suppressRootStyles, suppressTooltip, suppressAria, suppressTabIndex, suppressFocus } = configParams || {};
const {
params: { tooltip, disabled }
} = this;
const eGui = this.eGui = this.refreshRootElementGui(!!suppressRootStyles);
this.suppressAria = !!suppressAria;
if (!suppressAria) {
this.applyAriaProperties(eGui);
}
if (!suppressTabIndex) {
eGui.setAttribute("tabindex", "-1");
}
if (!suppressTooltip) {
this.refreshTooltip(tooltip);
}
if (!disabled) {
this.addListeners(eGui, configParams);
}
this.suppressFocus = !!suppressFocus;
}
refreshTooltip(tooltip, shouldDisplayTooltip) {
this.tooltip = tooltip;
this.tooltipFeature = this.destroyBean(this.tooltipFeature);
if (!tooltip || !this.menuItemComp) {
return;
}
const tooltipFeature = this.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.getGui(),
getTooltipValue: () => this.tooltip,
getLocation: () => "menu",
shouldDisplayTooltip
});
if (tooltipFeature) {
this.tooltipFeature = this.createBean(tooltipFeature);
}
}
destroy() {
this.tooltipFeature = this.destroyBean(this.tooltipFeature);
this.menuItemComp?.destroy?.();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/widgets/agMenuList.ts
var AgMenuList = class extends import_ag_grid_community59.TabGuardComp {
constructor(level = 0, params) {
super({ tag: "div", cls: "ag-menu-list", role: "menu" });
this.level = level;
this.menuItems = [];
this.params = params ?? {
column: null,
node: null,
value: null
};
}
postConstruct() {
this.initialiseTabGuard({
onTabKeyDown: (e) => this.onTabKeyDown(e),
handleKeyDown: (e) => (0, import_ag_grid_community59._preserveRangesWhile)(this.beans, () => this.handleKeyDown(e)),
onFocusIn: (e) => this.handleFocusIn(e),
onFocusOut: (e) => this.handleFocusOut(e)
});
}
onTabKeyDown(e) {
const parent = this.getParentComponent();
const isManaged = parent?.getGui()?.classList.contains("ag-focus-managed");
if (!isManaged) {
e.preventDefault();
}
if (e.shiftKey) {
this.closeIfIsChild(e);
}
}
handleKeyDown(e) {
switch (e.key) {
case import_ag_grid_community59.KeyCode.UP:
case import_ag_grid_community59.KeyCode.RIGHT:
case import_ag_grid_community59.KeyCode.DOWN:
case import_ag_grid_community59.KeyCode.LEFT:
e.preventDefault();
this.handleNavKey(e.key);
break;
case import_ag_grid_community59.KeyCode.ESCAPE:
if (this.closeIfIsChild()) {
(0, import_ag_grid_community59._stopPropagationForAgGrid)(e);
}
break;
}
}
handleFocusIn(e) {
const oldFocusedElement = e.relatedTarget;
if (!this.tabGuardFeature.getTabGuardCtrl().isTabGuard(oldFocusedElement) && (this.getGui().contains(oldFocusedElement) || this.activeMenuItem?.getSubMenuGui()?.contains(oldFocusedElement))) {
return;
}
if (this.activeMenuItem) {
this.activeMenuItem.activate();
} else {
this.activateFirstItem();
}
}
handleFocusOut(e) {
const newFocusedElement = e.relatedTarget;
if (!this.activeMenuItem || this.getGui().contains(newFocusedElement) || this.activeMenuItem.getSubMenuGui()?.contains(newFocusedElement)) {
return;
}
if (!this.activeMenuItem.isSubMenuOpening()) {
this.activeMenuItem.deactivate();
}
}
clearActiveItem() {
if (this.activeMenuItem) {
this.activeMenuItem.deactivate();
this.activeMenuItem = null;
}
}
addMenuItems(menuItems) {
if (menuItems == null) {
return;
}
import_ag_grid_community59.AgPromise.all(
menuItems.map((menuItemOrString) => {
if (menuItemOrString === "separator") {
return import_ag_grid_community59.AgPromise.resolve({ eGui: this.createSeparator() });
} else if (typeof menuItemOrString === "string") {
(0, import_ag_grid_community59._warn)(228, { menuItemOrString });
return import_ag_grid_community59.AgPromise.resolve({ eGui: null });
} else {
return this.addItem(menuItemOrString);
}
})
).then((elements) => {
(elements ?? []).forEach((element) => {
if (element?.eGui) {
this.appendChild(element.eGui);
if (element.comp) {
this.menuItems.push(element.comp);
}
}
});
});
}
addItem(menuItemDef) {
const menuItem = this.createManagedBean(new AgMenuItemComponent());
return menuItem.init({
menuItemDef,
isAnotherSubMenuOpen: () => this.menuItems.some((m) => m.isSubMenuOpen()),
level: this.level,
contextParams: this.params
}).then(() => {
menuItem.setParentComponent(this);
this.addManagedListeners(menuItem, {
closeMenu: (event) => {
this.dispatchLocalEvent(event);
},
menuItemActivated: (event) => {
if (this.activeMenuItem && this.activeMenuItem !== event.menuItem) {
this.activeMenuItem.deactivate();
}
this.activeMenuItem = event.menuItem;
}
});
return {
comp: menuItem,
eGui: menuItem.getGui()
};
});
}
activateFirstItem() {
const item = this.menuItems.filter((currentItem) => !currentItem.isDisabled())[0];
if (!item) {
return;
}
item.activate();
}
createSeparator() {
const part = { tag: "div", cls: "ag-menu-separator-part" };
return (0, import_ag_grid_community59._createElement)({
tag: "div",
cls: "ag-menu-separator",
attrs: {
"aria-hidden": "true"
},
children: [part, part, part, part]
});
}
handleNavKey(key) {
switch (key) {
case import_ag_grid_community59.KeyCode.UP:
case import_ag_grid_community59.KeyCode.DOWN: {
const nextItem = this.findNextItem(key === import_ag_grid_community59.KeyCode.UP);
if (nextItem && nextItem !== this.activeMenuItem) {
nextItem.activate(false, true);
}
return;
}
}
const left = this.gos.get("enableRtl") ? import_ag_grid_community59.KeyCode.RIGHT : import_ag_grid_community59.KeyCode.LEFT;
if (key === left) {
this.closeIfIsChild();
} else {
this.openChild();
}
}
closeIfIsChild(e) {
const parentItem = this.getParentComponent();
if (parentItem && parentItem instanceof AgMenuItemComponent) {
if (e) {
e.preventDefault();
}
parentItem.closeSubMenu();
parentItem.getGui().focus();
return true;
}
return false;
}
openChild() {
if (this.activeMenuItem) {
this.activeMenuItem.openSubMenu(true);
}
}
findNextItem(up) {
const items = [...this.menuItems];
if (!items.length) {
return;
}
if (!this.activeMenuItem) {
return up ? (0, import_ag_grid_community59._last)(items) : items[0];
}
if (up) {
items.reverse();
}
let nextItem;
let foundCurrent = false;
for (const item of items) {
if (!foundCurrent) {
if (item === this.activeMenuItem) {
foundCurrent = true;
}
continue;
}
nextItem = item;
break;
}
if (foundCurrent && !nextItem) {
return items[0];
}
return nextItem || this.activeMenuItem;
}
destroy() {
this.clearActiveItem();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/columnToolPanel/toolPanelContextMenu.ts
var ToolPanelContextMenu = class extends import_ag_grid_community60.Component {
constructor(column, mouseEvent, parentEl) {
super({ tag: "div", cls: "ag-menu" });
this.column = column;
this.mouseEvent = mouseEvent;
this.parentEl = parentEl;
this.displayName = null;
}
postConstruct() {
const {
column,
beans: { colNames }
} = this;
this.initializeProperties(column);
let displayName;
if ((0, import_ag_grid_community60.isColumn)(column)) {
displayName = colNames.getDisplayNameForColumn(column, "columnToolPanel");
} else {
displayName = colNames.getDisplayNameForProvidedColumnGroup(null, column, "columnToolPanel");
}
this.displayName = displayName;
this.buildMenuItemMap();
if (this.isActive()) {
this.mouseEvent.preventDefault();
const menuItemsMapped = this.getMappedMenuItems();
if (menuItemsMapped.length === 0) {
return;
}
this.displayContextMenu(menuItemsMapped);
}
}
initializeProperties(column) {
let columns;
if ((0, import_ag_grid_community60.isProvidedColumnGroup)(column)) {
columns = column.getLeafColumns();
} else {
columns = [column];
}
this.columns = columns;
const isPivotMode2 = this.beans.colModel.isPivotMode();
this.allowScrollIntoView = !isPivotMode2 && columns.some(this.isColumnValidForScrollIntoView);
this.allowGrouping = columns.some((col) => col.isPrimary() && col.isAllowRowGroup());
this.allowValues = columns.some((col) => col.isPrimary() && col.isAllowValue());
this.allowPivoting = isPivotMode2 && columns.some((col) => col.isPrimary() && col.isAllowPivot());
}
buildMenuItemMap() {
const localeTextFunc = this.getLocaleTextFunc();
const { beans, displayName } = this;
const { rowGroupColsSvc, valueColsSvc, pivotColsSvc, colModel } = beans;
const menuItemMap = /* @__PURE__ */ new Map();
this.menuItemMap = menuItemMap;
const isPivotMode2 = colModel.isPivotMode();
menuItemMap.set("scrollIntoView", {
allowedFunction: (col) => !col.isPinned() && !isPivotMode2 && this.isColumnValidForScrollIntoView(col),
activeFunction: () => false,
activateLabel: () => localeTextFunc("scrollColumnIntoView", `Scroll ${displayName} into View`, [displayName]),
activateFunction: () => {
const firstVisibleColumn = this.columns.find(this.isColumnValidForScrollIntoView);
if (firstVisibleColumn) {
this.beans.ctrlsSvc.getScrollFeature().ensureColumnVisible(firstVisibleColumn);
}
},
deActivateFunction: () => {
},
addIcon: "ensureColumnVisible"
});
menuItemMap.set("rowGroup", {
allowedFunction: (col) => col.isPrimary() && col.isAllowRowGroup() && !isRowGroupColLocked(col, beans),
activeFunction: (col) => col.isRowGroupActive(),
activateLabel: () => `${localeTextFunc("groupBy", "Group by")} ${displayName}`,
deactivateLabel: () => `${localeTextFunc("ungroupBy", "Un-Group by")} ${displayName}`,
activateFunction: () => rowGroupColsSvc?.setColumns(this.addColumnsToList(rowGroupColsSvc.columns), "toolPanelUi"),
deActivateFunction: () => rowGroupColsSvc?.setColumns(this.removeColumnsFromList(rowGroupColsSvc.columns), "toolPanelUi"),
addIcon: "menuAddRowGroup",
removeIcon: "menuRemoveRowGroup"
});
menuItemMap.set("value", {
allowedFunction: (col) => col.isPrimary() && col.isAllowValue(),
activeFunction: (col) => col.isValueActive(),
activateLabel: () => localeTextFunc("addToValues", `Add ${displayName} to values`, [displayName]),
deactivateLabel: () => localeTextFunc("removeFromValues", `Remove ${displayName} from values`, [displayName]),
activateFunction: () => valueColsSvc?.setColumns(this.addColumnsToList(valueColsSvc.columns), "toolPanelUi"),
deActivateFunction: () => valueColsSvc?.setColumns(this.removeColumnsFromList(valueColsSvc.columns), "toolPanelUi"),
addIcon: "valuePanel",
removeIcon: "valuePanel"
});
menuItemMap.set("pivot", {
allowedFunction: (col) => isPivotMode2 && col.isPrimary() && col.isAllowPivot(),
activeFunction: (col) => col.isPivotActive(),
activateLabel: () => localeTextFunc("addToLabels", `Add ${displayName} to labels`, [displayName]),
deactivateLabel: () => localeTextFunc("removeFromLabels", `Remove ${displayName} from labels`, [displayName]),
activateFunction: () => pivotColsSvc?.setColumns(this.addColumnsToList(pivotColsSvc.columns), "toolPanelUi"),
deActivateFunction: () => pivotColsSvc?.setColumns(this.removeColumnsFromList(pivotColsSvc.columns), "toolPanelUi"),
addIcon: "pivotPanel",
removeIcon: "pivotPanel"
});
}
isColumnValidForScrollIntoView(col) {
const isVisible = col.isVisible();
if (!isVisible) {
return false;
}
const parent = col.getParent();
if (!parent) {
return true;
}
return parent.getDisplayedChildren()?.indexOf(col) !== -1;
}
addColumnsToList(columnList) {
return [...columnList].concat(this.columns.filter((col) => columnList.indexOf(col) === -1));
}
removeColumnsFromList(columnList) {
return columnList.filter((col) => this.columns.indexOf(col) === -1);
}
displayContextMenu(menuItemsMapped) {
const eGui = this.getGui();
const menuList = this.createBean(new AgMenuList());
const localeTextFunc = this.getLocaleTextFunc();
let hideFunc = () => {
};
eGui.appendChild(menuList.getGui());
menuList.addMenuItems(menuItemsMapped);
menuList.addManagedListeners(menuList, {
closeMenu: () => {
this.parentEl.focus();
hideFunc();
}
});
const popupSvc = this.beans.popupSvc;
const addPopupRes = popupSvc.addPopup({
modal: true,
eChild: eGui,
closeOnEsc: true,
afterGuiAttached: () => (0, import_ag_grid_community60._focusInto)(menuList.getGui()),
ariaLabel: localeTextFunc("ariaLabelContextMenu", "Context Menu"),
closedCallback: (e) => {
if (e instanceof KeyboardEvent) {
this.parentEl.focus();
}
this.destroyBean(menuList);
}
});
if (addPopupRes) {
hideFunc = addPopupRes.hideFunc;
}
popupSvc.positionPopupUnderMouseEvent({
type: "columnContextMenu",
mouseEvent: this.mouseEvent,
ePopup: eGui
});
}
isActive() {
return this.allowScrollIntoView || this.allowGrouping || this.allowValues || this.allowPivoting;
}
getMappedMenuItems() {
const ret = [];
const { menuItemMap, columns, displayName, beans } = this;
for (const val of menuItemMap.values()) {
const isInactive = columns.some((col) => val.allowedFunction(col) && !val.activeFunction(col));
const isActive = columns.some((col) => val.allowedFunction(col) && val.activeFunction(col));
if (isInactive) {
ret.push({
name: val.activateLabel(displayName),
icon: (0, import_ag_grid_community60._createIconNoSpan)(val.addIcon, beans, null),
action: () => val.activateFunction()
});
}
if (isActive && val.removeIcon && val.deactivateLabel) {
ret.push({
name: val.deactivateLabel(displayName),
icon: (0, import_ag_grid_community60._createIconNoSpan)(val.removeIcon, beans, null),
action: () => val.deActivateFunction?.()
});
}
}
return ret;
}
};
// packages/ag-grid-enterprise/src/columnToolPanel/toolPanelColumnGroupComp.ts
var ToolPanelColumnGroupElement = {
tag: "div",
cls: "ag-column-select-column-group",
children: [
{
tag: "span",
ref: "eColumnGroupIcons",
cls: "ag-column-group-icons",
children: [
{ tag: "span", ref: "eGroupClosedIcon", cls: "ag-column-group-closed-icon" },
{ tag: "span", ref: "eGroupOpenedIcon", cls: "ag-column-group-opened-icon" }
]
},
{ tag: "ag-checkbox", ref: "cbSelect", cls: "ag-column-select-checkbox" },
{ tag: "span", ref: "eLabel", cls: "ag-column-select-column-label" }
]
};
var ToolPanelColumnGroupComp = class extends import_ag_grid_community61.Component {
constructor(modelItem, allowDragging, eventType, focusWrapper) {
super();
this.modelItem = modelItem;
this.allowDragging = allowDragging;
this.eventType = eventType;
this.focusWrapper = focusWrapper;
this.cbSelect = import_ag_grid_community61.RefPlaceholder;
this.eLabel = import_ag_grid_community61.RefPlaceholder;
this.eGroupOpenedIcon = import_ag_grid_community61.RefPlaceholder;
this.eGroupClosedIcon = import_ag_grid_community61.RefPlaceholder;
this.eColumnGroupIcons = import_ag_grid_community61.RefPlaceholder;
this.processingColumnStateChange = false;
const { columnGroup, depth, displayName } = modelItem;
this.columnGroup = columnGroup;
this.columnDepth = depth;
this.displayName = displayName;
}
postConstruct() {
this.setTemplate(ToolPanelColumnGroupElement, [import_ag_grid_community61.AgCheckboxSelector]);
const { beans, cbSelect, eLabel, displayName, columnDepth, modelItem, focusWrapper, columnGroup } = this;
const { registry, gos } = beans;
const eDragHandle = (0, import_ag_grid_community61._createIconNoSpan)("columnDrag", beans);
this.eDragHandle = eDragHandle;
eDragHandle.classList.add("ag-drag-handle", "ag-column-select-column-group-drag-handle");
const checkboxGui = cbSelect.getGui();
const checkboxInput = cbSelect.getInputElement();
checkboxGui.insertAdjacentElement("afterend", eDragHandle);
checkboxInput.setAttribute("tabindex", "-1");
eLabel.textContent = displayName ?? "";
this.setupExpandContract();
this.addCss("ag-column-select-indent-" + columnDepth);
this.getGui().style.setProperty("--ag-indentation-level", String(columnDepth));
this.tooltipFeature = this.createOptionalManagedBean(
registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.getGui(),
getLocation: () => "columnToolPanelColumnGroup",
shouldDisplayTooltip: (0, import_ag_grid_community61._getShouldDisplayTooltip)(gos, () => eLabel)
})
);
this.addManagedEventListeners({ columnPivotModeChanged: this.onColumnStateChanged.bind(this) });
this.addManagedElementListeners(eLabel, { click: this.onLabelClicked.bind(this) });
this.addManagedListeners(cbSelect, { fieldValueChanged: this.onCheckboxChanged.bind(this) });
this.addManagedListeners(modelItem, { expandedChanged: this.onExpandChanged.bind(this) });
this.addManagedListeners(focusWrapper, {
keydown: this.handleKeyDown.bind(this),
contextmenu: this.onContextMenu.bind(this)
});
this.setOpenClosedIcons();
this.setupDragging();
this.onColumnStateChanged();
this.addVisibilityListenersToAllChildren();
this.refreshAriaExpanded();
this.refreshAriaLabel();
this.setupTooltip();
const classes = (0, import_ag_grid_community61._getToolPanelClassesFromColDef)(columnGroup.getColGroupDef(), gos, null, columnGroup);
classes.forEach((c) => this.toggleCss(c, true));
}
getColumns() {
return this.columnGroup.getLeafColumns();
}
setupTooltip() {
const colGroupDef = this.columnGroup.getColGroupDef();
if (!colGroupDef) {
return;
}
const refresh = () => this.tooltipFeature?.setTooltipAndRefresh(colGroupDef.headerTooltip);
refresh();
this.addManagedEventListeners({ newColumnsLoaded: refresh });
}
handleKeyDown(e) {
switch (e.key) {
case import_ag_grid_community61.KeyCode.LEFT:
e.preventDefault();
this.modelItem.expanded = false;
break;
case import_ag_grid_community61.KeyCode.RIGHT:
e.preventDefault();
this.modelItem.expanded = true;
break;
case import_ag_grid_community61.KeyCode.SPACE:
e.preventDefault();
if (this.isSelectable()) {
this.onSelectAllChanged(!this.isSelected());
}
break;
}
}
onContextMenu(e) {
const { columnGroup, gos } = this;
if (gos.get("functionsReadOnly")) {
return;
}
const contextMenu = this.createBean(new ToolPanelContextMenu(columnGroup, e, this.focusWrapper));
this.addDestroyFunc(() => {
if (contextMenu.isAlive()) {
this.destroyBean(contextMenu);
}
});
}
addVisibilityListenersToAllChildren() {
const listener = this.onColumnStateChanged.bind(this);
this.columnGroup.getLeafColumns().forEach((column) => {
this.addManagedListeners(column, {
visibleChanged: listener,
columnValueChanged: listener,
columnPivotChanged: listener,
columnRowGroupChanged: listener
});
});
}
setupDragging() {
if (!this.allowDragging) {
(0, import_ag_grid_community61._setDisplayed)(this.eDragHandle, false);
return;
}
const beans = this.beans;
const { gos, eventSvc, dragAndDrop } = beans;
let hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns");
const dragSource = {
type: import_ag_grid_community61.DragSourceType.ToolPanel,
eElement: this.eDragHandle,
dragItemName: this.displayName,
getDefaultIconName: () => hideColumnOnExit ? "hide" : "notAllowed",
getDragItem: () => this.createDragItem(),
onDragStarted: () => {
hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns");
eventSvc.dispatchEvent({
type: "columnPanelItemDragStart",
column: this.columnGroup
});
},
onDragStopped: () => {
eventSvc.dispatchEvent({
type: "columnPanelItemDragEnd"
});
},
onGridEnter: (dragItem) => {
if (hideColumnOnExit) {
updateColumns(beans, {
columns: this.columnGroup.getLeafColumns(),
visibleState: dragItem?.visibleState,
pivotState: dragItem?.pivotState,
eventType: this.eventType
});
}
},
onGridExit: () => {
if (hideColumnOnExit) {
this.onChangeCommon(false);
}
}
};
dragAndDrop.addDragSource(dragSource, true);
this.addDestroyFunc(() => dragAndDrop.removeDragSource(dragSource));
}
createDragItem() {
const columns = this.columnGroup.getLeafColumns();
const visibleState = {};
const pivotState = {};
columns.forEach((col) => {
const colId = col.getId();
visibleState[colId] = col.isVisible();
pivotState[colId] = createPivotState(col);
});
return {
columns,
visibleState,
pivotState
};
}
setupExpandContract() {
const { beans, eGroupClosedIcon, eGroupOpenedIcon, eColumnGroupIcons } = this;
eGroupClosedIcon.appendChild((0, import_ag_grid_community61._createIcon)("columnSelectClosed", beans, null));
eGroupOpenedIcon.appendChild((0, import_ag_grid_community61._createIcon)("columnSelectOpen", beans, null));
const listener = this.onExpandOrContractClicked.bind(this);
this.addManagedElementListeners(eGroupClosedIcon, { click: listener });
this.addManagedElementListeners(eGroupOpenedIcon, { click: listener });
const touchListener = new import_ag_grid_community61.TouchListener(eColumnGroupIcons, true);
this.addManagedListeners(touchListener, { tap: listener });
this.addDestroyFunc(touchListener.destroy.bind(touchListener));
}
onLabelClicked() {
const nextState = !this.cbSelect.getValue();
this.onChangeCommon(nextState);
}
onCheckboxChanged(event) {
this.onChangeCommon(event.selected);
}
getVisibleLeafColumns() {
const childColumns = [];
const extractCols = (children) => {
children.forEach((child) => {
if (!child.passesFilter) {
return;
}
if (child.group) {
extractCols(child.children);
} else {
childColumns.push(child.column);
}
});
};
extractCols(this.modelItem.children);
return childColumns;
}
onChangeCommon(nextState) {
this.refreshAriaLabel();
if (this.processingColumnStateChange) {
return;
}
selectAllChildren(this.beans, this.modelItem.children, nextState, this.eventType);
}
refreshAriaLabel() {
const { cbSelect, focusWrapper, displayName } = this;
const translate = this.getLocaleTextFunc();
const columnLabel = translate("ariaColumnGroup", "Column Group");
const checkboxValue = cbSelect.getValue();
const state = checkboxValue === void 0 ? translate("ariaIndeterminate", "indeterminate") : checkboxValue ? translate("ariaVisible", "visible") : translate("ariaHidden", "hidden");
const visibilityLabel = translate("ariaToggleVisibility", "Press SPACE to toggle visibility");
(0, import_ag_grid_community61._setAriaLabel)(focusWrapper, `${displayName} ${columnLabel}`);
cbSelect.setInputAriaLabel(`${visibilityLabel} (${state})`);
(0, import_ag_grid_community61._setAriaDescribedBy)(focusWrapper, cbSelect.getInputElement().id);
}
onColumnStateChanged() {
const selectedValue = this.workOutSelectedValue();
const readOnlyValue = this.workOutReadOnlyValue();
this.processingColumnStateChange = true;
const cbSelect = this.cbSelect;
cbSelect.setValue(selectedValue);
cbSelect.setReadOnly(readOnlyValue);
this.toggleCss("ag-column-select-column-group-readonly", readOnlyValue);
this.processingColumnStateChange = false;
}
workOutSelectedValue() {
const pivotMode = this.beans.colModel.isPivotMode();
const visibleLeafColumns = this.getVisibleLeafColumns();
let checkedCount = 0;
let uncheckedCount = 0;
visibleLeafColumns.forEach((column) => {
if (!pivotMode && column.getColDef().lockVisible) {
return;
}
if (this.isColumnChecked(column, pivotMode)) {
checkedCount++;
} else {
uncheckedCount++;
}
});
if (checkedCount > 0 && uncheckedCount > 0) {
return void 0;
}
return checkedCount > 0;
}
workOutReadOnlyValue() {
const pivotMode = this.beans.colModel.isPivotMode();
let colsThatCanAction = 0;
this.columnGroup.getLeafColumns().forEach((col) => {
if (pivotMode) {
if (col.isAnyFunctionAllowed()) {
colsThatCanAction++;
}
} else {
if (!col.getColDef().lockVisible) {
colsThatCanAction++;
}
}
});
return colsThatCanAction === 0;
}
isColumnChecked(column, pivotMode) {
if (pivotMode) {
const pivoted = column.isPivotActive();
const grouped = column.isRowGroupActive();
const aggregated = column.isValueActive();
return pivoted || grouped || aggregated;
}
return column.isVisible();
}
onExpandOrContractClicked() {
const modelItem = this.modelItem;
const oldState = modelItem.expanded;
modelItem.expanded = !oldState;
}
onExpandChanged() {
this.setOpenClosedIcons();
this.refreshAriaExpanded();
}
setOpenClosedIcons() {
const folderOpen = this.modelItem.expanded;
(0, import_ag_grid_community61._setDisplayed)(this.eGroupClosedIcon, !folderOpen);
(0, import_ag_grid_community61._setDisplayed)(this.eGroupOpenedIcon, folderOpen);
}
refreshAriaExpanded() {
(0, import_ag_grid_community61._setAriaExpanded)(this.focusWrapper, this.modelItem.expanded);
}
getDisplayName() {
return this.displayName;
}
onSelectAllChanged(value) {
const cbSelect = this.cbSelect;
const cbValue = cbSelect.getValue();
const readOnly = cbSelect.isReadOnly();
if (!readOnly && (value && !cbValue || !value && cbValue)) {
cbSelect.toggle();
}
}
isSelected() {
return this.cbSelect.getValue();
}
isSelectable() {
return !this.cbSelect.isReadOnly();
}
setSelected(selected) {
this.cbSelect.setValue(selected, true);
}
};
// packages/ag-grid-enterprise/src/columnToolPanel/columnMoveUtils.ts
var getCurrentColumnsBeingMoved = (column) => {
if ((0, import_ag_grid_community62.isProvidedColumnGroup)(column)) {
return column.getLeafColumns();
}
return column ? [column] : [];
};
var getMoveTargetIndex = (beans, currentColumns, lastHoveredColumn, isBefore) => {
if (!lastHoveredColumn || !currentColumns) {
return null;
}
const allColumns = beans.colModel.getCols();
const targetColumnIndex = allColumns.indexOf(lastHoveredColumn);
const adjustedTarget = isBefore ? targetColumnIndex : targetColumnIndex + 1;
const diff = getMoveDiff(allColumns, currentColumns, adjustedTarget);
return adjustedTarget - diff;
};
var getMoveDiff = (allColumns, currentColumns, end) => {
if (!currentColumns) {
return 0;
}
const targetColumn = currentColumns[0];
const span = currentColumns.length;
const currentIndex = allColumns.indexOf(targetColumn);
if (currentIndex < end) {
return span;
}
return 0;
};
var isMoveBlocked = (gos, beans, currentColumns) => {
const preventMoving = gos.get("suppressMovableColumns") || beans.colModel.isPivotMode();
if (preventMoving) {
return true;
}
const hasNotMovable = currentColumns.find(({ colDef }) => !!colDef.suppressMovable || !!colDef.lockPosition);
return !!hasNotMovable;
};
var moveItem = (beans, currentColumns, lastHoveredListItem) => {
if (!lastHoveredListItem) {
return;
}
const { component } = lastHoveredListItem;
let lastHoveredColumn = null;
let isBefore = lastHoveredListItem.position === "top";
if (component instanceof ToolPanelColumnGroupComp) {
const columns = component.getColumns();
lastHoveredColumn = columns[0];
isBefore = true;
} else if (component) {
lastHoveredColumn = component.column;
}
if (!lastHoveredColumn) {
return;
}
const targetIndex = getMoveTargetIndex(beans, currentColumns, lastHoveredColumn, isBefore);
if (targetIndex != null) {
beans.colMoves?.moveColumns(currentColumns, targetIndex, "toolPanelUi");
}
};
var getCurrentDragValue = (listItemDragStartEvent) => {
return listItemDragStartEvent.column;
};
// packages/ag-grid-enterprise/src/columnToolPanel/toolPanelColumnComp.ts
var import_ag_grid_community63 = require("ag-grid-community");
var ToolPanelColumnElement = {
tag: "div",
cls: "ag-column-select-column",
children: [
{ tag: "ag-checkbox", ref: "cbSelect", cls: "ag-column-select-checkbox" },
{ tag: "span", ref: "eLabel", cls: "ag-column-select-column-label" }
]
};
var ToolPanelColumnComp = class extends import_ag_grid_community63.Component {
constructor(modelItem, allowDragging, groupsExist, focusWrapper) {
super();
this.modelItem = modelItem;
this.allowDragging = allowDragging;
this.groupsExist = groupsExist;
this.focusWrapper = focusWrapper;
this.eLabel = import_ag_grid_community63.RefPlaceholder;
this.cbSelect = import_ag_grid_community63.RefPlaceholder;
this.processingColumnStateChange = false;
const { column, depth, displayName } = modelItem;
this.column = column;
this.columnDepth = depth;
this.displayName = displayName;
}
postConstruct() {
this.setTemplate(ToolPanelColumnElement, [import_ag_grid_community63.AgCheckboxSelector]);
const {
beans,
cbSelect,
displayName,
eLabel,
columnDepth: indent,
groupsExist,
column,
gos,
focusWrapper
} = this;
const eDragHandle = (0, import_ag_grid_community63._createIconNoSpan)("columnDrag", beans);
this.eDragHandle = eDragHandle;
eDragHandle.classList.add("ag-drag-handle", "ag-column-select-column-drag-handle");
const checkboxGui = cbSelect.getGui();
const checkboxInput = cbSelect.getInputElement();
checkboxGui.insertAdjacentElement("afterend", eDragHandle);
checkboxInput.setAttribute("tabindex", "-1");
eLabel.textContent = displayName;
if (groupsExist) {
this.addCss("ag-column-select-add-group-indent");
}
this.addCss(`ag-column-select-indent-${indent}`);
this.getGui().style.setProperty("--ag-indentation-level", String(indent));
this.tooltipFeature = this.createOptionalManagedBean(
beans.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.getGui(),
getLocation: () => "columnToolPanelColumn",
getColDef: () => column.getColDef(),
shouldDisplayTooltip: (0, import_ag_grid_community63._getShouldDisplayTooltip)(gos, () => eLabel)
})
);
this.setupDragging();
const onColStateChanged = this.onColumnStateChanged.bind(this);
this.addManagedEventListeners({ columnPivotModeChanged: onColStateChanged });
this.addManagedListeners(column, {
columnValueChanged: onColStateChanged,
columnPivotChanged: onColStateChanged,
columnRowGroupChanged: onColStateChanged,
visibleChanged: onColStateChanged
});
this.addManagedListeners(focusWrapper, {
keydown: this.handleKeyDown.bind(this),
contextmenu: this.onContextMenu.bind(this)
});
this.addManagedPropertyListener("functionsReadOnly", this.onColumnStateChanged.bind(this));
this.addManagedListeners(cbSelect, { fieldValueChanged: this.onCheckboxChanged.bind(this) });
this.addManagedElementListeners(eLabel, { click: this.onLabelClicked.bind(this) });
this.onColumnStateChanged();
this.refreshAriaLabel();
this.setupTooltip();
const classes = (0, import_ag_grid_community63._getToolPanelClassesFromColDef)(column.getColDef(), gos, column, null);
classes.forEach((c) => this.toggleCss(c, true));
}
getColumn() {
return this.column;
}
setupTooltip() {
const refresh = () => this.tooltipFeature?.setTooltipAndRefresh(this.column.getColDef().headerTooltip);
refresh();
this.addManagedEventListeners({ newColumnsLoaded: refresh });
}
onContextMenu(e) {
const { column, gos } = this;
if (gos.get("functionsReadOnly")) {
return;
}
const contextMenu = this.createBean(new ToolPanelContextMenu(column, e, this.focusWrapper));
this.addDestroyFunc(() => {
if (contextMenu.isAlive()) {
this.destroyBean(contextMenu);
}
});
}
handleKeyDown(e) {
if (e.key === import_ag_grid_community63.KeyCode.SPACE) {
e.preventDefault();
if (this.isSelectable()) {
this.onSelectAllChanged(!this.isSelected());
}
}
}
onLabelClicked() {
if (this.gos.get("functionsReadOnly")) {
return;
}
const nextState = !this.cbSelect.getValue();
this.onChangeCommon(nextState);
}
onCheckboxChanged(event) {
this.onChangeCommon(event.selected);
}
onChangeCommon(nextState) {
if (this.cbSelect.isReadOnly()) {
return;
}
this.refreshAriaLabel();
if (this.processingColumnStateChange) {
return;
}
setAllColumns(this.beans, [this.column], nextState, "toolPanelUi");
}
refreshAriaLabel() {
const { cbSelect, focusWrapper, displayName } = this;
const translate = this.getLocaleTextFunc();
const columnLabel = translate("ariaColumn", "Column");
const state = cbSelect.getValue() ? translate("ariaVisible", "visible") : translate("ariaHidden", "hidden");
const visibilityLabel = translate("ariaToggleVisibility", "Press SPACE to toggle visibility");
(0, import_ag_grid_community63._setAriaLabel)(focusWrapper, `${displayName} ${columnLabel}`);
this.cbSelect.setInputAriaLabel(`${visibilityLabel} (${state})`);
(0, import_ag_grid_community63._setAriaDescribedBy)(focusWrapper, cbSelect.getInputElement().id);
}
setupDragging() {
const eDragHandle = this.eDragHandle;
if (!this.allowDragging) {
(0, import_ag_grid_community63._setDisplayed)(eDragHandle, false);
return;
}
const beans = this.beans;
const { gos, eventSvc, dragAndDrop } = beans;
let hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns");
const dragSource = {
type: import_ag_grid_community63.DragSourceType.ToolPanel,
eElement: eDragHandle,
dragItemName: this.displayName,
getDefaultIconName: () => hideColumnOnExit ? "hide" : "notAllowed",
getDragItem: () => this.createDragItem(),
onDragStarted: () => {
hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns");
eventSvc.dispatchEvent({
type: "columnPanelItemDragStart",
column: this.column
});
},
onDragStopped: () => {
eventSvc.dispatchEvent({
type: "columnPanelItemDragEnd"
});
},
onGridEnter: (dragItem) => {
if (hideColumnOnExit) {
updateColumns(beans, {
columns: [this.column],
visibleState: dragItem?.visibleState,
pivotState: dragItem?.pivotState,
eventType: "toolPanelUi"
});
}
},
onGridExit: () => {
if (hideColumnOnExit) {
this.onChangeCommon(false);
}
}
};
dragAndDrop.addDragSource(dragSource, true);
this.addDestroyFunc(() => dragAndDrop.removeDragSource(dragSource));
}
createDragItem() {
const colId = this.column.getColId();
const visibleState = { [colId]: this.column.isVisible() };
const pivotState = { [colId]: createPivotState(this.column) };
return {
columns: [this.column],
visibleState,
pivotState
};
}
onColumnStateChanged() {
this.processingColumnStateChange = true;
const isPivotMode2 = this.beans.colModel.isPivotMode();
if (isPivotMode2) {
const anyFunctionActive = this.column.isAnyFunctionActive();
this.cbSelect.setValue(anyFunctionActive);
} else {
this.cbSelect.setValue(this.column.isVisible());
}
let canBeToggled = true;
let canBeDragged = true;
if (isPivotMode2) {
const functionsReadOnly = this.gos.get("functionsReadOnly");
const noFunctionsAllowed = !this.column.isAnyFunctionAllowed();
canBeToggled = !functionsReadOnly && !noFunctionsAllowed;
canBeDragged = canBeToggled;
} else {
const { enableRowGroup, enableValue, lockPosition, suppressMovable, lockVisible } = this.column.getColDef();
const forceDraggable = !!enableRowGroup || !!enableValue;
const disableDraggable = !!lockPosition || !!suppressMovable;
canBeToggled = !lockVisible;
canBeDragged = forceDraggable || !disableDraggable;
}
this.cbSelect.setReadOnly(!canBeToggled);
this.eDragHandle.classList.toggle("ag-column-select-column-readonly", !canBeDragged);
this.toggleCss("ag-column-select-column-readonly", !canBeDragged && !canBeToggled);
this.cbSelect.setPassive(false);
this.processingColumnStateChange = false;
}
getDisplayName() {
return this.displayName;
}
onSelectAllChanged(value) {
const cbSelect = this.cbSelect;
if (value !== cbSelect.getValue()) {
if (!cbSelect.isReadOnly()) {
cbSelect.toggle();
}
}
}
isSelected() {
return this.cbSelect.getValue();
}
isSelectable() {
return !this.cbSelect.isReadOnly();
}
isExpandable() {
return false;
}
setExpanded(_value) {
(0, import_ag_grid_community63._warn)(158);
}
};
// packages/ag-grid-enterprise/src/columnToolPanel/agPrimaryColsList.ts
var UIColumnModel = class {
constructor(items) {
this.items = items;
}
getRowCount() {
return this.items.length;
}
getRow(index) {
return this.items[index];
}
};
var PRIMARY_COLS_LIST_PANEL_CLASS = "ag-column-select-list";
var AgPrimaryColsList = class extends import_ag_grid_community64.Component {
constructor() {
super({ tag: "div", cls: PRIMARY_COLS_LIST_PANEL_CLASS, role: "presentation" });
this.destroyColumnItemFuncs = [];
this.hasLoadedInitialState = false;
this.isInitialState = false;
this.skipRefocus = false;
}
wireBeans(beans) {
this.colModel = beans.colModel;
}
destroy() {
this.destroyColumnTree();
super.destroy();
}
destroyColumnTree() {
this.allColsTree = [];
this.destroyColumnItemFuncs.forEach((f) => f());
this.destroyColumnItemFuncs = [];
}
init(params, allowDragging, eventType) {
this.params = params;
const { suppressSyncLayoutWithGrid, contractColumnSelection, suppressColumnMove } = params;
this.allowDragging = allowDragging;
this.eventType = eventType;
if (!suppressSyncLayoutWithGrid) {
this.addManagedEventListeners({ columnMoved: this.onColumnsChanged.bind(this) });
}
this.addManagedEventListeners({
newColumnsLoaded: this.onColumnsChanged.bind(this)
});
const listener = this.fireSelectionChangedEvent.bind(this);
this.addManagedEventListeners({
columnPivotChanged: listener,
columnPivotModeChanged: listener,
columnRowGroupChanged: listener,
columnValueChanged: listener,
columnVisible: listener,
newColumnsLoaded: listener
});
this.expandGroupsByDefault = !contractColumnSelection;
const isPreventMove = suppressColumnMove || suppressSyncLayoutWithGrid;
const virtualList = this.createManagedBean(
new VirtualList({
cssIdentifier: "column-select",
ariaRole: "tree",
moveItemCallback: (item, isUp) => {
if (isPreventMove) {
return;
}
this.moveItems(item, isUp);
}
})
);
this.virtualList = virtualList;
this.appendChild(virtualList.getGui());
virtualList.setComponentCreator((item, listItemElement) => {
(0, import_ag_grid_community64._setAriaLevel)(listItemElement, item.depth + 1);
return this.createComponentFromItem(item, listItemElement);
});
if (this.colModel.ready) {
this.onColumnsChanged();
}
if (isPreventMove) {
return;
}
this.createItemDragFeature();
}
createItemDragFeature() {
const { gos, beans, eventSvc, virtualList } = this;
this.createManagedBean(
new VirtualListDragFeature(this, virtualList, {
dragSourceType: import_ag_grid_community65.DragSourceType.ToolPanel,
listItemDragStartEvent: "columnPanelItemDragStart",
listItemDragEndEvent: "columnPanelItemDragEnd",
eventSource: eventSvc,
getCurrentDragValue: (listItemDragStartEvent) => getCurrentDragValue(listItemDragStartEvent),
isMoveBlocked: (currentDragValue) => isMoveBlocked(gos, beans, getCurrentColumnsBeingMoved(currentDragValue)),
getNumRows: (comp) => comp.getDisplayedColsList().length,
moveItem: (currentDragValue, lastHoveredListItem) => moveItem(beans, getCurrentColumnsBeingMoved(currentDragValue), lastHoveredListItem)
})
);
}
moveItems(item, isUp) {
const { gos, beans } = this;
const { modelItem } = item;
const { group, columnGroup, column, expanded } = modelItem;
const currentColumns = getCurrentColumnsBeingMoved(group ? columnGroup : column);
if (isMoveBlocked(gos, beans, currentColumns)) {
return;
}
const currentIndex = this.displayedColsList.indexOf(modelItem);
const diff = isUp ? -1 : 1;
let movePadding = 0;
if (isUp) {
const children = item.columnDepth > 0 && column.getParent()?.getChildren();
if (children && children.length && column === children[0]) {
movePadding = -1;
}
} else if (group) {
movePadding = expanded ? modelItem.children.length : 0;
}
const nextItem = Math.min(Math.max(currentIndex + movePadding + diff, 0), this.displayedColsList.length - 1);
this.skipRefocus = true;
moveItem(beans, currentColumns, {
rowIndex: nextItem,
position: isUp ? "top" : "bottom",
component: this.virtualList.getComponentAt(nextItem)
});
this.focusRowIfAlive(nextItem - movePadding).then(() => {
this.skipRefocus = false;
});
}
createComponentFromItem(item, listItemElement) {
const allowDragging = this.allowDragging;
if (item.group) {
const renderedGroup = new ToolPanelColumnGroupComp(item, allowDragging, this.eventType, listItemElement);
this.createBean(renderedGroup);
return renderedGroup;
}
const columnComp = new ToolPanelColumnComp(item, allowDragging, this.groupsExist, listItemElement);
this.createBean(columnComp);
return columnComp;
}
onColumnsChanged() {
const params = this.params;
if (!this.hasLoadedInitialState) {
this.hasLoadedInitialState = true;
this.isInitialState = !!params.initialState;
}
const expandedStates = this.getExpandedStates();
const pivotModeActive = this.colModel.isPivotMode();
const shouldSyncColumnLayoutWithGrid = !params.suppressSyncLayoutWithGrid && !pivotModeActive;
if (shouldSyncColumnLayoutWithGrid) {
this.buildTreeFromWhatGridIsDisplaying();
} else {
this.buildTreeFromProvidedColumnDefs();
}
this.setExpandedStates(expandedStates);
this.markFilteredColumns();
this.flattenAndFilterModel();
this.isInitialState = false;
}
getDisplayedColsList() {
return this.displayedColsList;
}
getExpandedStates() {
const res = {};
if (this.isInitialState) {
const { expandedGroupIds } = this.params.initialState;
expandedGroupIds.forEach((id) => {
res[id] = true;
});
return res;
}
if (!this.allColsTree) {
return {};
}
this.forEachItem((item) => {
if (!item.group) {
return;
}
const colGroup = item.columnGroup;
if (colGroup) {
res[colGroup.getId()] = item.expanded;
}
});
return res;
}
setExpandedStates(states) {
if (!this.allColsTree) {
return;
}
const { isInitialState } = this;
this.forEachItem((item) => {
if (!item.group) {
return;
}
const colGroup = item.columnGroup;
if (colGroup) {
const expanded = states[colGroup.getId()];
const groupExistedLastTime = expanded != null;
if (groupExistedLastTime || isInitialState) {
item.expanded = !!expanded;
}
}
});
}
buildTreeFromWhatGridIsDisplaying() {
syncLayoutWithGrid(this.colModel, this.setColumnLayout.bind(this));
}
setColumnLayout(colDefs) {
const columnTree = toolPanelCreateColumnTree(this.colModel, colDefs);
this.buildListModel(columnTree);
this.groupsExist = colDefs.some((colDef) => {
return colDef && typeof colDef.children !== "undefined";
});
this.markFilteredColumns();
this.flattenAndFilterModel();
}
buildTreeFromProvidedColumnDefs() {
const colModel = this.colModel;
this.buildListModel(colModel.getColDefColTree());
this.groupsExist = !!colModel.colDefCols?.treeDepth;
}
buildListModel(columnTree) {
const columnExpandedListener = this.onColumnExpanded.bind(this);
const addListeners = (item) => {
item.addEventListener("expandedChanged", columnExpandedListener);
const removeFunc = item.removeEventListener.bind(item, "expandedChanged", columnExpandedListener);
this.destroyColumnItemFuncs.push(removeFunc);
};
const colNames = this.beans.colNames;
const recursivelyBuild = (tree, depth, parentList) => {
tree.forEach((child) => {
if ((0, import_ag_grid_community64.isProvidedColumnGroup)(child)) {
createGroupItem(child, depth, parentList);
} else {
createColumnItem(child, depth, parentList);
}
});
};
const createGroupItem = (columnGroup, depth, parentList) => {
const columnGroupDef = columnGroup.getColGroupDef();
const skipThisGroup = columnGroupDef && columnGroupDef.suppressColumnsToolPanel;
if (skipThisGroup) {
return;
}
if (columnGroup.isPadding()) {
recursivelyBuild(columnGroup.getChildren(), depth, parentList);
return;
}
const displayName = colNames.getDisplayNameForProvidedColumnGroup(null, columnGroup, "columnToolPanel");
const item = new ColumnModelItem(
displayName,
columnGroup,
depth,
true,
this.expandGroupsByDefault
);
parentList.push(item);
addListeners(item);
recursivelyBuild(columnGroup.getChildren(), depth + 1, item.children);
};
const createColumnItem = (column, depth, parentList) => {
const skipThisColumn = column.getColDef() && column.getColDef().suppressColumnsToolPanel;
if (skipThisColumn) {
return;
}
const displayName = colNames.getDisplayNameForColumn(column, "columnToolPanel");
parentList.push(new ColumnModelItem(displayName, column, depth));
};
this.destroyColumnTree();
recursivelyBuild(columnTree, 0, this.allColsTree);
}
onColumnExpanded() {
this.flattenAndFilterModel();
}
flattenAndFilterModel() {
this.displayedColsList = [];
const recursiveFunc = (item) => {
if (!item.passesFilter) {
return;
}
this.displayedColsList.push(item);
if (item.group && item.expanded) {
item.children.forEach(recursiveFunc);
}
};
const virtualList = this.virtualList;
this.allColsTree.forEach(recursiveFunc);
virtualList.setModel(new UIColumnModel(this.displayedColsList));
let focusedRow = null;
if (!this.skipRefocus) {
focusedRow = virtualList.getLastFocusedRow();
}
virtualList.refresh();
if (focusedRow != null) {
this.focusRowIfAlive(focusedRow);
}
this.notifyListeners();
this.refreshAriaLabel();
}
refreshAriaLabel() {
const translate = this.getLocaleTextFunc();
const columnListName = translate("ariaColumnPanelList", "Column List");
const localeColumns = translate("columns", "Columns");
const items = this.displayedColsList.length;
(0, import_ag_grid_community64._setAriaLabel)(this.virtualList.getAriaElement(), `${columnListName} ${items} ${localeColumns}`);
}
focusRowIfAlive(rowIndex) {
if (rowIndex === -1) {
return Promise.resolve();
}
return new Promise((res) => {
window.setTimeout(() => {
if (this.isAlive()) {
this.virtualList.focusRow(rowIndex);
}
res();
}, 0);
});
}
forEachItem(callback) {
const recursiveFunc = (items) => {
items.forEach((item) => {
callback(item);
if (item.group) {
recursiveFunc(item.children);
}
});
};
const allColsTree = this.allColsTree;
if (!allColsTree) {
return;
}
recursiveFunc(allColsTree);
}
doSetExpandedAll(value) {
this.forEachItem((item) => {
if (item.group) {
item.expanded = value;
}
});
}
setGroupsExpanded(expand, groupIds) {
if (!groupIds) {
this.doSetExpandedAll(expand);
return;
}
const expandedGroupIds = [];
this.forEachItem((item) => {
if (!item.group) {
return;
}
const groupId = item.columnGroup.getId();
if (groupIds.indexOf(groupId) >= 0) {
item.expanded = expand;
expandedGroupIds.push(groupId);
}
});
const unrecognisedGroupIds = groupIds.filter((groupId) => !expandedGroupIds.includes(groupId));
if (unrecognisedGroupIds.length > 0) {
(0, import_ag_grid_community64._warn)(157, { unrecognisedGroupIds });
}
}
getExpandState() {
let expandedCount = 0;
let notExpandedCount = 0;
this.forEachItem((item) => {
if (!item.group) {
return;
}
if (item.expanded) {
expandedCount++;
} else {
notExpandedCount++;
}
});
if (expandedCount > 0 && notExpandedCount > 0) {
return 2 /* INDETERMINATE */;
}
if (notExpandedCount > 0) {
return 1 /* COLLAPSED */;
}
return 0 /* EXPANDED */;
}
doSetSelectedAll(selectAllChecked) {
selectAllChildren(this.beans, this.allColsTree, selectAllChecked, this.eventType);
}
getSelectionState() {
let checkedCount = 0;
let uncheckedCount = 0;
const pivotMode = this.colModel.isPivotMode();
this.forEachItem((item) => {
if (item.group) {
return;
}
if (!item.passesFilter) {
return;
}
const column = item.column;
const colDef = column.getColDef();
let checked;
if (pivotMode) {
const noPivotModeOptionsAllowed = !column.isAllowPivot() && !column.isAllowRowGroup() && !column.isAllowValue();
if (noPivotModeOptionsAllowed) {
return;
}
checked = column.isValueActive() || column.isPivotActive() || column.isRowGroupActive();
} else {
if (colDef.lockVisible) {
return;
}
checked = column.isVisible();
}
checked ? checkedCount++ : uncheckedCount++;
});
if (checkedCount > 0 && uncheckedCount > 0) {
return void 0;
}
return !(checkedCount === 0 || uncheckedCount > 0);
}
setFilterText(filterText) {
this.filterText = (0, import_ag_grid_community64._exists)(filterText) ? filterText.toLowerCase() : null;
this.markFilteredColumns();
this.flattenAndFilterModel();
}
markFilteredColumns() {
const passesFilter = (item) => {
if (!(0, import_ag_grid_community64._exists)(this.filterText)) {
return true;
}
const displayName = item.displayName;
return displayName == null || displayName.toLowerCase().indexOf(this.filterText) !== -1;
};
const recursivelyCheckFilter = (item, parentPasses) => {
let atLeastOneChildPassed = false;
if (item.group) {
const groupPasses = passesFilter(item);
item.children.forEach((child) => {
const childPasses = recursivelyCheckFilter(child, groupPasses || parentPasses);
if (childPasses) {
atLeastOneChildPassed = childPasses;
}
});
}
const filterPasses = parentPasses || atLeastOneChildPassed ? true : passesFilter(item);
item.passesFilter = filterPasses;
return filterPasses;
};
this.allColsTree.forEach((item) => recursivelyCheckFilter(item, false));
}
notifyListeners() {
this.fireGroupExpandedEvent();
this.fireSelectionChangedEvent();
}
fireGroupExpandedEvent() {
const expandState = this.getExpandState();
this.dispatchLocalEvent({ type: "groupExpanded", state: expandState });
}
fireSelectionChangedEvent() {
if (!this.allColsTree) {
return;
}
const selectionState = this.getSelectionState();
this.dispatchLocalEvent({ type: "selectionChanged", state: selectionState });
}
getExpandedGroups() {
const expandedGroupIds = [];
if (!this.allColsTree) {
return expandedGroupIds;
}
this.forEachItem((item) => {
if (item.group && item.expanded) {
expandedGroupIds.push(item.columnGroup.getId());
}
});
return expandedGroupIds;
}
};
var AgPrimaryColsListSelector = {
selector: "AG-PRIMARY-COLS-LIST",
component: AgPrimaryColsList
};
// packages/ag-grid-enterprise/src/columnToolPanel/agPrimaryCols.ts
var AgPrimaryColsElement = {
tag: "div",
cls: "ag-column-select",
children: [
{ tag: "ag-primary-cols-header", ref: "primaryColsHeaderPanel" },
{ tag: "ag-primary-cols-list", ref: "primaryColsListPanel" }
]
};
var AgPrimaryCols = class extends import_ag_grid_community66.Component {
constructor() {
super(AgPrimaryColsElement, [AgPrimaryColsHeaderSelector, AgPrimaryColsListSelector]);
this.primaryColsHeaderPanel = import_ag_grid_community66.RefPlaceholder;
this.primaryColsListPanel = import_ag_grid_community66.RefPlaceholder;
this.registerCSS(agPrimaryColsCSS);
}
// we allow dragging in the toolPanel, but not when this component appears in the column menu
init(allowDragging, params, eventType) {
const { primaryColsHeaderPanel, primaryColsListPanel } = this;
primaryColsHeaderPanel.init(params);
const hideFilter = params.suppressColumnFilter;
const hideSelect = params.suppressColumnSelectAll;
const hideExpand = params.suppressColumnExpandAll;
if (hideExpand && hideFilter && hideSelect) {
primaryColsHeaderPanel.setDisplayed(false);
}
this.addManagedListeners(primaryColsListPanel, {
groupExpanded: (event) => {
primaryColsHeaderPanel.setExpandState(event.state);
params.onStateUpdated();
},
selectionChanged: (event) => primaryColsHeaderPanel.setSelectionState(event.state)
});
primaryColsListPanel.init(params, allowDragging, eventType);
this.addManagedListeners(primaryColsHeaderPanel, {
expandAll: primaryColsListPanel.doSetExpandedAll.bind(primaryColsListPanel, true),
collapseAll: primaryColsListPanel.doSetExpandedAll.bind(primaryColsListPanel, false),
selectAll: primaryColsListPanel.doSetSelectedAll.bind(primaryColsListPanel, true),
unselectAll: primaryColsListPanel.doSetSelectedAll.bind(primaryColsListPanel, false),
filterChanged: (event) => primaryColsListPanel.setFilterText(event.filterText)
});
this.positionableFeature = this.createManagedBean(new import_ag_grid_community66.PositionableFeature(this.getGui(), { minHeight: 100 }));
}
toggleResizable(resizable) {
this.positionableFeature.setResizable(resizable ? { bottom: true } : false);
}
expandGroups(groupIds) {
this.primaryColsListPanel.setGroupsExpanded(true, groupIds);
}
collapseGroups(groupIds) {
this.primaryColsListPanel.setGroupsExpanded(false, groupIds);
}
setColumnLayout(colDefs) {
this.primaryColsListPanel.setColumnLayout(colDefs);
}
syncLayoutWithGrid() {
this.primaryColsListPanel.onColumnsChanged();
}
getExpandedGroups() {
return this.primaryColsListPanel.getExpandedGroups();
}
};
// packages/ag-grid-enterprise/src/columnToolPanel/columnToolPanel.css-GENERATED.ts
var columnToolPanelCSS = (
/*css*/
`.ag-column-panel{display:flex;flex:1 1 auto;flex-direction:column;overflow:hidden}.ag-pivot-mode-panel{display:flex;height:var(--ag-header-height)}.ag-pivot-mode-select{align-items:center;display:flex}:where(.ag-ltr) .ag-pivot-mode-select{margin-left:var(--ag-widget-container-horizontal-padding)}:where(.ag-rtl) .ag-pivot-mode-select{margin-right:var(--ag-widget-container-horizontal-padding)}.ag-column-panel-column-select{border-bottom:var(--ag-tool-panel-separator-border)}.ag-column-panel-column-select:where(:nth-child(n+2 of :not(.ag-hidden))){border-top:var(--ag-tool-panel-separator-border)}:where(.ag-column-panel) .ag-column-drop-vertical{flex:1 1 0px;min-height:50px;&:where(:not(.ag-last-column-drop)){border-bottom:var(--ag-tool-panel-separator-border)}}`
);
// packages/ag-grid-enterprise/src/columnToolPanel/columnToolPanel.ts
var ColumnToolPanel = class extends import_ag_grid_community67.Component {
constructor() {
super({ tag: "div", cls: "ag-column-panel" });
this.initialised = false;
this.childDestroyFuncs = [];
this.registerCSS(columnToolPanelCSS);
}
wireBeans(beans) {
this.colToolPanelFactory = beans.colToolPanelFactory;
}
// lazy initialise the panel
setVisible(visible) {
super.setDisplayed(visible);
if (visible && !this.initialised) {
this.init(this.params);
}
}
init(params) {
const defaultParams = (0, import_ag_grid_community67._addGridCommonParams)(this.gos, {
suppressColumnMove: false,
suppressColumnSelectAll: false,
suppressColumnFilter: false,
suppressColumnExpandAll: false,
contractColumnSelection: false,
suppressPivotMode: false,
suppressRowGroups: false,
suppressValues: false,
suppressPivots: false,
suppressSyncLayoutWithGrid: false
});
const mergedParams = {
...defaultParams,
...params
};
this.params = mergedParams;
const { childDestroyFuncs, colToolPanelFactory, gos } = this;
const hasPivotModule = gos.isModuleRegistered("SharedPivot");
const hasRowGroupingModule = hasPivotModule || gos.isModuleRegistered("SharedRowGrouping");
if (!mergedParams.suppressPivotMode && colToolPanelFactory && hasPivotModule) {
this.pivotModePanel = colToolPanelFactory.createPivotModePanel(this, childDestroyFuncs);
}
const primaryColsPanel = this.createBean(new AgPrimaryCols());
this.primaryColsPanel = primaryColsPanel;
childDestroyFuncs.push(() => this.destroyBean(this.primaryColsPanel));
primaryColsPanel.init(true, mergedParams, "toolPanelUi");
primaryColsPanel.addCss("ag-column-panel-column-select");
this.appendChild(primaryColsPanel);
if (colToolPanelFactory) {
if (!mergedParams.suppressRowGroups && hasRowGroupingModule) {
this.rowGroupDropZonePanel = colToolPanelFactory.createRowGroupPanel(this, childDestroyFuncs);
}
if (!mergedParams.suppressValues && hasRowGroupingModule) {
this.valuesDropZonePanel = colToolPanelFactory.createValuesPanel(this, childDestroyFuncs);
}
if (!mergedParams.suppressPivots && hasPivotModule) {
this.pivotDropZonePanel = colToolPanelFactory.createPivotPanel(this, childDestroyFuncs);
}
this.setLastVisible();
const [pivotModeListener] = this.addManagedEventListeners({
columnPivotModeChanged: () => {
this.resetChildrenHeight();
this.setLastVisible();
}
});
childDestroyFuncs.push(() => pivotModeListener());
}
this.initialised = true;
}
setPivotModeSectionVisible(visible) {
const colToolPanelFactory = this.colToolPanelFactory;
if (!colToolPanelFactory) {
return;
}
this.pivotModePanel = colToolPanelFactory.setPanelVisible(
this.pivotModePanel,
visible,
colToolPanelFactory.createPivotModePanel.bind(colToolPanelFactory, this, this.childDestroyFuncs, true)
);
this.setLastVisible();
}
setRowGroupsSectionVisible(visible) {
const colToolPanelFactory = this.colToolPanelFactory;
if (!colToolPanelFactory) {
return;
}
this.rowGroupDropZonePanel = colToolPanelFactory.setPanelVisible(
this.rowGroupDropZonePanel,
visible,
colToolPanelFactory.createRowGroupPanel.bind(colToolPanelFactory, this, this.childDestroyFuncs)
);
this.setLastVisible();
}
setValuesSectionVisible(visible) {
const colToolPanelFactory = this.colToolPanelFactory;
if (!colToolPanelFactory) {
return;
}
this.valuesDropZonePanel = colToolPanelFactory.setPanelVisible(
this.valuesDropZonePanel,
visible,
colToolPanelFactory.createValuesPanel.bind(colToolPanelFactory, this, this.childDestroyFuncs)
);
this.setLastVisible();
}
setPivotSectionVisible(visible) {
const colToolPanelFactory = this.colToolPanelFactory;
if (!colToolPanelFactory) {
return;
}
this.pivotDropZonePanel = colToolPanelFactory.setPanelVisible(
this.pivotDropZonePanel,
visible,
colToolPanelFactory.createPivotPanel.bind(colToolPanelFactory, this, this.childDestroyFuncs)
);
this.pivotDropZonePanel?.setDisplayed(visible);
this.setLastVisible();
}
setResizers() {
[this.primaryColsPanel, this.rowGroupDropZonePanel, this.valuesDropZonePanel, this.pivotDropZonePanel].forEach(
(panel) => {
if (!panel) {
return;
}
const eGui = panel.getGui();
panel.toggleResizable(
!eGui.classList.contains("ag-last-column-drop") && !eGui.classList.contains("ag-hidden")
);
}
);
}
setLastVisible() {
const eGui = this.getGui();
const columnDrops = Array.prototype.slice.call(eGui.querySelectorAll(".ag-column-drop"));
columnDrops.forEach((columnDrop) => columnDrop.classList.remove("ag-last-column-drop"));
const columnDropEls = eGui.querySelectorAll(".ag-column-drop:not(.ag-hidden)");
const lastVisible = (0, import_ag_grid_community67._last)(columnDropEls);
if (lastVisible) {
lastVisible.classList.add("ag-last-column-drop");
}
this.setResizers();
}
resetChildrenHeight() {
const eGui = this.getGui();
const children = eGui.children;
for (let i = 0; i < children.length; i++) {
const { style } = children[i];
style.removeProperty("height");
style.removeProperty("flex");
}
}
expandColumnGroups(groupIds) {
this.primaryColsPanel.expandGroups(groupIds);
}
collapseColumnGroups(groupIds) {
this.primaryColsPanel.collapseGroups(groupIds);
}
setColumnLayout(colDefs) {
this.primaryColsPanel.setColumnLayout(colDefs);
}
syncLayoutWithGrid() {
this.primaryColsPanel.syncLayoutWithGrid();
}
destroyChildren() {
const childDestroyFuncs = this.childDestroyFuncs;
childDestroyFuncs.forEach((func) => func());
childDestroyFuncs.length = 0;
(0, import_ag_grid_community67._clearElement)(this.getGui());
}
refresh(params) {
this.destroyChildren();
this.init(params);
return true;
}
getState() {
return {
expandedGroupIds: this.primaryColsPanel.getExpandedGroups()
};
}
destroy() {
this.destroyChildren();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/columnToolPanel/columnToolPanelFactory.ts
var import_ag_grid_community76 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/pivotDropZonePanel.ts
var import_ag_grid_community72 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/baseDropZonePanel.ts
var import_ag_grid_community71 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/pillDropZonePanel.ts
var import_ag_grid_community68 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/pillDropZonePanel.css-GENERATED.ts
var pillDropZonePanelCSS = (
/*css*/
`.ag-column-drop{align-items:center;display:inline-flex;overflow:auto;position:relative;width:100%}.ag-column-drop-list{align-items:center;display:flex}.ag-column-drop-cell{align-items:center;background-color:var(--ag-column-drop-cell-background-color);border:var(--ag-column-drop-cell-border);border-radius:500px;color:var(--ag-column-drop-cell-text-color);display:flex;padding:calc(var(--ag-spacing)*.25);position:relative;&:focus-visible{box-shadow:var(--ag-focus-shadow)}:where(.ag-drag-handle){color:var(--ag-column-drop-cell-drag-handle-color)}}:where(.ag-ltr) .ag-column-drop-cell{padding-left:calc(var(--ag-spacing)*.75)}:where(.ag-rtl) .ag-column-drop-cell{padding-right:calc(var(--ag-spacing)*.75)}.ag-column-drop-cell-text{flex:1 1 auto;margin:0 var(--ag-spacing);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ag-column-drop-vertical{align-items:stretch;display:flex;flex-direction:column;min-height:75px;overflow:hidden}.ag-column-drop-vertical-title-bar{align-items:center;display:flex;flex:none;padding:var(--ag-widget-container-vertical-padding) calc(var(--ag-spacing)*2) 0}.ag-column-drop-vertical-list{align-items:stretch;flex-direction:column;flex-grow:1;overflow-x:auto;padding-bottom:var(--ag-spacing);padding-left:var(--ag-spacing);padding-right:var(--ag-spacing);position:relative;>*{flex:none}}:where(.ag-column-drop-empty) .ag-column-drop-vertical-list{overflow:hidden}.ag-column-drop-cell-button{cursor:pointer;min-width:0;opacity:.75;&:hover{opacity:1}}.ag-column-drop-wrapper{display:flex}.ag-column-drop-horizontal-half-width{width:50%!important}.ag-column-drop-cell-ghost{opacity:.5}.ag-column-drop-horizontal{background-color:var(--ag-header-background-color);border-bottom:var(--ag-header-row-border);gap:var(--ag-cell-widget-spacing);height:var(--ag-header-height);overflow:hidden;white-space:nowrap}:where(.ag-ltr) .ag-column-drop-horizontal{padding-left:var(--ag-cell-horizontal-padding)}:where(.ag-rtl) .ag-column-drop-horizontal{padding-right:var(--ag-cell-horizontal-padding)}.ag-column-drop-horizontal-list{gap:var(--ag-cell-widget-spacing)}.ag-column-drop-vertical-cell{margin-top:var(--ag-spacing)}:where(.ag-ltr) .ag-column-drop-vertical-icon{margin-right:var(--ag-widget-horizontal-spacing)}:where(.ag-rtl) .ag-column-drop-vertical-icon{margin-left:var(--ag-widget-horizontal-spacing)}.ag-select-agg-func-popup{background:var(--ag-background-color);border:solid var(--ag-border-width) var(--ag-border-color);border-radius:var(--ag-border-radius);box-shadow:var(--ag-dropdown-shadow);height:calc(var(--ag-spacing)*5*3.5);padding:0;position:absolute}.ag-select-agg-func-virtual-list-item{cursor:default;&:hover{background-color:var(--ag-selected-row-background-color)}}:where(.ag-ltr) .ag-select-agg-func-virtual-list-item{padding-left:calc(var(--ag-spacing)*2)}:where(.ag-rtl) .ag-select-agg-func-virtual-list-item{padding-right:calc(var(--ag-spacing)*2)}:where(.ag-ltr) .ag-column-drop-horizontal-half-width:where(:not(:last-child)){border-right:solid var(--ag-border-width) var(--ag-border-color)}:where(.ag-rtl) .ag-column-drop-horizontal-half-width:where(:not(:last-child)){border-left:solid var(--ag-border-width) var(--ag-border-color)}`
);
// packages/ag-grid-enterprise/src/widgets/pillDropZonePanel.ts
function _insertArrayIntoArray(dest, src, toIndex) {
if (dest == null || src == null) {
return;
}
dest.splice(toIndex, 0, ...src);
}
var PillDropZonePanelElement = { tag: "div", cls: "ag-unselectable", role: "presentation" };
var PillDropZonePanel = class extends import_ag_grid_community68.Component {
constructor(horizontal) {
super(PillDropZonePanelElement);
this.horizontal = horizontal;
this.state = "notDragging";
this.guiDestroyFunctions = [];
this.childPillComponents = [];
this.resizeEnabled = false;
this.addElementClasses(this.getGui());
this.ePillDropList = (0, import_ag_grid_community68._createElement)({ tag: "div" });
this.addElementClasses(this.ePillDropList, "list");
this.registerCSS(pillDropZonePanelCSS);
}
toggleResizable(resizable) {
this.positionableFeature.setResizable(resizable ? { bottom: true } : false);
this.resizeEnabled = resizable;
}
isSourceEventFromTarget(draggingEvent) {
const { dropZoneTarget, dragSource } = draggingEvent;
return dropZoneTarget.contains(dragSource.eElement);
}
destroy() {
this.destroyGui();
super.destroy();
}
destroyGui() {
this.guiDestroyFunctions.forEach((func) => func());
this.guiDestroyFunctions.length = 0;
this.childPillComponents.length = 0;
(0, import_ag_grid_community68._clearElement)(this.getGui());
(0, import_ag_grid_community68._clearElement)(this.ePillDropList);
}
init(params) {
this.params = params ?? {};
this.createManagedBean(
new import_ag_grid_community68.ManagedFocusFeature(this.getFocusableElement(), {
onTabKeyDown: this.onTabKeyDown.bind(this),
handleKeyDown: this.onKeyDown.bind(this)
})
);
this.setupDropTarget();
this.positionableFeature = new import_ag_grid_community68.PositionableFeature(this.getGui());
this.createManagedBean(this.positionableFeature);
this.refreshGui();
(0, import_ag_grid_community68._setAriaLabel)(this.ePillDropList, this.getAriaLabel());
}
onTabKeyDown(e) {
const focusableElements = (0, import_ag_grid_community68._findFocusableElements)(this.getFocusableElement(), null, true);
const len = focusableElements.length;
if (len === 0) {
return;
}
const { shiftKey } = e;
const activeEl = (0, import_ag_grid_community68._getActiveDomElement)(this.beans);
const isFirstFocused = activeEl === focusableElements[0];
const isLastFocused = activeEl === (0, import_ag_grid_community68._last)(focusableElements);
const shouldAllowDefaultTab = len === 1 || isFirstFocused && shiftKey || isLastFocused && !shiftKey;
if (!shouldAllowDefaultTab) {
focusableElements[shiftKey ? 0 : len - 1].focus();
}
}
onKeyDown(e) {
const { key } = e;
const isVertical = !this.horizontal;
let isNext = key === import_ag_grid_community68.KeyCode.DOWN;
let isPrevious = key === import_ag_grid_community68.KeyCode.UP;
if (!isVertical) {
const isRtl = this.gos.get("enableRtl");
isNext = !isRtl && key === import_ag_grid_community68.KeyCode.RIGHT || isRtl && key === import_ag_grid_community68.KeyCode.LEFT;
isPrevious = !isRtl && key === import_ag_grid_community68.KeyCode.LEFT || isRtl && key === import_ag_grid_community68.KeyCode.RIGHT;
}
if (!isNext && !isPrevious) {
return;
}
e.preventDefault();
if (e.shiftKey) {
this.moveFocusedItem(isPrevious);
} else {
const el = (0, import_ag_grid_community68._findNextFocusableElement)(this.beans, this.getFocusableElement(), false, isPrevious);
if (el) {
el.focus();
}
}
}
moveFocusedItem(isPrevious) {
const currentItemIndex = this.getFocusedItem();
if (currentItemIndex === -1) {
return;
}
const diff = isPrevious ? -1 : 1;
const changed = this.normalizeAndUpdateInsertIndex(currentItemIndex, currentItemIndex + diff);
if (!changed) {
return;
}
const comp = this.childPillComponents[currentItemIndex];
if (!comp.isMovable()) {
return;
}
const currentItem = comp.getItem();
this.focusItemAtIndex(this.insertIndex);
this.rearrangeItems([currentItem], true);
}
addElementClasses(el, suffix) {
suffix = suffix ? `-${suffix}` : "";
const direction = this.horizontal ? "horizontal" : "vertical";
el.classList.add(`ag-column-drop${suffix}`, `ag-column-drop-${direction}${suffix}`);
}
setupDropTarget() {
this.dropTarget = {
getContainer: this.getGui.bind(this),
getIconName: this.getIconName.bind(this),
onDragging: this.onDragging.bind(this),
onDragEnter: this.onDragEnter.bind(this),
onDragLeave: this.onDragLeave.bind(this),
onDragStop: this.onDragStop.bind(this),
onDragCancel: this.onDragCancel.bind(this),
isInterestedIn: this.isInterestedIn.bind(this)
};
this.beans.dragAndDrop?.addDropTarget(this.dropTarget);
}
minimumAllowedNewInsertIndex() {
return 0;
}
checkInsertIndex(draggingEvent) {
const newIndex = this.getNewInsertIndex(draggingEvent);
if (newIndex < 0) {
return false;
}
return this.normalizeAndUpdateInsertIndex(this.insertIndex, newIndex);
}
normalizeAndUpdateInsertIndex(currentIndex, index) {
const minimumAllowedIndex = this.minimumAllowedNewInsertIndex();
const newAdjustedIndex = Math.max(minimumAllowedIndex, index);
const changed = newAdjustedIndex !== currentIndex;
if (changed) {
this.insertIndex = newAdjustedIndex;
}
return changed;
}
getNewInsertIndex(draggingEvent) {
const mouseEvent = draggingEvent.event;
const mouseLocation = this.horizontal ? mouseEvent.clientX : mouseEvent.clientY;
const boundsList = this.childPillComponents.map((comp) => comp.getGui().getBoundingClientRect());
const hoveredIndex = boundsList.findIndex(
(rect) => this.horizontal ? rect.right > mouseLocation && rect.left < mouseLocation : rect.top < mouseLocation && rect.bottom > mouseLocation
);
if (hoveredIndex === -1) {
const enableRtl = this.gos.get("enableRtl");
const isLast = boundsList.every((rect) => mouseLocation > (this.horizontal ? rect.right : rect.bottom));
if (isLast) {
return enableRtl && this.horizontal ? 0 : this.childPillComponents.length;
}
const isFirst = boundsList.every((rect) => mouseLocation < (this.horizontal ? rect.left : rect.top));
if (isFirst) {
return enableRtl && this.horizontal ? this.childPillComponents.length : 0;
}
return this.insertIndex;
}
if (this.insertIndex <= hoveredIndex) {
return hoveredIndex + 1;
}
return hoveredIndex;
}
checkDragStartedBySelf(draggingEvent) {
if (this.state !== "notDragging") {
return;
}
this.state = "rearrangeItems";
this.potentialDndItems = this.getItems(draggingEvent.dragSource.getDragItem());
this.refreshGui();
this.checkInsertIndex(draggingEvent);
this.refreshGui();
}
onDragging(draggingEvent) {
this.checkDragStartedBySelf(draggingEvent);
if (this.checkInsertIndex(draggingEvent)) {
this.refreshGui();
}
}
handleDragEnterEnd(_) {
}
onDragEnter(draggingEvent) {
const dragItems = this.getItems(draggingEvent.dragSource.getDragItem());
this.state = "newItemsIn";
const goodDragItems = dragItems.filter((item) => this.isItemDroppable(item, draggingEvent));
const alreadyPresent = goodDragItems.every(
(item) => this.childPillComponents.map((cmp) => cmp.getItem()).indexOf(item) !== -1
);
if (goodDragItems.length === 0) {
return;
}
this.potentialDndItems = goodDragItems;
if (alreadyPresent) {
this.state = "notDragging";
return;
}
this.handleDragEnterEnd(draggingEvent);
this.checkInsertIndex(draggingEvent);
this.refreshGui();
}
isPotentialDndItems() {
return !!this.potentialDndItems?.length;
}
handleDragLeaveEnd(_) {
}
onDragLeave(draggingEvent) {
if (this.state === "rearrangeItems") {
const items = this.getItems(draggingEvent.dragSource.getDragItem());
this.removeItems(items);
}
if (this.isPotentialDndItems()) {
this.handleDragLeaveEnd(draggingEvent);
this.potentialDndItems = [];
this.refreshGui();
}
this.state = "notDragging";
}
onDragCancel(draggingEvent) {
if (this.isPotentialDndItems()) {
if (this.state === "newItemsIn") {
this.handleDragLeaveEnd(draggingEvent);
}
this.potentialDndItems = [];
this.refreshGui();
}
this.state = "notDragging";
}
onDragStop() {
if (this.isPotentialDndItems()) {
if (this.state === "newItemsIn") {
this.addItems(this.potentialDndItems);
} else {
this.rearrangeItems(this.potentialDndItems);
}
this.potentialDndItems = [];
this.refreshGui();
}
this.state = "notDragging";
}
removeItems(itemsToRemove) {
const newItemList = this.getExistingItems().filter((item) => !itemsToRemove.includes(item));
this.updateItems(newItemList);
}
addItems(itemsToAdd) {
if (!itemsToAdd) {
return;
}
const newItemList = this.getExistingItems().slice();
const itemsToAddNoDuplicates = itemsToAdd.filter((item) => newItemList.indexOf(item) < 0);
_insertArrayIntoArray(newItemList, itemsToAddNoDuplicates, this.insertIndex);
this.updateItems(newItemList);
}
addItem(item) {
this.insertIndex = this.getExistingItems().length;
this.addItems([item]);
this.refreshGui();
}
rearrangeItems(itemsToAdd, fromKeyboard) {
let newItemList;
if (!fromKeyboard) {
newItemList = this.getNonGhostItems().slice();
} else {
newItemList = this.getExistingItems().filter((item) => itemsToAdd.indexOf(item) === -1);
}
_insertArrayIntoArray(newItemList, itemsToAdd, this.insertIndex);
if ((0, import_ag_grid_community68._areEqual)(newItemList, this.getExistingItems())) {
return false;
}
this.updateItems(newItemList);
return true;
}
refreshGui() {
let scrollTop = 0;
if (!this.horizontal) {
scrollTop = this.ePillDropList.scrollTop;
}
const resizeEnabled = this.resizeEnabled;
const focusedIndex = this.getFocusedItem();
const { eGridDiv } = this.beans;
const isKeyboardMode = (0, import_ag_grid_community68._isKeyboardMode)();
let alternateElement = null;
if (isKeyboardMode) {
alternateElement = (0, import_ag_grid_community68._findNextFocusableElement)(this.beans, eGridDiv) ?? (0, import_ag_grid_community68._findNextFocusableElement)(this.beans, eGridDiv, false, true);
}
this.toggleResizable(false);
this.destroyGui();
this.addIconAndTitleToGui();
this.addEmptyMessageToGui();
this.addItemsToGui();
if (scrollTop !== 0) {
this.ePillDropList.scrollTop = scrollTop;
}
if (resizeEnabled) {
this.toggleResizable(resizeEnabled);
}
if (isKeyboardMode) {
this.restoreFocus(focusedIndex, alternateElement);
}
}
getFocusedItem() {
const eGui = this.getGui();
const activeElement = (0, import_ag_grid_community68._getActiveDomElement)(this.beans);
if (!eGui.contains(activeElement)) {
return -1;
}
const items = Array.from(eGui.querySelectorAll(".ag-column-drop-cell"));
return items.indexOf(activeElement);
}
focusItemAtIndex(index) {
const eGui = this.getGui();
const items = Array.from(eGui.querySelectorAll(".ag-column-drop-cell"));
const item = items[index];
if (!item) {
return;
}
item.focus({ preventScroll: true });
}
restoreFocus(index, alternateElement) {
const eGui = this.getGui();
const items = Array.from(eGui.querySelectorAll(".ag-column-drop-cell"));
if (index === -1) {
return;
}
if (items.length === 0) {
alternateElement.focus();
}
const indexToFocus = Math.min(items.length - 1, index);
const el = items[indexToFocus];
if (el) {
el.focus();
}
}
focusList(fromBottom) {
const index = fromBottom ? this.childPillComponents.length - 1 : 0;
this.restoreFocus(index, this.getFocusableElement());
}
getNonGhostItems() {
const existingItems = this.getExistingItems();
if (this.isPotentialDndItems()) {
return existingItems.filter((item) => !this.potentialDndItems.includes(item));
}
return existingItems;
}
addItemsToGui() {
const nonGhostItems = this.getNonGhostItems();
const itemsToAddToGui = nonGhostItems.map((item) => this.createItemComponent(item, false));
if (this.isPotentialDndItems()) {
const dndItems = this.potentialDndItems.map((item) => this.createItemComponent(item, true));
if (this.insertIndex >= itemsToAddToGui.length) {
itemsToAddToGui.push(...dndItems);
} else {
itemsToAddToGui.splice(this.insertIndex, 0, ...dndItems);
}
}
this.appendChild(this.ePillDropList);
itemsToAddToGui.forEach((itemComponent, index) => {
if (index > 0) {
this.addArrow(this.ePillDropList);
}
this.ePillDropList.appendChild(itemComponent.getGui());
});
this.addAriaLabelsToComponents();
}
addAriaLabelsToComponents() {
const { childPillComponents, ePillDropList } = this;
const len = childPillComponents.length;
(0, import_ag_grid_community68._setAriaRole)(ePillDropList, len === 0 ? "presentation" : "listbox");
for (let i = 0; i < len; i++) {
const comp = childPillComponents[i];
const eGui = comp.getGui();
(0, import_ag_grid_community68._setAriaPosInSet)(eGui, i + 1);
(0, import_ag_grid_community68._setAriaSetSize)(eGui, len);
}
}
createItemComponent(item, ghost) {
const itemComponent = this.createPillComponent(item, this.dropTarget, ghost, this.horizontal);
itemComponent.addEventListener("columnRemove", this.removeItems.bind(this, [item]));
this.createBean(itemComponent);
this.guiDestroyFunctions.push(() => this.destroyBean(itemComponent));
if (!ghost) {
this.childPillComponents.push(itemComponent);
}
return itemComponent;
}
addIconAndTitleToGui() {
const { title, icon: eGroupIcon } = this.params;
if (!title || !eGroupIcon) {
return;
}
const eTitleBar = (0, import_ag_grid_community68._createElement)({ tag: "div" });
(0, import_ag_grid_community68._setAriaHidden)(eTitleBar, true);
this.addElementClasses(eTitleBar, "title-bar");
this.addElementClasses(eGroupIcon, "icon");
this.toggleCss("ag-column-drop-empty", this.isExistingItemsEmpty());
eTitleBar.appendChild(eGroupIcon);
if (!this.horizontal) {
const eTitle = (0, import_ag_grid_community68._createElement)({ tag: "span" });
this.addElementClasses(eTitle, "title");
eTitle.textContent = title;
eTitleBar.appendChild(eTitle);
}
this.appendChild(eTitleBar);
}
isExistingItemsEmpty() {
return this.getExistingItems().length === 0;
}
addEmptyMessageToGui() {
const { emptyMessage } = this.params;
if (!emptyMessage || !this.isExistingItemsEmpty() || this.isPotentialDndItems()) {
return;
}
const eMessage = (0, import_ag_grid_community68._createElement)({ tag: "span" });
eMessage.textContent = emptyMessage;
this.addElementClasses(eMessage, "empty-message");
this.ePillDropList.appendChild(eMessage);
}
addArrow(eParent) {
if (this.horizontal) {
const enableRtl = this.gos.get("enableRtl");
const icon = (0, import_ag_grid_community68._createIconNoSpan)(enableRtl ? "panelDelimiterRtl" : "panelDelimiter", this.beans);
this.addElementClasses(icon, "cell-separator");
eParent.appendChild(icon);
}
}
};
// packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/dropZoneColumnComp.ts
var import_ag_grid_community70 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/pillDragComp.ts
var import_ag_grid_community69 = require("ag-grid-community");
var PillDragCompElement = {
tag: "span",
role: "option",
children: [
{
tag: "span",
ref: "eDragHandle",
cls: "ag-drag-handle ag-column-drop-cell-drag-handle",
role: "presentation"
},
{ tag: "span", ref: "eText", cls: "ag-column-drop-cell-text", attrs: { "aria-hidden": "true" } },
{ tag: "span", ref: "eButton", cls: "ag-column-drop-cell-button", role: "presentation" }
]
};
var PillDragComp = class extends import_ag_grid_community69.Component {
constructor(dragSourceDropTarget, ghost, horizontal, template, agComponents) {
super();
this.dragSourceDropTarget = dragSourceDropTarget;
this.ghost = ghost;
this.horizontal = horizontal;
this.template = template;
this.agComponents = agComponents;
this.eText = import_ag_grid_community69.RefPlaceholder;
this.eDragHandle = import_ag_grid_community69.RefPlaceholder;
this.eButton = import_ag_grid_community69.RefPlaceholder;
}
postConstruct() {
this.setTemplate(this.template ?? PillDragCompElement, this.agComponents);
const eGui = this.getGui();
const { beans, eDragHandle, eText, eButton } = this;
this.addElementClasses(eGui);
this.addElementClasses(eDragHandle, "drag-handle");
this.addElementClasses(eText, "text");
this.addElementClasses(eButton, "button");
eDragHandle.appendChild((0, import_ag_grid_community69._createIconNoSpan)("columnDrag", beans));
eButton.appendChild((0, import_ag_grid_community69._createIconNoSpan)("cancel", beans));
this.tooltipFeature = this.createOptionalManagedBean(
beans.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.getGui()
})
);
this.setupComponents();
if (!this.ghost && this.isDraggable()) {
this.addDragSource();
}
this.setupAria();
this.setupTooltip();
this.activateTabIndex();
this.refreshDraggable();
}
isDraggable() {
return true;
}
refreshDraggable() {
this.eDragHandle.classList.toggle("ag-column-select-column-readonly", !this.isDraggable());
}
setupAria() {
const translate = this.getLocaleTextFunc();
const ariaInstructions = [this.getAriaDisplayName()];
this.addAdditionalAriaInstructions(ariaInstructions, translate);
(0, import_ag_grid_community69._setAriaLabel)(this.getGui(), ariaInstructions.join(". "));
}
addAdditionalAriaInstructions(ariaInstructions, translate) {
if (this.isRemovable()) {
const deleteAria = translate("ariaDropZoneColumnComponentDescription", "Press DELETE to remove");
ariaInstructions.push(deleteAria);
}
}
setupTooltip() {
const refresh = () => this.tooltipFeature?.setTooltipAndRefresh(this.getTooltip());
refresh();
this.addManagedEventListeners({ newColumnsLoaded: refresh });
}
getDragSourceId() {
return void 0;
}
getDefaultIconName() {
return "notAllowed";
}
addDragSource() {
const {
beans: { dragAndDrop },
eDragHandle
} = this;
const getDragItem = this.createGetDragItem();
const defaultIconName = this.getDefaultIconName();
const dragSource = {
type: this.getDragSourceType(),
sourceId: this.getDragSourceId(),
eElement: eDragHandle,
getDefaultIconName: () => defaultIconName,
getDragItem,
dragItemName: this.getDisplayName()
};
dragAndDrop?.addDragSource(dragSource, true);
this.addDestroyFunc(() => dragAndDrop?.removeDragSource(dragSource));
}
setupComponents() {
this.eText.textContent = this.getDisplayValue();
this.setupRemove();
if (this.ghost) {
this.addCss("ag-column-drop-cell-ghost");
}
}
isRemovable() {
return true;
}
refreshRemove() {
(0, import_ag_grid_community69._setDisplayed)(this.eButton, this.isRemovable());
}
setupRemove() {
this.refreshRemove();
const agEvent = { type: "columnRemove" };
this.addGuiEventListener("keydown", (e) => this.onKeyDown(e));
this.addManagedElementListeners(this.eButton, {
click: (mouseEvent) => {
this.dispatchLocalEvent(agEvent);
mouseEvent.stopPropagation();
}
});
const touchListener = new import_ag_grid_community69.TouchListener(this.eButton);
this.addManagedListeners(touchListener, {
tap: () => this.dispatchLocalEvent(agEvent)
});
this.addDestroyFunc(touchListener.destroy.bind(touchListener));
}
onKeyDown(e) {
const isDelete = e.key === import_ag_grid_community69.KeyCode.DELETE;
if (isDelete) {
if (this.isRemovable()) {
e.preventDefault();
this.dispatchLocalEvent({ type: "columnRemove" });
}
}
}
getDisplayValue() {
return this.getDisplayName();
}
addElementClasses(el, suffix) {
suffix = suffix ? `-${suffix}` : "";
const direction = this.horizontal ? "horizontal" : "vertical";
el.classList.add(`ag-column-drop-cell${suffix}`, `ag-column-drop-${direction}-cell${suffix}`);
}
destroy() {
super.destroy();
this.dragSourceDropTarget = null;
}
};
// packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/dropZoneColumnComp.ts
var DropZoneColumnComp = class extends PillDragComp {
constructor(column, dragSourceDropTarget, ghost, dropZonePurpose, horizontal) {
super(dragSourceDropTarget, ghost, horizontal);
this.column = column;
this.dropZonePurpose = dropZonePurpose;
this.eSortIndicator = import_ag_grid_community70.RefPlaceholder;
this.popupShowing = false;
}
postConstruct() {
const { sortSvc, colNames } = this.beans;
this.template = {
tag: "span",
role: "option",
children: [
{
tag: "span",
ref: "eDragHandle",
cls: "ag-drag-handle ag-column-drop-cell-drag-handle",
role: "presentation"
},
{ tag: "span", ref: "eText", cls: "ag-column-drop-cell-text", attrs: { "aria-hidden": "true" } },
sortSvc ? { tag: "ag-sort-indicator", ref: "eSortIndicator" } : void 0,
{ tag: "span", ref: "eButton", cls: "ag-column-drop-cell-button", role: "presentation" }
]
};
if (sortSvc) {
this.agComponents = [sortSvc.getSortIndicatorSelector()];
}
this.displayName = colNames.getDisplayNameForColumn(this.column, "columnDrop");
super.postConstruct();
if (sortSvc) {
this.setupSort();
this.addManagedEventListeners({
sortChanged: () => {
this.setupAria();
}
});
}
if (this.isGroupingZone()) {
this.addManagedPropertyListener("groupLockGroupColumns", () => {
this.refreshRemove();
this.refreshDraggable();
this.setupAria();
});
}
}
getItem() {
return this.column;
}
getDisplayName() {
return this.displayName;
}
getTooltip() {
return this.column.getColDef().headerTooltip;
}
addAdditionalAriaInstructions(ariaInstructions, translate) {
const isSortSuppressed = this.gos.get("rowGroupPanelSuppressSort");
const isFunctionsReadOnly = this.gos.get("functionsReadOnly");
if (this.isAggregationZone() && !isFunctionsReadOnly) {
const aggregationMenuAria = translate(
"ariaDropZoneColumnValueItemDescription",
"Press ENTER to change the aggregation type"
);
ariaInstructions.push(aggregationMenuAria);
}
if (this.isGroupingZone() && this.column.isSortable() && !isSortSuppressed) {
const sortProgressAria = translate("ariaDropZoneColumnGroupItemDescription", "Press ENTER to sort");
ariaInstructions.push(sortProgressAria);
}
super.addAdditionalAriaInstructions(ariaInstructions, translate);
}
isMovable() {
return this.isDraggable();
}
isDraggable() {
return this.isReadOnly();
}
isRemovable() {
return this.isReadOnly();
}
isReadOnly() {
return !this.isGroupingAndLocked() && !this.gos.get("functionsReadOnly");
}
getAriaDisplayName() {
const translate = this.getLocaleTextFunc();
const { name, aggFuncName } = this.getColumnAndAggFuncName();
const aggSeparator = translate("ariaDropZoneColumnComponentAggFuncSeparator", " of ");
const sortDirection = {
asc: translate("ariaDropZoneColumnComponentSortAscending", "ascending"),
desc: translate("ariaDropZoneColumnComponentSortDescending", "descending")
};
const columnSort = this.column.getSort();
const isSortSuppressed = this.gos.get("rowGroupPanelSuppressSort");
return [
aggFuncName && `${aggFuncName}${aggSeparator}`,
name,
this.isGroupingZone() && !isSortSuppressed && columnSort && `, ${sortDirection[columnSort]}`
].filter((part) => !!part).join("");
}
getColumnAndAggFuncName() {
const name = this.displayName;
let aggFuncName = "";
if (this.isAggregationZone()) {
const aggFunc = this.column.getAggFunc();
const aggFuncString = typeof aggFunc === "string" ? aggFunc : "agg";
const localeTextFunc = this.getLocaleTextFunc();
aggFuncName = localeTextFunc(aggFuncString, aggFuncString);
}
return { name, aggFuncName };
}
setupSort() {
if (!this.column.isSortable() || !this.isGroupingZone()) {
return;
}
if (!this.gos.get("rowGroupPanelSuppressSort")) {
this.eSortIndicator.setupSort(this.column, true);
const performSort = (event) => {
event.preventDefault();
this.beans.sortSvc.progressSortFromEvent(this.column, event);
};
this.addGuiEventListener("click", performSort);
this.addGuiEventListener("keydown", (e) => {
const isEnter = e.key === import_ag_grid_community70.KeyCode.ENTER;
if (isEnter && this.isGroupingZone()) {
performSort(e);
}
});
}
}
getDefaultIconName() {
return "hide";
}
createGetDragItem() {
const { column } = this;
return () => {
const visibleState = {};
visibleState[column.getId()] = column.isVisible();
return {
columns: [column],
visibleState
};
};
}
setupComponents() {
super.setupComponents();
if (this.isAggregationZone() && !this.gos.get("functionsReadOnly")) {
this.addGuiEventListener("click", this.onShowAggFuncSelection.bind(this));
}
}
onKeyDown(e) {
super.onKeyDown(e);
const isEnter = e.key === import_ag_grid_community70.KeyCode.ENTER;
if (isEnter && this.isAggregationZone() && !this.gos.get("functionsReadOnly")) {
e.preventDefault();
this.onShowAggFuncSelection();
}
}
getDisplayValue() {
const { name, aggFuncName } = this.getColumnAndAggFuncName();
return this.isAggregationZone() ? `${aggFuncName}(${name})` : name;
}
onShowAggFuncSelection() {
if (this.popupShowing) {
return;
}
this.popupShowing = true;
const { aggFuncSvc, popupSvc } = this.beans;
const virtualList = new VirtualList({ cssIdentifier: "select-agg-func" });
const rows = aggFuncSvc.getFuncNames(this.column);
const eGui = this.getGui();
const virtualListGui = virtualList.getGui();
virtualList.setModel({
getRow: function(index) {
return rows[index];
},
getRowCount: function() {
return rows.length;
}
});
this.createBean(virtualList);
const ePopup = (0, import_ag_grid_community70._createElement)({ tag: "div", cls: "ag-select-agg-func-popup" });
ePopup.style.top = "0px";
ePopup.style.left = "0px";
ePopup.appendChild(virtualListGui);
ePopup.style.width = `${eGui.clientWidth}px`;
const [focusoutListener] = this.addManagedElementListeners(ePopup, {
focusout: (e) => {
if (!ePopup.contains(e.relatedTarget) && addPopupRes) {
addPopupRes.hideFunc();
}
}
});
const popupHiddenFunc = (callbackEvent) => {
this.destroyBean(virtualList);
this.popupShowing = false;
if (callbackEvent?.key === "Escape") {
eGui.focus();
}
if (focusoutListener) {
focusoutListener();
}
};
const translate = this.getLocaleTextFunc();
const addPopupRes = popupSvc.addPopup({
modal: true,
eChild: ePopup,
closeOnEsc: true,
closedCallback: popupHiddenFunc,
ariaLabel: translate("ariaLabelAggregationFunction", "Aggregation Function")
});
if (addPopupRes) {
virtualList.setComponentCreator(this.createAggSelect.bind(this, addPopupRes.hideFunc));
}
virtualList.addGuiEventListener("keydown", (e) => {
if (e.key === import_ag_grid_community70.KeyCode.ENTER || e.key === import_ag_grid_community70.KeyCode.SPACE) {
const row = virtualList.getLastFocusedRow();
if (row == null) {
return;
}
const comp = virtualList.getComponentAt(row);
if (comp) {
comp.selectItem();
}
}
});
popupSvc.positionPopupByComponent({
type: "aggFuncSelect",
eventSource: eGui,
ePopup,
keepWithinBounds: true,
column: this.column,
position: "under"
});
virtualList.refresh();
let rowToFocus = rows.findIndex((r) => r === this.column.getAggFunc());
if (rowToFocus === -1) {
rowToFocus = 0;
}
virtualList.focusRow(rowToFocus);
}
createAggSelect(hidePopup, value) {
const itemSelected = () => {
hidePopup();
this.getGui().focus();
this.beans.valueColsSvc?.setColumnAggFunc?.(this.column, value, "toolPanelDragAndDrop");
};
const localeTextFunc = this.getLocaleTextFunc();
const aggFuncString = value.toString();
const aggFuncStringTranslated = localeTextFunc(aggFuncString, aggFuncString);
const comp = new AggItemComp(itemSelected, aggFuncStringTranslated);
return comp;
}
isGroupingAndLocked() {
return this.isGroupingZone() && isRowGroupColLocked(this.column, this.beans);
}
isAggregationZone() {
return this.dropZonePurpose === "aggregation";
}
isGroupingZone() {
return this.dropZonePurpose === "rowGroup";
}
getDragSourceType() {
return import_ag_grid_community70.DragSourceType.ToolPanel;
}
destroy() {
super.destroy();
this.column = null;
}
};
var AggItemComp = class extends import_ag_grid_community70.Component {
constructor(itemSelected, value) {
super({ tag: "div", cls: "ag-select-agg-func-item", children: value });
this.selectItem = itemSelected;
this.addGuiEventListener("click", this.selectItem);
}
};
// packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/baseDropZonePanel.ts
var BaseDropZonePanel = class extends PillDropZonePanel {
constructor(horizontal, dropZonePurpose) {
super(horizontal);
this.dropZonePurpose = dropZonePurpose;
this.addElementClasses(this.getGui(), this.dropZonePurpose.toLowerCase());
}
init(params) {
super.init(params);
this.addManagedEventListeners({ newColumnsLoaded: this.refreshGui.bind(this) });
this.addManagedPropertyListeners(
["functionsReadOnly", "rowGroupPanelSuppressSort", "groupLockGroupColumns"],
this.refreshGui.bind(this)
);
}
getItems(dragItem) {
return dragItem.columns ?? [];
}
isInterestedIn(type) {
return type === import_ag_grid_community71.DragSourceType.HeaderCell || type === import_ag_grid_community71.DragSourceType.ToolPanel;
}
minimumAllowedNewInsertIndex() {
const { gos, rowGroupColsSvc } = this.beans;
const numberOfLockedCols = gos.get("groupLockGroupColumns");
const numberOfGroupCols = rowGroupColsSvc?.columns.length ?? 0;
if (numberOfLockedCols === -1) {
return numberOfGroupCols;
}
return Math.min(numberOfLockedCols, numberOfGroupCols);
}
showOrHideColumnOnExit(draggingEvent) {
return this.isRowGroupPanel() && (0, import_ag_grid_community71._shouldUpdateColVisibilityAfterGroup)(this.gos, true) && !draggingEvent.fromNudge;
}
handleDragEnterEnd(draggingEvent) {
const hideColumnOnExit = this.showOrHideColumnOnExit(draggingEvent);
if (hideColumnOnExit) {
const dragItem = draggingEvent.dragSource.getDragItem();
const columns = dragItem.columns;
this.setColumnsVisible(columns, false, "uiColumnDragged");
}
}
handleDragLeaveEnd(draggingEvent) {
const showColumnOnExit = this.showOrHideColumnOnExit(draggingEvent);
if (showColumnOnExit) {
const dragItem = draggingEvent.dragSource.getDragItem();
this.setColumnsVisible(dragItem.columns, true, "uiColumnDragged");
}
}
setColumnsVisible(columns, visible, source) {
if (columns) {
const allowedCols = columns.filter((c) => !c.getColDef().lockVisible);
this.beans.colModel.setColsVisible(allowedCols, visible, source);
}
}
isRowGroupPanel() {
return this.dropZonePurpose === "rowGroup";
}
createPillComponent(column, dropTarget, ghost, horizontal) {
return new DropZoneColumnComp(column, dropTarget, ghost, this.dropZonePurpose, horizontal);
}
};
// packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/pivotDropZonePanel.ts
var PivotDropZonePanel = class extends BaseDropZonePanel {
constructor(horizontal) {
super(horizontal, "pivot");
}
postConstruct() {
const localeTextFunc = this.getLocaleTextFunc();
const emptyMessage = localeTextFunc("pivotColumnsEmptyMessage", "Drag here to set column labels");
const title = localeTextFunc("pivots", "Column Labels");
super.init({
icon: (0, import_ag_grid_community72._createIconNoSpan)("pivotPanel", this.beans, null),
emptyMessage,
title
});
this.addManagedEventListeners({
newColumnsLoaded: this.refresh.bind(this),
columnPivotChanged: this.refresh.bind(this),
columnPivotModeChanged: this.checkVisibility.bind(this)
});
this.refresh();
}
getAriaLabel() {
const translate = this.getLocaleTextFunc();
const label = translate("ariaPivotDropZonePanelLabel", "Column Labels");
return label;
}
refresh() {
this.checkVisibility();
this.refreshGui();
}
checkVisibility() {
const colModel = this.beans.colModel;
const pivotMode = colModel.isPivotMode();
if (this.horizontal) {
switch (this.gos.get("pivotPanelShow")) {
case "always":
this.setDisplayed(pivotMode);
break;
case "onlyWhenPivoting": {
const pivotActive = colModel.isPivotActive();
this.setDisplayed(pivotMode && pivotActive);
break;
}
default:
this.setDisplayed(false);
break;
}
} else {
this.setDisplayed(pivotMode);
}
}
isItemDroppable(column, draggingEvent) {
if (this.gos.get("functionsReadOnly") || !column.isPrimary()) {
return false;
}
return column.isAllowPivot() && (!column.isPivotActive() || this.isSourceEventFromTarget(draggingEvent));
}
updateItems(columns) {
this.beans.pivotColsSvc?.setColumns(columns, "toolPanelUi");
}
getIconName() {
return this.isPotentialDndItems() ? "pivot" : "notAllowed";
}
getExistingItems() {
return this.beans.pivotColsSvc?.columns ?? [];
}
};
// packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/rowGroupDropZonePanel.ts
var import_ag_grid_community73 = require("ag-grid-community");
var RowGroupDropZonePanel = class extends BaseDropZonePanel {
constructor(horizontal) {
super(horizontal, "rowGroup");
}
postConstruct() {
const localeTextFunc = this.getLocaleTextFunc();
const emptyMessage = localeTextFunc("rowGroupColumnsEmptyMessage", "Drag here to set row groups");
const title = localeTextFunc("groups", "Row Groups");
super.init({
icon: (0, import_ag_grid_community73._createIconNoSpan)("rowGroupPanel", this.beans, null),
emptyMessage,
title
});
this.addManagedEventListeners({ columnRowGroupChanged: this.refreshGui.bind(this) });
}
getAriaLabel() {
const translate = this.getLocaleTextFunc();
const label = translate("ariaRowGroupDropZonePanelLabel", "Row Groups");
return label;
}
isItemDroppable(column, draggingEvent) {
if (this.gos.get("functionsReadOnly") || !column.isPrimary() || column.colDef.showRowGroup) {
return false;
}
return column.isAllowRowGroup() && (!column.isRowGroupActive() || this.isSourceEventFromTarget(draggingEvent));
}
updateItems(columns) {
this.beans.rowGroupColsSvc?.setColumns(columns, "toolPanelUi");
}
getIconName() {
return this.isPotentialDndItems() ? "group" : "notAllowed";
}
getExistingItems() {
return this.beans.rowGroupColsSvc?.columns ?? [];
}
};
// packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/valueDropZonePanel.ts
var import_ag_grid_community74 = require("ag-grid-community");
var ValuesDropZonePanel = class extends BaseDropZonePanel {
constructor(horizontal) {
super(horizontal, "aggregation");
}
postConstruct() {
const localeTextFunc = this.getLocaleTextFunc();
const emptyMessage = localeTextFunc("valueColumnsEmptyMessage", "Drag here to aggregate");
const title = localeTextFunc("values", "Values");
super.init({
icon: (0, import_ag_grid_community74._createIconNoSpan)("valuePanel", this.beans, null),
emptyMessage,
title
});
this.addManagedEventListeners({ columnValueChanged: this.refreshGui.bind(this) });
}
getAriaLabel() {
const translate = this.getLocaleTextFunc();
const label = translate("ariaValuesDropZonePanelLabel", "Values");
return label;
}
getIconName() {
return this.isPotentialDndItems() ? "aggregate" : "notAllowed";
}
isItemDroppable(column, draggingEvent) {
if (this.gos.get("functionsReadOnly") || !column.isPrimary()) {
return false;
}
return column.isAllowValue() && (!column.isValueActive() || this.isSourceEventFromTarget(draggingEvent));
}
updateItems(columns) {
this.beans.valueColsSvc?.setColumns(columns, "toolPanelUi");
}
getExistingItems() {
return this.beans.valueColsSvc?.columns ?? [];
}
};
// packages/ag-grid-enterprise/src/columnToolPanel/pivotModePanel.ts
var import_ag_grid_community75 = require("ag-grid-community");
var PivotModePanelElement = {
tag: "div",
cls: "ag-pivot-mode-panel",
children: [
{
tag: "ag-toggle-button",
ref: "cbPivotMode",
cls: "ag-pivot-mode-select"
}
]
};
var PivotModePanel = class extends import_ag_grid_community75.Component {
constructor() {
super(...arguments);
this.cbPivotMode = import_ag_grid_community75.RefPlaceholder;
}
postConstruct() {
this.setTemplate(PivotModePanelElement, [import_ag_grid_community75.AgToggleButtonSelector]);
const cbPivotMode = this.cbPivotMode;
const { colModel, ctrlsSvc, gos } = this.beans;
cbPivotMode.setValue(colModel.isPivotMode());
const localeTextFunc = this.getLocaleTextFunc();
cbPivotMode.setLabel(localeTextFunc("pivotMode", "Pivot Mode"));
const onBtPivotMode = () => {
const newValue = !!cbPivotMode.getValue();
if (newValue !== colModel.isPivotMode()) {
gos.updateGridOptions({ options: { pivotMode: newValue }, source: "toolPanelUi" });
ctrlsSvc.getHeaderRowContainerCtrls().forEach((c) => c.refresh());
}
};
const onPivotModeChanged = () => {
const pivotModeActive = colModel.isPivotMode();
cbPivotMode.setValue(pivotModeActive);
};
this.addManagedListeners(cbPivotMode, { fieldValueChanged: onBtPivotMode });
this.addManagedEventListeners({
newColumnsLoaded: onPivotModeChanged,
columnPivotModeChanged: onPivotModeChanged
});
}
};
// packages/ag-grid-enterprise/src/columnToolPanel/columnToolPanelFactory.ts
var ColumnToolPanelFactory = class extends import_ag_grid_community76.BeanStub {
constructor() {
super(...arguments);
this.beanName = "colToolPanelFactory";
}
setPanelVisible(existingPanel, visible, createFunc) {
if (existingPanel) {
existingPanel.setDisplayed(visible);
} else if (visible) {
existingPanel = createFunc();
}
return existingPanel;
}
createRowGroupPanel(parent, destroyFuncs) {
return this.createPanel(parent, destroyFuncs, new RowGroupDropZonePanel(false));
}
createValuesPanel(parent, destroyFuncs) {
return this.createPanel(parent, destroyFuncs, new ValuesDropZonePanel(false));
}
createPivotPanel(parent, destroyFuncs) {
return this.createPanel(parent, destroyFuncs, new PivotDropZonePanel(false));
}
createPivotModePanel(parent, destroyFuncs, prepend) {
return this.createPanel(parent, destroyFuncs, new PivotModePanel(), prepend);
}
createPanel(parent, destroyFuncs, panel, prepend) {
panel = parent.createBean(panel);
destroyFuncs.push(() => parent.destroyBean(panel));
if (prepend) {
parent.prependChild(panel);
} else {
parent.appendChild(panel);
}
return panel;
}
};
// packages/ag-grid-enterprise/src/columnToolPanel/columnsToolPanelModule.ts
var ColumnsToolPanelModule = {
moduleName: "ColumnsToolPanel",
version: VERSION,
beans: [ColumnToolPanelFactory],
userComponents: { agColumnsToolPanel: ColumnToolPanel },
icons: {
ensureColumnVisible: "column-arrow",
// column tool panel tab
columnsToolPanel: "columns",
// "Group by {column-name}" item in column header menu
menuAddRowGroup: "group",
// "Un-Group by {column-name}" item in column header menu
menuRemoveRowGroup: "group",
// 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",
// column tool panel column group contracted (click to expand)
columnSelectClosed: "tree-closed",
// column 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"
},
dependsOn: [
EnterpriseCoreModule,
SideBarModule,
import_ag_grid_community77._ColumnMoveModule,
import_ag_grid_community77._SharedDragAndDropModule,
import_ag_grid_community77._PopupModule,
MenuItemModule
]
};
// packages/ag-grid-enterprise/src/menu/menuModule.ts
var import_ag_grid_community86 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/menu/chartMenuItemMapper.ts
var import_ag_grid_community78 = require("ag-grid-community");
var ChartMenuItemMapper = class extends import_ag_grid_community78.BeanStub {
constructor() {
super(...arguments);
this.beanName = "chartMenuItemMapper";
}
getChartItems(key) {
const beans = this.beans;
const chartSvc = beans.chartSvc;
const isPivot = key === "pivotChart";
if (!chartSvc) {
return null;
}
const getLocaleTextFunc = this.getLocaleTextFunc.bind(this);
const builder = isPivot ? new PivotMenuItemMapper(beans, chartSvc, getLocaleTextFunc) : new RangeMenuItemMapper(beans, chartSvc, getLocaleTextFunc);
const isEnterprise = chartSvc.isEnterprise();
let topLevelMenuItem = builder.getMenuItem();
if (topLevelMenuItem && topLevelMenuItem.subMenu && !isEnterprise) {
const filterEnterpriseItems = (m) => ({
...m,
subMenu: m.subMenu?.filter((menu) => !menu._enterprise).map((menu) => filterEnterpriseItems(menu))
});
topLevelMenuItem = filterEnterpriseItems(topLevelMenuItem);
}
const chartGroupsDef = this.gos.get("chartToolPanelsDef")?.settingsPanel?.chartGroupsDef;
if (chartGroupsDef) {
topLevelMenuItem = this.filterAndOrderChartMenu(
topLevelMenuItem,
chartGroupsDef,
builder.getConfigLookup()
);
}
return this.cleanInternals(topLevelMenuItem);
}
// Remove our internal _key and _enterprise properties so this does not leak out of the class on the menu items.
cleanInternals(menuItem) {
if (!menuItem) {
return menuItem;
}
const removeKeys = (m) => {
delete m?._key;
delete m?._enterprise;
m?.subMenu?.forEach((s) => removeKeys(s));
return m;
};
return removeKeys(menuItem);
}
buildLookup(menuItem) {
const itemLookup = {};
const addItem = (item) => {
itemLookup[item._key] = item;
if (item.subMenu) {
item.subMenu.forEach((s) => addItem(s));
}
};
addItem(menuItem);
return itemLookup;
}
/**
* Make the MenuItem match the charts provided and their ordering on the ChartGroupsDef config object as provided by the user.
*/
filterAndOrderChartMenu(topLevelMenuItem, chartGroupsDef, configLookup) {
const menuItemLookup = this.buildLookup(topLevelMenuItem);
const orderedAndFiltered = { ...topLevelMenuItem, subMenu: [] };
for (const group of Object.keys(chartGroupsDef)) {
const chartTypes = chartGroupsDef[group];
const chartConfigGroup = configLookup[group];
if (chartConfigGroup === null)
continue;
if (chartConfigGroup == void 0) {
(0, import_ag_grid_community78._warn)(173, { group });
continue;
}
const menuItem = menuItemLookup[chartConfigGroup._key];
if (menuItem) {
if (menuItem.subMenu) {
const subMenus = chartTypes.map((chartType) => {
const itemKey = chartConfigGroup[chartType];
if (itemKey == void 0) {
(0, import_ag_grid_community78._warn)(174, { group, chartType });
return void 0;
}
return menuItemLookup[itemKey];
}).filter((s) => s !== void 0);
if (subMenus.length > 0) {
menuItem.subMenu = subMenus;
orderedAndFiltered.subMenu?.push(menuItem);
}
} else {
orderedAndFiltered.subMenu?.push(menuItem);
}
}
}
if (orderedAndFiltered.subMenu?.length == 0) {
return null;
}
return orderedAndFiltered;
}
};
var PivotMenuItemMapper = class {
constructor(beans, chartSvc, getLocaleTextFunc) {
this.beans = beans;
this.chartSvc = chartSvc;
this.getLocaleTextFunc = getLocaleTextFunc;
}
getMenuItem() {
const localeTextFunc = this.getLocaleTextFunc();
const getMenuItem = (localeKey, defaultText, chartType, key, enterprise = false) => {
return {
// will have a LRM character appended to ensure correct display in RTL languages
name: localeTextFunc(localeKey, defaultText + "\u200E"),
action: () => this.chartSvc.createPivotChart({ chartType }),
_key: key,
_enterprise: enterprise
};
};
return {
name: localeTextFunc("pivotChart", "Pivot Chart"),
_key: "pivotChart",
subMenu: [
{
_key: "pivotColumnChart",
name: localeTextFunc("columnChart", "Column"),
subMenu: [
getMenuItem("groupedColumn", "Grouped", "groupedColumn", "pivotGroupedColumn"),
getMenuItem("stackedColumn", "Stacked", "stackedColumn", "pivotStackedColumn"),
getMenuItem("normalizedColumn", "100% Stacked", "normalizedColumn", "pivotNormalizedColumn")
]
},
{
_key: "pivotBarChart",
name: localeTextFunc("barChart", "Bar"),
subMenu: [
getMenuItem("groupedBar", "Grouped", "groupedBar", "pivotGroupedBar"),
getMenuItem("stackedBar", "Stacked", "stackedBar", "pivotStackedBar"),
getMenuItem("normalizedBar", "100% Stacked", "normalizedBar", "pivotNormalizedBar")
]
},
{
_key: "pivotPieChart",
name: localeTextFunc("pieChart", "Pie"),
subMenu: [
getMenuItem("pie", "Pie", "pie", "pivotPie"),
getMenuItem("donut", "Donut", "donut", "pivotDonut")
]
},
{
_key: "pivotLineChart",
name: localeTextFunc("lineChart", "Line"),
subMenu: [
getMenuItem("lineChart", "Line", "line", "pivotLineChart"),
getMenuItem("stackedLine", "Stacked", "stackedLine", "pivotStackedLine"),
getMenuItem("normalizedLine", "100% Stacked", "normalizedLine", "pivotNormalizedLine")
]
},
{
_key: "pivotAreaChart",
name: localeTextFunc("areaChart", "Area"),
subMenu: [
getMenuItem("areaChart", "Area", "area", "pivotArea"),
getMenuItem("stackedArea", "Stacked", "stackedArea", "pivotStackedArea"),
getMenuItem("normalizedArea", "100% Stacked", "normalizedArea", "pivotNormalizedArea")
]
},
{
_key: "pivotXYChart",
name: localeTextFunc("xyChart", "X Y (Scatter)"),
subMenu: [
getMenuItem("scatter", "Scatter", "scatter", "pivotScatter"),
getMenuItem("bubble", "Bubble", "bubble", "pivotBubble")
]
},
{
_key: "pivotStatisticalChart",
_enterprise: false,
// histogram chart is available in both community and enterprise distributions
name: localeTextFunc("statisticalChart", "Statistical"),
subMenu: [getMenuItem("histogramChart", "Histogram", "histogram", "pivotHistogram", false)]
},
{
_key: "pivotHierarchicalChart",
_enterprise: true,
name: localeTextFunc("hierarchicalChart", "Hierarchical"),
subMenu: [
getMenuItem("treemapChart", "Treemap", "treemap", "pivotTreemap", true),
getMenuItem("sunburstChart", "Sunburst", "sunburst", "pivotSunburst", true)
]
},
{
_key: "pivotFunnel",
name: localeTextFunc("funnel", "Funnel"),
subMenu: [
getMenuItem("funnel", "Funnel", "funnel", "pivotFunnel"),
getMenuItem("coneFunnel", "Cone Funnel", "coneFunnel", "pivotConeFunnel"),
getMenuItem("pyramid", "Pyramid", "pyramid", "pivotPyramid")
]
},
{
_key: "pivotCombinationChart",
name: localeTextFunc("combinationChart", "Combination"),
subMenu: [
getMenuItem("columnLineCombo", "Column & Line", "columnLineCombo", "pivotColumnLineCombo"),
getMenuItem("AreaColumnCombo", "Area & Column", "areaColumnCombo", "pivotAreaColumnCombo")
]
}
],
icon: (0, import_ag_grid_community78._createIconNoSpan)("chart", this.beans, void 0)
};
}
getConfigLookup() {
return {
columnGroup: {
_key: "pivotColumnChart",
column: "pivotGroupedColumn",
stackedColumn: "pivotStackedColumn",
normalizedColumn: "pivotNormalizedColumn"
},
barGroup: {
_key: "pivotBarChart",
bar: "pivotGroupedBar",
stackedBar: "pivotStackedBar",
normalizedBar: "pivotNormalizedBar"
},
pieGroup: {
_key: "pivotPieChart",
pie: "pivotPie",
donut: "pivotDonut",
doughnut: "pivotDonut"
},
lineGroup: {
_key: "pivotLineChart",
line: "pivotLineChart",
stackedLine: "pivotStackedLine",
normalizedLine: "pivotNormalizedLine"
},
areaGroup: {
_key: "pivotAreaChart",
area: "pivotArea",
stackedArea: "pivotStackedArea",
normalizedArea: "pivotNormalizedArea"
},
scatterGroup: {
_key: "pivotXYChart",
bubble: "pivotBubble",
scatter: "pivotScatter"
},
combinationGroup: {
_key: "pivotCombinationChart",
columnLineCombo: "pivotColumnLineCombo",
areaColumnCombo: "pivotAreaColumnCombo",
customCombo: null
// Not currently supported
},
hierarchicalGroup: {
_key: "pivotHierarchicalChart",
treemap: "pivotTreemap",
sunburst: "pivotSunburst"
},
statisticalGroup: {
_key: "pivotStatisticalChart",
histogram: "pivotHistogram",
// Some statistical charts do not currently support pivot mode
rangeBar: null,
rangeArea: null,
boxPlot: null
},
funnelGroup: {
_key: "pivotFunnel",
funnel: "pivotFunnel",
coneFunnel: "pivotConeFunnel",
pyramid: "pivotPyramid"
},
// Polar charts do not support pivot mode
polarGroup: null,
// Specialized charts do not currently support pivot mode
specializedGroup: null
};
}
};
var RangeMenuItemMapper = class {
constructor(beans, chartSvc, getLocaleTextFunc) {
this.beans = beans;
this.chartSvc = chartSvc;
this.getLocaleTextFunc = getLocaleTextFunc;
}
getMenuItem() {
const localeTextFunc = this.getLocaleTextFunc();
const getMenuItem = (localeKey, defaultText, chartType, key, enterprise = false) => {
return {
name: localeTextFunc(localeKey, defaultText),
action: () => this.chartSvc.createChartFromCurrentRange(chartType),
_key: key,
_enterprise: enterprise
};
};
return {
name: localeTextFunc("chartRange", "Chart Range"),
_key: "chartRange",
subMenu: [
{
name: localeTextFunc("columnChart", "Column"),
subMenu: [
getMenuItem("groupedColumn", "Grouped", "groupedColumn", "rangeGroupedColumn"),
getMenuItem("stackedColumn", "Stacked", "stackedColumn", "rangeStackedColumn"),
getMenuItem("normalizedColumn", "100% Stacked", "normalizedColumn", "rangeNormalizedColumn")
],
_key: "rangeColumnChart"
},
{
name: localeTextFunc("barChart", "Bar"),
subMenu: [
getMenuItem("groupedBar", "Grouped", "groupedBar", "rangeGroupedBar"),
getMenuItem("stackedBar", "Stacked", "stackedBar", "rangeStackedBar"),
getMenuItem("normalizedBar", "100% Stacked", "normalizedBar", "rangeNormalizedBar")
],
_key: "rangeBarChart"
},
{
name: localeTextFunc("pieChart", "Pie"),
subMenu: [
getMenuItem("pie", "Pie", "pie", "rangePie"),
getMenuItem("donut", "Donut", "donut", "rangeDonut")
],
_key: "rangePieChart"
},
{
name: localeTextFunc("lineChart", "Line"),
subMenu: [
getMenuItem("lineChart", "Line", "line", "rangeLineChart"),
getMenuItem("stackedLine", "Stacked", "stackedLine", "rangeStackedLine"),
getMenuItem("normalizedLine", "100% Stacked", "normalizedLine", "rangeNormalizedLine")
],
_key: "rangeLineChart"
},
{
name: localeTextFunc("areaChart", "Area"),
subMenu: [
getMenuItem("areaChart", "Area", "area", "rangeArea"),
getMenuItem("stackedArea", "Stacked", "stackedArea", "rangeStackedArea"),
getMenuItem("normalizedArea", "100% Stacked", "normalizedArea", "rangeNormalizedArea")
],
_key: "rangeAreaChart"
},
{
name: localeTextFunc("xyChart", "X Y (Scatter)"),
subMenu: [
getMenuItem("scatter", "Scatter", "scatter", "rangeScatter"),
getMenuItem("bubble", "Bubble", "bubble", "rangeBubble")
],
_key: "rangeXYChart"
},
{
name: localeTextFunc("polarChart", "Polar"),
subMenu: [
getMenuItem("radarLine", "Radar Line", "radarLine", "rangeRadarLine"),
getMenuItem("radarArea", "Radar Area", "radarArea", "rangeRadarArea"),
getMenuItem("nightingale", "Nightingale", "nightingale", "rangeNightingale"),
getMenuItem("radialColumn", "Radial Column", "radialColumn", "rangeRadialColumn"),
getMenuItem("radialBar", "Radial Bar", "radialBar", "rangeRadialBar")
],
_key: "rangePolarChart",
_enterprise: true
},
{
name: localeTextFunc("statisticalChart", "Statistical"),
subMenu: [
getMenuItem("boxPlot", "Box Plot", "boxPlot", "rangeBoxPlot", true),
getMenuItem("histogramChart", "Histogram", "histogram", "rangeHistogram", false),
getMenuItem("rangeBar", "Range Bar", "rangeBar", "rangeRangeBar", true),
getMenuItem("rangeArea", "Range Area", "rangeArea", "rangeRangeArea", true)
],
_key: "rangeStatisticalChart",
_enterprise: false
// histogram chart is available in both community and enterprise distributions
},
{
name: localeTextFunc("hierarchicalChart", "Hierarchical"),
subMenu: [
getMenuItem("treemap", "Treemap", "treemap", "rangeTreemap"),
getMenuItem("sunburst", "Sunburst", "sunburst", "rangeSunburst")
],
_key: "rangeHierarchicalChart",
_enterprise: true
},
{
name: localeTextFunc("specializedChart", "Specialized"),
subMenu: [
getMenuItem("heatmap", "Heatmap", "heatmap", "rangeHeatmap"),
getMenuItem("waterfall", "Waterfall", "waterfall", "rangeWaterfall")
],
_key: "rangeSpecializedChart",
_enterprise: true
},
{
name: localeTextFunc("funnel", "Funnel"),
subMenu: [
getMenuItem("funnel", "Funnel", "funnel", "rangeFunnel"),
getMenuItem("coneFunnel", "Cone Funnel", "coneFunnel", "rangeConeFunnel"),
getMenuItem("pyramid", "Pyramid", "pyramid", "rangePyramid")
],
_key: "rangeFunnel",
_enterprise: true
},
{
name: localeTextFunc("combinationChart", "Combination"),
subMenu: [
getMenuItem("columnLineCombo", "Column & Line", "columnLineCombo", "rangeColumnLineCombo"),
getMenuItem("AreaColumnCombo", "Area & Column", "areaColumnCombo", "rangeAreaColumnCombo")
],
_key: "rangeCombinationChart"
}
],
icon: (0, import_ag_grid_community78._createIconNoSpan)("chart", this.beans, void 0)
};
}
getConfigLookup() {
return {
columnGroup: {
_key: "rangeColumnChart",
column: "rangeGroupedColumn",
stackedColumn: "rangeStackedColumn",
normalizedColumn: "rangeNormalizedColumn"
},
barGroup: {
_key: "rangeBarChart",
bar: "rangeGroupedBar",
stackedBar: "rangeStackedBar",
normalizedBar: "rangeNormalizedBar"
},
pieGroup: {
_key: "rangePieChart",
pie: "rangePie",
donut: "rangeDonut",
doughnut: "rangeDonut"
},
lineGroup: {
_key: "rangeLineChart",
line: "rangeLineChart",
stackedLine: "rangeStackedLine",
normalizedLine: "rangeNormalizedLine"
},
areaGroup: {
_key: "rangeAreaChart",
area: "rangeArea",
stackedArea: "rangeStackedArea",
normalizedArea: "rangeNormalizedArea"
},
scatterGroup: {
_key: "rangeXYChart",
bubble: "rangeBubble",
scatter: "rangeScatter"
},
polarGroup: {
_key: "rangePolarChart",
radarLine: "rangeRadarLine",
radarArea: "rangeRadarArea",
nightingale: "rangeNightingale",
radialColumn: "rangeRadialColumn",
radialBar: "rangeRadialBar"
},
statisticalGroup: {
_key: "rangeStatisticalChart",
boxPlot: "rangeBoxPlot",
histogram: "rangeHistogram",
rangeBar: "rangeRangeBar",
rangeArea: "rangeRangeArea"
},
hierarchicalGroup: {
_key: "rangeHierarchicalChart",
treemap: "rangeTreemap",
sunburst: "rangeSunburst"
},
specializedGroup: {
_key: "rangeSpecializedChart",
heatmap: "rangeHeatmap",
waterfall: "rangeWaterfall"
},
funnelGroup: {
_key: "rangeFunnel",
funnel: "rangeFunnel",
coneFunnel: "rangeConeFunnel",
pyramid: "rangePyramid"
},
combinationGroup: {
_key: "rangeCombinationChart",
columnLineCombo: "rangeColumnLineCombo",
areaColumnCombo: "rangeAreaColumnCombo",
customCombo: null
// Not currently supported
}
};
}
};
// packages/ag-grid-enterprise/src/menu/columnChooserFactory.ts
var import_ag_grid_community79 = require("ag-grid-community");
var ColumnChooserFactory = class extends import_ag_grid_community79.BeanStub {
constructor() {
super(...arguments);
this.beanName = "colChooserFactory";
}
createColumnSelectPanel(parent, column, draggable, params) {
const columnSelectPanel = parent.createManagedBean(new AgPrimaryCols());
const columnChooserParams = params ?? column?.getColDef().columnChooserParams ?? {};
const {
contractColumnSelection,
suppressColumnExpandAll,
suppressColumnFilter,
suppressColumnSelectAll,
suppressSyncLayoutWithGrid,
columnLayout
} = columnChooserParams;
columnSelectPanel.init(
!!draggable,
(0, import_ag_grid_community79._addGridCommonParams)(this.gos, {
suppressColumnMove: false,
suppressValues: false,
suppressPivots: false,
suppressRowGroups: false,
suppressPivotMode: false,
contractColumnSelection: !!contractColumnSelection,
suppressColumnExpandAll: !!suppressColumnExpandAll,
suppressColumnFilter: !!suppressColumnFilter,
suppressColumnSelectAll: !!suppressColumnSelectAll,
suppressSyncLayoutWithGrid: !!columnLayout || !!suppressSyncLayoutWithGrid,
onStateUpdated: () => {
}
}),
"columnMenu"
);
if (columnLayout) {
columnSelectPanel.setColumnLayout(columnLayout);
}
return columnSelectPanel;
}
showColumnChooser({
column,
chooserParams,
eventSource,
headerPosition: providedHeaderPosition
}) {
this.hideActiveColumnChooser();
const columnSelectPanel = this.createColumnSelectPanel(this, column, true, chooserParams);
const translate = this.getLocaleTextFunc();
const beans = this.beans;
const { visibleCols, focusSvc, menuUtils } = beans;
const columnIndex = visibleCols.allCols.indexOf(column);
const headerPosition = column ? focusSvc.focusedHeader ?? providedHeaderPosition ?? null : null;
this.activeColumnChooserDialog = this.createBean(
new AgDialog({
title: translate("chooseColumns", "Choose Columns"),
component: columnSelectPanel,
width: 300,
height: 300,
resizable: true,
movable: true,
centered: true,
closable: true,
afterGuiAttached: () => {
(0, import_ag_grid_community79._findNextFocusableElement)(beans, columnSelectPanel.getGui())?.focus({
preventScroll: true
});
this.dispatchVisibleChangedEvent(true, column);
},
closedCallback: (event) => {
const eComp = this.activeColumnChooser.getGui();
this.destroyBean(this.activeColumnChooser);
this.activeColumnChooser = void 0;
this.activeColumnChooserDialog = void 0;
this.dispatchVisibleChangedEvent(false, column);
if (column) {
menuUtils.restoreFocusOnClose(
{ column, headerPosition, columnIndex, eventSource },
eComp,
event,
true
);
}
},
postProcessPopupParams: {
type: "columnChooser",
column,
eventSource
}
})
);
this.activeColumnChooser = columnSelectPanel;
}
hideActiveColumnChooser() {
this.destroyBean(this.activeColumnChooserDialog);
}
dispatchVisibleChangedEvent(visible, column) {
this.eventSvc.dispatchEvent({
type: "columnMenuVisibleChanged",
visible,
switchingTab: false,
key: "columnChooser",
column: column ?? null
});
}
};
// packages/ag-grid-enterprise/src/menu/columnMenuFactory.ts
var import_ag_grid_community81 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/menu/menuItemMapper.ts
var import_ag_grid_community80 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/menu/menuItemValidations.ts
var MENU_ITEM_MODULES = {
pinSubMenu: "PinnedColumn",
pinLeft: "PinnedColumn",
pinRight: "PinnedColumn",
clearPinned: "PinnedColumn",
pinRowSubMenu: "PinnedRow",
pinBottom: "PinnedRow",
pinTop: "PinnedRow",
unpinRow: "PinnedRow",
valueAggSubMenu: "SharedAggregation",
autoSizeThis: "ColumnAutoSize",
autoSizeAll: "ColumnAutoSize",
rowGroup: "SharedRowGrouping",
rowUnGroup: "SharedRowGrouping",
resetColumns: "CommunityCore",
expandAll: ["ClientSideRowModelHierarchy", "ServerSideRowModel"],
contractAll: ["ClientSideRowModelHierarchy", "ServerSideRowModel"],
copy: "Clipboard",
copyWithHeaders: "Clipboard",
copyWithGroupHeaders: "Clipboard",
cut: "Clipboard",
paste: "Clipboard",
export: ["CsvExport", "ExcelExport"],
csvExport: "CsvExport",
excelExport: "ExcelExport",
separator: "CommunityCore",
pivotChart: "IntegratedCharts",
chartRange: "IntegratedCharts",
columnFilter: "ColumnFilter",
columnChooser: "ColumnMenu",
sortAscending: "Sort",
sortDescending: "Sort",
sortUnSort: "Sort"
};
function validateMenuItem(gos, key) {
const moduleName4 = MENU_ITEM_MODULES[key];
if (moduleName4) {
gos.assertModuleRegistered(moduleName4, `menu item '${key}'`);
}
}
// packages/ag-grid-enterprise/src/menu/menuItemMapper.ts
var MENU_ITEM_SEPARATOR = "separator";
function _removeRepeatsFromArray(array, object) {
if (!array) {
return;
}
for (let index = array.length - 2; index >= 0; index--) {
const thisOneMatches = array[index] === object;
const nextOneMatches = array[index + 1] === object;
if (thisOneMatches && nextOneMatches) {
array.splice(index + 1, 1);
}
}
}
var MenuItemMapper = class extends import_ag_grid_community80.BeanStub {
constructor() {
super(...arguments);
this.beanName = "menuItemMapper";
}
mapWithStockItems(originalList, column, node, sourceElement, source) {
if (!originalList) {
return [];
}
const resultList = [];
const localeTextFunc = this.getLocaleTextFunc();
const { beans, gos } = this;
const {
pinnedCols,
colAutosize,
aggFuncSvc,
rowGroupColsSvc,
colNames,
colModel,
clipboardSvc,
expansionSvc,
focusSvc,
csvCreator,
excelCreator,
menuSvc,
colChooserFactory,
sortSvc,
chartMenuItemMapper,
valueColsSvc,
pinnedRowModel
} = beans;
const getStockMenuItem = (key, column2, sourceElement2, source2) => {
validateMenuItem(gos, key);
switch (key) {
case "pinSubMenu":
return pinnedCols && column2 ? {
name: localeTextFunc("pinColumn", "Pin Column"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("menuPin", beans, null),
subMenu: ["clearPinned", "pinLeft", "pinRight"]
} : null;
case "pinLeft":
return pinnedCols && column2 ? {
name: localeTextFunc("pinLeft", "Pin Left"),
action: () => pinnedCols.setColsPinned([column2], "left", source2),
checked: !!column2 && column2.isPinnedLeft()
} : null;
case "pinRight":
return pinnedCols && column2 ? {
name: localeTextFunc("pinRight", "Pin Right"),
action: () => pinnedCols.setColsPinned([column2], "right", source2),
checked: !!column2 && column2.isPinnedRight()
} : null;
case "clearPinned":
return pinnedCols && column2 ? {
name: localeTextFunc("noPin", "No Pin"),
action: () => pinnedCols.setColsPinned([column2], null, source2),
checked: !!column2 && !column2.isPinned()
} : null;
case "pinRowSubMenu": {
const enableRowPinning = gos.get("enableRowPinning");
const subMenu = [];
const pinned = node?.rowPinned ?? node?.pinnedSibling?.rowPinned;
if (pinned) {
subMenu.push("unpinRow");
}
if (enableRowPinning && enableRowPinning !== "bottom" && pinned != "top") {
subMenu.push("pinTop");
}
if (enableRowPinning && enableRowPinning !== "top" && pinned != "bottom") {
subMenu.push("pinBottom");
}
return pinnedRowModel?.isManual() ? {
name: localeTextFunc("pinRow", "Pin Row"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("rowPin", beans, column2),
subMenu
} : null;
}
case "pinTop":
return pinnedRowModel?.isManual() ? {
name: localeTextFunc("pinTop", "Pin to Top"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("rowPinTop", beans, column2),
action: ({ node: node2, column: column3 }) => node2 && pinnedRowModel.pinRow(node2, "top", column3)
} : null;
case "pinBottom":
return pinnedRowModel?.isManual() ? {
name: localeTextFunc("pinBottom", "Pin to Bottom"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("rowPinBottom", beans, column2),
action: ({ node: node2, column: column3 }) => node2 && pinnedRowModel.pinRow(node2, "bottom", column3)
} : null;
case "unpinRow":
return pinnedRowModel?.isManual() ? {
name: localeTextFunc("unpinRow", "Unpin Row"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("rowUnpin", beans, column2),
action: ({ node: node2, column: column3 }) => node2 && pinnedRowModel.pinRow(node2, null, column3)
} : null;
case "valueAggSubMenu":
if (aggFuncSvc && valueColsSvc && (column2?.isPrimary() || column2?.getColDef().pivotValueColumn)) {
return {
name: localeTextFunc("valueAggregation", "Value Aggregation"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("menuValue", beans, null),
subMenu: createAggregationSubMenu(column2, aggFuncSvc, valueColsSvc, localeTextFunc),
disabled: gos.get("functionsReadOnly")
};
} else {
return null;
}
case "autoSizeThis":
return colAutosize ? {
name: localeTextFunc("autosizeThisColumn", "Autosize This Column"),
action: () => colAutosize.autoSizeColumn(column2, source2, gos.get("skipHeaderOnAutoSize"))
} : null;
case "autoSizeAll":
return colAutosize ? {
name: localeTextFunc("autosizeAllColumns", "Autosize All Columns"),
action: () => colAutosize.autoSizeAllColumns({
source: source2,
skipHeader: gos.get("skipHeaderOnAutoSize")
})
} : null;
case "rowGroup":
return rowGroupColsSvc ? {
name: localeTextFunc("groupBy", "Group by") + " " + colNames.getDisplayNameForColumn(column2, "header"),
disabled: gos.get("functionsReadOnly") || column2?.isRowGroupActive() || !column2?.getColDef().enableRowGroup,
action: () => rowGroupColsSvc.addColumns([column2], source2),
icon: (0, import_ag_grid_community80._createIconNoSpan)("menuAddRowGroup", beans, null)
} : null;
case "rowUnGroup": {
if (rowGroupColsSvc && gos.isModuleRegistered("SharedRowGrouping")) {
const showRowGroup = column2?.getColDef().showRowGroup;
const lockedGroups = gos.get("groupLockGroupColumns");
let name;
let disabled;
let action;
if (showRowGroup === true) {
name = localeTextFunc("ungroupAll", "Un-Group All");
disabled = gos.get("functionsReadOnly") || lockedGroups === -1 || lockedGroups >= (rowGroupColsSvc.columns.length ?? 0);
action = () => rowGroupColsSvc.setColumns(rowGroupColsSvc.columns.slice(0, lockedGroups), source2);
} else if (typeof showRowGroup === "string") {
const underlyingColumn = colModel.getColDefCol(showRowGroup);
const ungroupByName = underlyingColumn != null ? colNames.getDisplayNameForColumn(underlyingColumn, "header") : showRowGroup;
name = localeTextFunc("ungroupBy", "Un-Group by") + " " + ungroupByName;
disabled = gos.get("functionsReadOnly") || isRowGroupColLocked(underlyingColumn, beans);
action = () => {
rowGroupColsSvc.removeColumns([showRowGroup], source2);
};
} else {
name = localeTextFunc("ungroupBy", "Un-Group by") + " " + colNames.getDisplayNameForColumn(column2, "header");
disabled = gos.get("functionsReadOnly") || !column2?.isRowGroupActive() || !column2?.getColDef().enableRowGroup || isRowGroupColLocked(column2, beans);
action = () => rowGroupColsSvc.removeColumns([column2], source2);
}
return {
name,
disabled,
action,
icon: (0, import_ag_grid_community80._createIconNoSpan)("menuRemoveRowGroup", beans, null)
};
} else {
return null;
}
}
case "resetColumns":
return {
name: localeTextFunc("resetColumns", "Reset Columns"),
action: () => (0, import_ag_grid_community80._resetColumnState)(beans, source2)
};
case "expandAll":
return expansionSvc ? {
name: localeTextFunc("expandAll", "Expand All Row Groups"),
action: () => expansionSvc.expandAll(true)
} : null;
case "contractAll":
return expansionSvc ? {
name: localeTextFunc("collapseAll", "Collapse All Row Groups"),
action: () => expansionSvc.expandAll(false)
} : null;
case "copy":
return clipboardSvc ? {
name: localeTextFunc("copy", "Copy"),
shortcut: localeTextFunc("ctrlC", "Ctrl+C"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("clipboardCopy", beans, null),
action: () => clipboardSvc.copyToClipboard()
} : null;
case "copyWithHeaders":
return clipboardSvc ? {
name: localeTextFunc("copyWithHeaders", "Copy with Headers"),
// shortcut: localeTextFunc('ctrlC','Ctrl+C'),
icon: (0, import_ag_grid_community80._createIconNoSpan)("clipboardCopy", beans, null),
action: () => clipboardSvc.copyToClipboard({ includeHeaders: true })
} : null;
case "copyWithGroupHeaders":
return clipboardSvc ? {
name: localeTextFunc("copyWithGroupHeaders", "Copy with Group Headers"),
// shortcut: localeTextFunc('ctrlC','Ctrl+C'),
icon: (0, import_ag_grid_community80._createIconNoSpan)("clipboardCopy", beans, null),
action: () => clipboardSvc.copyToClipboard({ includeHeaders: true, includeGroupHeaders: true })
} : null;
case "cut":
if (clipboardSvc) {
const focusedCell = focusSvc.getFocusedCell();
const rowNode = focusedCell ? (0, import_ag_grid_community80._getRowNode)(beans, focusedCell) : null;
const isEditable = rowNode ? focusedCell?.column.isCellEditable(rowNode) : false;
return {
name: localeTextFunc("cut", "Cut"),
shortcut: localeTextFunc("ctrlX", "Ctrl+X"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("clipboardCut", beans, null),
disabled: !isEditable || gos.get("suppressCutToClipboard"),
action: () => clipboardSvc.cutToClipboard(void 0, "contextMenu")
};
} else {
return null;
}
case "paste":
return clipboardSvc ? {
name: localeTextFunc("paste", "Paste"),
shortcut: localeTextFunc("ctrlV", "Ctrl+V"),
disabled: true,
icon: (0, import_ag_grid_community80._createIconNoSpan)("clipboardPaste", beans, null),
action: () => clipboardSvc.pasteFromClipboard()
} : null;
case "export": {
const exportSubMenuItems = [];
if (!gos.get("suppressCsvExport") && csvCreator) {
exportSubMenuItems.push("csvExport");
}
if (!gos.get("suppressExcelExport") && excelCreator) {
exportSubMenuItems.push("excelExport");
}
return exportSubMenuItems.length ? {
name: localeTextFunc("export", "Export"),
subMenu: exportSubMenuItems,
icon: (0, import_ag_grid_community80._createIconNoSpan)("save", beans, null)
} : null;
}
case "csvExport":
return csvCreator ? {
name: localeTextFunc("csvExport", "CSV Export"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("csvExport", beans, null),
action: () => csvCreator.exportDataAsCsv()
} : null;
case "excelExport":
return excelCreator ? {
name: localeTextFunc("excelExport", "Excel Export"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("excelExport", beans, null),
action: () => excelCreator.exportDataAsExcel()
} : null;
case "separator":
return key;
case "pivotChart":
case "chartRange":
return chartMenuItemMapper.getChartItems(key);
case "columnFilter":
return menuSvc && column2 ? {
name: localeTextFunc("columnFilter", "Column Filter"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("filter", beans, null),
action: () => menuSvc.showFilterMenu({
column: column2,
buttonElement: sourceElement2(),
containerType: "columnFilter",
positionBy: "button"
})
} : null;
case "columnChooser": {
const headerPosition = focusSvc.focusedHeader;
return colChooserFactory ? {
name: localeTextFunc("columnChooser", "Choose Columns"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("columns", beans, null),
action: () => colChooserFactory.showColumnChooser({
column: column2,
eventSource: sourceElement2(),
headerPosition
})
} : null;
}
case "sortAscending":
return sortSvc ? {
name: localeTextFunc("sortAscending", "Sort Ascending"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("sortAscending", beans, null),
action: () => sortSvc.setSortForColumn(column2, "asc", false, source2)
} : null;
case "sortDescending":
return sortSvc ? {
name: localeTextFunc("sortDescending", "Sort Descending"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("sortDescending", beans, null),
action: () => sortSvc.setSortForColumn(column2, "desc", false, source2)
} : null;
case "sortUnSort":
return sortSvc ? {
name: localeTextFunc("sortUnSort", "Clear Sort"),
icon: (0, import_ag_grid_community80._createIconNoSpan)("sortUnSort", beans, null),
action: () => sortSvc.setSortForColumn(column2, null, false, source2)
} : null;
default: {
(0, import_ag_grid_community80._warn)(176, { key });
return null;
}
}
};
originalList.forEach((menuItemOrString) => {
let result;
if (typeof menuItemOrString === "string") {
result = getStockMenuItem(menuItemOrString, column, sourceElement, source);
} else {
result = { ...menuItemOrString };
}
if (!result) {
return;
}
const resultDef = result;
const { subMenu } = resultDef;
if (subMenu && subMenu instanceof Array) {
resultDef.subMenu = this.mapWithStockItems(
subMenu,
column,
node,
sourceElement,
source
);
}
if (result != null) {
resultList.push(result);
}
});
_removeRepeatsFromArray(resultList, MENU_ITEM_SEPARATOR);
return resultList;
}
};
function createAggregationSubMenu(column, aggFuncSvc, valueColsSvc, localeTextFunc) {
let columnToUse;
if (column.isPrimary()) {
columnToUse = column;
} else {
const pivotValueColumn = column.getColDef().pivotValueColumn;
columnToUse = (0, import_ag_grid_community80._exists)(pivotValueColumn) ? pivotValueColumn : void 0;
}
const result = [];
if (columnToUse) {
const columnIsAlreadyAggValue = columnToUse.isValueActive();
const funcNames = aggFuncSvc.getFuncNames(columnToUse);
result.push({
name: localeTextFunc("noAggregation", "None"),
action: () => {
valueColsSvc.removeColumns([columnToUse], "contextMenu");
valueColsSvc.setColumnAggFunc(columnToUse, void 0, "contextMenu");
},
checked: !columnIsAlreadyAggValue
});
funcNames.forEach((funcName) => {
result.push({
name: localeTextFunc(funcName, aggFuncSvc.getDefaultFuncLabel(funcName)),
action: () => {
valueColsSvc.setColumnAggFunc(columnToUse, funcName, "contextMenu");
valueColsSvc.addColumns([columnToUse], "contextMenu");
},
checked: columnIsAlreadyAggValue && columnToUse.getAggFunc() === funcName
});
});
}
return result;
}
// packages/ag-grid-enterprise/src/menu/columnMenuFactory.ts
var ColumnMenuFactory = class extends import_ag_grid_community81.BeanStub {
constructor() {
super(...arguments);
this.beanName = "colMenuFactory";
}
createMenu(parent, menuItems, column, sourceElement) {
const menuList = parent.createManagedBean(
new AgMenuList(0, {
column: column ?? null,
node: null,
value: null
})
);
const menuItemsMapped = this.beans.menuItemMapper.mapWithStockItems(
menuItems,
column ?? null,
null,
sourceElement,
"columnMenu"
);
menuList.addMenuItems(menuItemsMapped);
return menuList;
}
getMenuItems(column = null, columnGroup = null) {
const defaultItems = this.getDefaultMenuOptions(column);
let result;
const columnMainMenuItems = (column?.getColDef() ?? columnGroup?.getColGroupDef())?.mainMenuItems;
if (Array.isArray(columnMainMenuItems)) {
result = columnMainMenuItems;
} else if (typeof columnMainMenuItems === "function") {
result = columnMainMenuItems(
(0, import_ag_grid_community81._addGridCommonParams)(this.gos, {
column,
columnGroup,
defaultItems
})
);
} else {
const userFunc = this.gos.getCallback("getMainMenuItems");
if (userFunc) {
result = userFunc({
column,
columnGroup,
defaultItems
});
} else {
result = defaultItems;
}
}
_removeRepeatsFromArray(result, MENU_ITEM_SEPARATOR);
return result;
}
getDefaultMenuOptions(column) {
const result = [];
const { beans, gos } = this;
const {
colChooserFactory,
rowGroupColsSvc,
colModel,
expansionSvc,
sortSvc,
menuSvc,
pinnedCols,
aggFuncSvc,
colAutosize
} = beans;
const isLegacyMenuEnabled = (0, import_ag_grid_community81._isLegacyMenuEnabled)(gos);
const addColumnItems = () => {
if (!isLegacyMenuEnabled && colChooserFactory) {
result.push("columnChooser");
}
result.push("resetColumns");
};
if (!column) {
addColumnItems();
return result;
}
const { colDef } = column;
const allowPinning = pinnedCols && !colDef.lockPinned;
const rowGroupCount = rowGroupColsSvc?.columns.length ?? 0;
const doingGrouping = rowGroupCount > 0;
const isPrimary = column.isPrimary();
const allowValueAgg = aggFuncSvc && // if primary, then only allow aggValue if grouping and it's a value columns
isPrimary && doingGrouping && column.isAllowValue() || // secondary columns can always have aggValue, as it means it's a pivot value column
!isPrimary;
if (sortSvc && !isLegacyMenuEnabled && column.isSortable()) {
const sort = column.getSort();
if (sort !== "asc") {
result.push("sortAscending");
}
if (sort !== "desc") {
result.push("sortDescending");
}
if (sort) {
result.push("sortUnSort");
}
result.push(MENU_ITEM_SEPARATOR);
}
if (menuSvc?.isFilterMenuItemEnabled(column)) {
result.push("columnFilter");
result.push(MENU_ITEM_SEPARATOR);
}
if (allowPinning) {
result.push("pinSubMenu");
}
if (allowValueAgg) {
result.push("valueAggSubMenu");
}
if (allowPinning || allowValueAgg) {
result.push(MENU_ITEM_SEPARATOR);
}
if (colAutosize) {
result.push("autoSizeThis");
result.push("autoSizeAll");
result.push(MENU_ITEM_SEPARATOR);
}
if (rowGroupColsSvc && gos.isModuleRegistered("SharedRowGrouping")) {
const numItems = result.length;
const showRowGroup = colDef.showRowGroup;
if (showRowGroup) {
result.push("rowUnGroup");
} else if (column.isAllowRowGroup() && isPrimary) {
if (column.isRowGroupActive()) {
const groupLocked = isRowGroupColLocked(column, beans);
if (!groupLocked) {
result.push("rowUnGroup");
}
} else {
result.push("rowGroup");
}
}
if (result.length > numItems) {
result.push(MENU_ITEM_SEPARATOR);
}
}
addColumnItems();
if (expansionSvc && (0, import_ag_grid_community81._isClientSideRowModel)(gos) && (gos.get("treeData") || rowGroupCount > (colModel.isPivotMode() ? 1 : 0))) {
result.push("expandAll");
result.push("contractAll");
}
return result;
}
};
// packages/ag-grid-enterprise/src/menu/contextMenu.ts
var import_ag_grid_community82 = require("ag-grid-community");
var CSS_MENU = "ag-menu";
var CSS_CONTEXT_MENU_OPEN = "ag-context-menu-open";
var CSS_CONTEXT_MENU_LOADING_ICON = "ag-context-menu-loading-icon";
var ContextMenuService = class extends import_ag_grid_community82.BeanStub {
constructor() {
super(...arguments);
this.beanName = "contextMenuSvc";
this.destroyLoadingSpinner = null;
this.lastPromise = 0;
}
hideActiveMenu() {
this.destroyBean(this.activeMenu);
}
getMenuItems(node, column, value, mouseEvent) {
const defaultMenuOptions = [];
const { clipboardSvc, chartSvc, csvCreator, excelCreator, colModel, rangeSvc, gos } = this.beans;
if ((0, import_ag_grid_community82._exists)(node) && clipboardSvc) {
if (column) {
if (!gos.get("suppressCutToClipboard")) {
defaultMenuOptions.push("cut");
}
defaultMenuOptions.push("copy", "copyWithHeaders", "copyWithGroupHeaders", "paste", "separator");
}
}
if (gos.get("enableCharts") && chartSvc) {
if (colModel.isPivotMode()) {
defaultMenuOptions.push("pivotChart");
}
if (rangeSvc && !rangeSvc.isEmpty()) {
defaultMenuOptions.push("chartRange");
}
}
if ((0, import_ag_grid_community82._exists)(node)) {
const enableRowPinning = gos.get("enableRowPinning");
const isRowPinnable = gos.get("isRowPinnable");
if (enableRowPinning) {
const isGroupTotalRow = node.level > -1 && node.footer;
const isGrandTotalRow = node.level === -1 && node.footer;
const grandTotalRow = (0, import_ag_grid_community82._getGrandTotalRow)(gos);
const isGrandTotalRowFixed = grandTotalRow === "pinnedBottom" || grandTotalRow === "pinnedTop";
if (isGrandTotalRow && !isGrandTotalRowFixed || !isGrandTotalRow && !isGroupTotalRow) {
const pinnable = isRowPinnable?.(node) ?? true;
if (pinnable) {
defaultMenuOptions.push("pinRowSubMenu");
}
}
}
const suppressExcel = gos.get("suppressExcelExport") || !excelCreator;
const suppressCsv = gos.get("suppressCsvExport") || !csvCreator;
const onIPad = (0, import_ag_grid_community82._isIOSUserAgent)();
const anyExport = !onIPad && (!suppressExcel || !suppressCsv);
if (anyExport) {
defaultMenuOptions.push("export");
}
}
const defaultItems = defaultMenuOptions.length ? defaultMenuOptions : void 0;
const columnContextMenuItems = column?.getColDef().contextMenuItems;
if (Array.isArray(columnContextMenuItems)) {
return columnContextMenuItems;
}
if (typeof columnContextMenuItems === "function") {
return columnContextMenuItems(
(0, import_ag_grid_community82._addGridCommonParams)(gos, {
column,
node,
value,
defaultItems,
event: mouseEvent
})
);
}
const userFunc = gos.getCallback("getContextMenuItems");
return userFunc?.({ column, node, value, defaultItems, event: mouseEvent }) ?? defaultMenuOptions;
}
getContextMenuPosition(rowNode, column) {
const rowCtrl = this.getRowCtrl(rowNode);
const eGui = this.getCellGui(rowCtrl, column);
if (!eGui) {
return { x: 0, y: rowCtrl?.getRowYPosition() ?? 0 };
}
const rect = eGui.getBoundingClientRect();
return {
x: rect.x + rect.width / 2,
y: rect.y + rect.height / 2
};
}
showContextMenu(params) {
const rowNode = params.rowNode ?? null;
const column = params.column ?? null;
let { anchorToElement, value, source } = params;
if (rowNode && column && value == null) {
value = this.beans.valueSvc.getValueForDisplay(column, rowNode).value;
}
if (anchorToElement == null) {
anchorToElement = this.getContextMenuAnchorElement(rowNode, column);
}
this.beans.menuUtils.onContextMenu({
mouseEvent: params.mouseEvent ?? null,
touchEvent: params.touchEvent ?? null,
showMenuCallback: (eventOrTouch) => this.showMenu(rowNode, column, value, eventOrTouch, anchorToElement),
source
});
}
handleContextMenuMouseEvent(mouseEvent, touchEvent, rowCtrl, cellCtrl) {
const rowNode = cellCtrl?.rowNode ?? rowCtrl?.rowNode ?? null;
const column = cellCtrl?.column ?? rowCtrl?.findFullWidthInfoForEvent(mouseEvent || touchEvent)?.column ?? null;
const { valueSvc, ctrlsSvc } = this.beans;
const value = column ? valueSvc.getValue(column, rowNode) : null;
const gridBodyCon = ctrlsSvc.getGridBodyCtrl();
const anchorToElement = cellCtrl ? cellCtrl.eGui : gridBodyCon.eGridBody;
this.showContextMenu({
mouseEvent,
touchEvent,
rowNode,
column,
value,
anchorToElement,
source: "ui"
});
}
showMenu(node, column, value, mouseEvent, anchorToElement) {
const menuItems = this.getMenuItems(node, column, value, mouseEvent);
if ((0, import_ag_grid_community82._isPromise)(menuItems)) {
const currentPromise = this.lastPromise + 1;
this.lastPromise = currentPromise;
if (!this.destroyLoadingSpinner) {
this.createLoadingIcon(mouseEvent);
}
menuItems.then((menuItems2) => {
if (this.lastPromise !== currentPromise) {
return;
}
const { target } = mouseEvent;
const isFromFakeEvent = !target;
const shouldShowMenu = (
// check if there are actual menu items to be displayed
menuItems2 && menuItems2.length && // check if the element that triggered the context menu was removed from the DOM
(isFromFakeEvent || (0, import_ag_grid_community82._isVisible)(target)) && // overlay was displayed
!this.beans.overlays?.isExclusive()
);
if (shouldShowMenu) {
this.createContextMenu({ menuItems: menuItems2, node, column, value, mouseEvent, anchorToElement });
}
this.destroyLoadingSpinner?.();
});
return true;
}
if (menuItems === void 0 || !menuItems?.length) {
return false;
}
this.createContextMenu({ menuItems, node, column, value, mouseEvent, anchorToElement });
return true;
}
createLoadingIcon(mouseEvent) {
const { beans } = this;
const translate = this.getLocaleTextFunc();
const loadingIcon = (0, import_ag_grid_community82._createIconNoSpan)("loadingMenuItems", beans);
const wrapperEl = (0, import_ag_grid_community82._createElement)({ tag: "div", cls: CSS_CONTEXT_MENU_LOADING_ICON });
wrapperEl.appendChild(loadingIcon);
const rootNode = (0, import_ag_grid_community82._getRootNode)(beans);
const targetEl = (0, import_ag_grid_community82._getPageBody)(beans);
if (!targetEl) {
(0, import_ag_grid_community82._warn)(54);
return;
}
targetEl.appendChild(wrapperEl);
beans.ariaAnnounce?.announceValue(
translate("ariaLabelLoadingContextMenu", "Loading Context Menu"),
"contextmenu"
);
beans.environment.applyThemeClasses(wrapperEl);
(0, import_ag_grid_community82._anchorElementToMouseMoveEvent)(wrapperEl, mouseEvent, beans);
const mouseMoveCallback = (e) => {
(0, import_ag_grid_community82._anchorElementToMouseMoveEvent)(wrapperEl, e, beans);
};
rootNode.addEventListener("mousemove", mouseMoveCallback);
this.destroyLoadingSpinner = () => {
rootNode.removeEventListener("mousemove", mouseMoveCallback);
targetEl.removeChild(wrapperEl);
this.destroyLoadingSpinner = null;
};
}
createContextMenu(params) {
const { menuItems, node, column, value, mouseEvent, anchorToElement } = params;
const { ctrlsSvc, focusSvc, popupSvc } = this.beans;
const eGridBodyGui = ctrlsSvc.getGridBodyCtrl().eGridBody;
const menu = new ContextMenu(menuItems, column, node, value);
this.createBean(menu);
const eMenuGui = menu.getGui();
if (!column) {
focusSvc.clearFocusedCell();
}
const positionParams = {
column,
rowNode: node,
type: "contextMenu",
mouseEvent,
ePopup: eMenuGui,
// move one pixel away so that accidentally double clicking
// won't show the browser's contextmenu
nudgeY: 1
};
const translate = this.getLocaleTextFunc();
const addPopupRes = popupSvc?.addPopup({
modal: true,
eChild: eMenuGui,
closeOnEsc: true,
closedCallback: (e) => {
(0, import_ag_grid_community82._preserveRangesWhile)(this.beans, () => {
eGridBodyGui.classList.remove(CSS_CONTEXT_MENU_OPEN);
this.destroyBean(menu);
this.dispatchVisibleChangedEvent(false, e === void 0 ? "api" : "ui");
});
},
click: mouseEvent,
positionCallback: () => {
const isRtl = this.gos.get("enableRtl");
popupSvc?.positionPopupUnderMouseEvent({
...positionParams,
nudgeX: isRtl ? (eMenuGui.offsetWidth + 1) * -1 : 1
});
},
// so when browser is scrolled down, or grid is scrolled, context menu stays with cell
anchorToElement,
ariaLabel: translate("ariaLabelContextMenu", "Context Menu")
});
if (addPopupRes) {
eGridBodyGui.classList.add(CSS_CONTEXT_MENU_OPEN);
menu.afterGuiAttached({ container: "contextMenu", hidePopup: addPopupRes.hideFunc });
}
if (this.activeMenu) {
this.hideActiveMenu();
}
this.activeMenu = menu;
menu.addEventListener("destroyed", () => {
if (this.activeMenu === menu) {
this.activeMenu = null;
}
});
if (addPopupRes) {
menu.addEventListener(
"closeMenu",
(e) => addPopupRes.hideFunc({
mouseEvent: e.mouseEvent ?? void 0,
keyboardEvent: e.keyboardEvent ?? void 0,
forceHide: true
})
);
}
const isApi = mouseEvent && mouseEvent instanceof MouseEvent && mouseEvent.type === "mousedown";
this.dispatchVisibleChangedEvent(true, isApi ? "api" : "ui");
}
dispatchVisibleChangedEvent(visible, source = "ui") {
this.eventSvc.dispatchEvent({
type: "contextMenuVisibleChanged",
visible,
source
});
}
getRowCtrl(rowNode) {
const { rowIndex, rowPinned } = rowNode || {};
if (rowIndex == null) {
return;
}
return this.beans.rowRenderer.getRowByPosition({ rowIndex, rowPinned }) || void 0;
}
getCellGui(rowCtrl, column) {
if (!rowCtrl || !column) {
return;
}
const cellCtrl = rowCtrl.getCellCtrl(column);
return cellCtrl?.eGui || void 0;
}
getContextMenuAnchorElement(rowNode, column) {
const gridBodyEl = this.beans.ctrlsSvc.getGridBodyCtrl().eGridBody;
const rowCtrl = this.getRowCtrl(rowNode);
if (!rowCtrl) {
return gridBodyEl;
}
const cellGui = this.getCellGui(rowCtrl, column);
if (cellGui) {
return cellGui;
}
if (rowCtrl.isFullWidth()) {
return rowCtrl.getFullWidthElement();
}
return gridBodyEl;
}
destroy() {
this.destroyLoadingSpinner?.();
super.destroy();
}
};
var ContextMenu = class extends import_ag_grid_community82.Component {
constructor(menuItems, column, node, value) {
super({ tag: "div", cls: CSS_MENU, role: "presentation" });
this.menuItems = menuItems;
this.column = column;
this.node = node;
this.value = value;
this.menuList = null;
this.focusedCell = null;
}
postConstruct() {
const menuList = this.createManagedBean(
new AgMenuList(0, {
column: this.column,
node: this.node,
value: this.value
})
);
const menuItemsMapped = this.beans.menuItemMapper.mapWithStockItems(
this.menuItems,
this.column,
this.node,
() => this.getGui(),
"contextMenu"
);
menuList.addMenuItems(menuItemsMapped);
this.appendChild(menuList);
this.menuList = menuList;
menuList.addEventListener("closeMenu", (e) => this.dispatchLocalEvent(e));
}
afterGuiAttached({ hidePopup }) {
if (hidePopup) {
this.addDestroyFunc(hidePopup);
}
this.focusedCell = this.beans.focusSvc.getFocusedCell();
const menuList = this.menuList;
if (menuList) {
(0, import_ag_grid_community82._preserveRangesWhile)(this.beans, () => (0, import_ag_grid_community82._focusInto)(menuList.getGui()));
}
}
restoreFocusedCell() {
const { beans, focusedCell } = this;
const focusSvc = beans.focusSvc;
const currentFocusedCell = focusSvc.getFocusedCell();
if (currentFocusedCell && focusedCell && (0, import_ag_grid_community82._areCellsEqual)(currentFocusedCell, focusedCell)) {
const { rowIndex, rowPinned, column } = focusedCell;
if ((0, import_ag_grid_community82._isNothingFocused)(beans)) {
focusSvc.setFocusedCell({
rowIndex,
column,
rowPinned,
forceBrowserFocus: true,
preventScrollOnBrowserFocus: !(0, import_ag_grid_community82._isKeyboardMode)()
});
}
}
}
destroy() {
super.destroy();
this.restoreFocusedCell();
}
};
// packages/ag-grid-enterprise/src/menu/enterpriseMenu.ts
var import_ag_grid_community84 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/tabbedLayout.ts
var import_ag_grid_community83 = require("ag-grid-community");
function getTabbedLayoutTemplate(cssClass) {
return {
tag: "div",
cls: `ag-tabs ${cssClass}`,
children: [
{ tag: "div", ref: "eHeader" },
{
tag: "div",
ref: "eBody",
role: "presentation",
cls: `ag-tabs-body ${cssClass ? `${cssClass}-body` : ""}`
}
]
};
}
var TabbedLayout = class extends import_ag_grid_community83.TabGuardComp {
constructor(params) {
super(getTabbedLayoutTemplate(params.cssClass));
this.eHeader = import_ag_grid_community83.RefPlaceholder;
this.eBody = import_ag_grid_community83.RefPlaceholder;
this.items = [];
this.tabbedItemScrollMap = /* @__PURE__ */ new Map();
this.params = params;
}
postConstruct() {
this.setupHeader();
if (this.params.items) {
this.params.items.forEach((item) => this.addItem(item));
}
this.initialiseTabGuard({
onTabKeyDown: this.onTabKeyDown.bind(this),
handleKeyDown: this.handleKeyDown.bind(this),
focusInnerElement: this.focusInnerElement.bind(this),
focusTrapActive: true
});
this.addDestroyFunc(() => this.activeItem?.tabbedItem?.afterDetachedCallback?.());
}
setupHeader() {
const { enableCloseButton, cssClass } = this.params;
const addCssClasses = (el, suffix) => {
el.classList.add(`ag-tabs-${suffix}`);
if (cssClass) {
el.classList.add(`${cssClass}-${suffix}`);
}
};
if (enableCloseButton) {
this.setupCloseButton(addCssClasses);
this.eTabHeader = (0, import_ag_grid_community83._createElement)({ tag: "div", role: "presentation" });
addCssClasses(this.eHeader, "header-wrapper");
this.eHeader.appendChild(this.eTabHeader);
} else {
this.eTabHeader = this.eHeader;
}
(0, import_ag_grid_community83._setAriaRole)(this.eTabHeader, "tablist");
addCssClasses(this.eTabHeader, "header");
}
setupCloseButton(addCssClasses) {
const eCloseButton = (0, import_ag_grid_community83._createElement)({ tag: "button" });
addCssClasses(eCloseButton, "close-button");
const eIcon = (0, import_ag_grid_community83._createIconNoSpan)("close", this.beans);
(0, import_ag_grid_community83._setAriaLabel)(eCloseButton, this.params.closeButtonAriaLabel);
eCloseButton.appendChild(eIcon);
this.addManagedElementListeners(eCloseButton, { click: () => this.params.onCloseClicked?.() });
const eCloseButtonWrapper = (0, import_ag_grid_community83._createElement)({ tag: "div", role: "presentation" });
addCssClasses(eCloseButtonWrapper, "close-button-wrapper");
eCloseButtonWrapper.appendChild(eCloseButton);
this.eHeader.appendChild(eCloseButtonWrapper);
this.eCloseButton = eCloseButton;
}
handleKeyDown(e) {
switch (e.key) {
case import_ag_grid_community83.KeyCode.RIGHT:
case import_ag_grid_community83.KeyCode.LEFT: {
if (!this.eTabHeader.contains((0, import_ag_grid_community83._getActiveDomElement)(this.beans))) {
return;
}
const isRightKey = e.key === import_ag_grid_community83.KeyCode.RIGHT;
const isRtl = this.gos.get("enableRtl");
const currentPosition = this.items.indexOf(this.activeItem);
const nextPosition = isRightKey !== isRtl ? Math.min(currentPosition + 1, this.items.length - 1) : Math.max(currentPosition - 1, 0);
if (currentPosition === nextPosition) {
return;
}
e.preventDefault();
const nextItem = this.items[nextPosition];
this.showItemWrapper(nextItem);
nextItem.eHeaderButton.focus();
break;
}
case import_ag_grid_community83.KeyCode.UP:
case import_ag_grid_community83.KeyCode.DOWN:
e.stopPropagation();
break;
}
}
onTabKeyDown(e) {
if (e.defaultPrevented) {
return;
}
const { beans, eHeader, eBody, activeItem, params } = this;
const { suppressTrapFocus, enableCloseButton } = params;
const activeElement = (0, import_ag_grid_community83._getActiveDomElement)(beans);
const target = e.target;
const backwards = e.shiftKey;
if (eHeader.contains(activeElement)) {
e.preventDefault();
if (enableCloseButton && backwards && !this.eCloseButton?.contains(activeElement)) {
this.eCloseButton?.focus();
} else if (suppressTrapFocus && backwards) {
findFocusableElementBeforeTabGuard((0, import_ag_grid_community83._getDocument)(beans).body, target)?.focus();
} else {
this.focusBody(e.shiftKey);
}
return;
}
let nextEl = null;
if (isTargetUnderManagedComponent(eBody, target)) {
if (backwards) {
nextEl = findFocusableElementBeforeTabGuard(eBody, target);
}
if (!nextEl && !suppressTrapFocus) {
nextEl = activeItem.eHeaderButton;
}
}
if (!nextEl && eBody.contains(activeElement)) {
nextEl = (0, import_ag_grid_community83._findNextFocusableElement)(beans, eBody, false, backwards);
if (!nextEl) {
if (suppressTrapFocus && !backwards) {
this.forceFocusOutOfContainer(backwards);
} else if (enableCloseButton && !backwards) {
e.preventDefault();
this.eCloseButton?.focus();
} else {
e.preventDefault();
this.focusHeader();
}
return;
}
}
if (nextEl) {
e.preventDefault();
nextEl.focus();
}
}
focusInnerElement(fromBottom) {
if (fromBottom) {
return this.focusBody(true);
} else {
this.focusHeader();
return true;
}
}
focusHeader(preventScroll) {
this.activeItem.eHeaderButton.focus({ preventScroll });
}
focusBody(fromBottom) {
return (0, import_ag_grid_community83._focusInto)(this.eBody, fromBottom);
}
setAfterAttachedParams(params) {
this.afterAttachedParams = params;
}
showFirstItem() {
if (this.items.length > 0) {
this.showItemWrapper(this.items[0]);
}
}
addItem(item) {
const eHeaderButton = (0, import_ag_grid_community83._createElement)({
tag: "span",
cls: "ag-tab",
role: "tab",
attrs: { tabindex: "-1" }
});
eHeaderButton.appendChild(item.title);
this.eTabHeader.appendChild(eHeaderButton);
(0, import_ag_grid_community83._setAriaLabel)(eHeaderButton, item.titleLabel);
const wrapper = {
tabbedItem: item,
eHeaderButton
};
this.items.push(wrapper);
eHeaderButton.addEventListener("click", this.showItemWrapper.bind(this, wrapper));
}
showItem(tabbedItem) {
const itemWrapper = this.items.find((wrapper) => wrapper.tabbedItem === tabbedItem);
if (itemWrapper) {
this.showItemWrapper(itemWrapper);
}
}
showItemWrapper(wrapper) {
const { tabbedItem, eHeaderButton } = wrapper;
this.params.onItemClicked?.({ item: tabbedItem });
if (this.activeItem === wrapper) {
this.params.onActiveItemClicked?.();
return;
}
if (this.lastScrollListener) {
this.lastScrollListener = this.lastScrollListener();
}
(0, import_ag_grid_community83._clearElement)(this.eBody);
tabbedItem.bodyPromise.then((body) => {
this.eBody.appendChild(body);
const onlyUnmanaged = !(0, import_ag_grid_community83._isKeyboardMode)();
if (!this.params.suppressFocusBodyOnOpen) {
(0, import_ag_grid_community83._focusInto)(this.eBody, false, onlyUnmanaged);
}
if (tabbedItem.afterAttachedCallback) {
tabbedItem.afterAttachedCallback(this.afterAttachedParams);
}
if (this.params.keepScrollPosition) {
const scrollableContainer = tabbedItem.getScrollableContainer && tabbedItem.getScrollableContainer() || body;
[this.lastScrollListener] = this.addManagedElementListeners(scrollableContainer, {
scroll: () => {
this.tabbedItemScrollMap.set(tabbedItem.name, scrollableContainer.scrollTop);
}
});
const scrollPosition = this.tabbedItemScrollMap.get(tabbedItem.name);
if (scrollPosition !== void 0) {
setTimeout(() => {
scrollableContainer.scrollTop = scrollPosition;
}, 0);
}
}
});
if (this.activeItem) {
this.activeItem.eHeaderButton.classList.remove("ag-tab-selected");
this.activeItem.tabbedItem.afterDetachedCallback?.();
}
eHeaderButton.classList.add("ag-tab-selected");
this.activeItem = wrapper;
}
};
// packages/ag-grid-enterprise/src/menu/enterpriseMenu.ts
var TAB_FILTER = "filterMenuTab";
var TAB_GENERAL = "generalMenuTab";
var TAB_COLUMNS = "columnsMenuTab";
var TABS_DEFAULT = [TAB_GENERAL, TAB_FILTER, TAB_COLUMNS];
var EnterpriseMenuFactory = class extends import_ag_grid_community84.BeanStub {
constructor() {
super(...arguments);
this.beanName = "enterpriseMenuFactory";
}
hideActiveMenu() {
this.destroyBean(this.activeMenu);
}
showMenuAfterMouseEvent(columnOrGroup, mouseEvent, containerType, onClosedCallback, filtersOnly) {
const { column, columnGroup } = this.splitColumnOrGroup(columnOrGroup);
const defaultTab = filtersOnly ? "filterMenuTab" : void 0;
this.showMenu(
column,
columnGroup,
(menu) => {
const ePopup = menu.getGui();
this.beans.popupSvc.positionPopupUnderMouseEvent({
type: containerType,
column,
mouseEvent,
ePopup
});
if (defaultTab) {
menu.showTab?.(defaultTab);
}
this.dispatchVisibleChangedEvent(true, false, column, columnGroup, defaultTab);
},
containerType,
defaultTab,
void 0,
mouseEvent.target,
onClosedCallback
);
}
splitColumnOrGroup(columnOrGroup) {
const colIsColumn = columnOrGroup && (0, import_ag_grid_community84.isColumn)(columnOrGroup);
const column = colIsColumn ? columnOrGroup : void 0;
const columnGroup = colIsColumn ? void 0 : columnOrGroup;
return { column, columnGroup };
}
showMenuAfterButtonClick(columnOrGroup, eventSource, containerType, onClosedCallback, filtersOnly) {
let multiplier = -1;
let alignSide = "left";
if (this.gos.get("enableRtl")) {
multiplier = 1;
alignSide = "right";
}
const defaultTab = filtersOnly ? "filterMenuTab" : void 0;
const restrictToTabs = defaultTab ? [defaultTab] : void 0;
const isLegacyMenuEnabled = (0, import_ag_grid_community84._isLegacyMenuEnabled)(this.gos);
const nudgeX = (isLegacyMenuEnabled ? 9 : 4) * multiplier;
const nudgeY = isLegacyMenuEnabled ? -23 : 4;
const { column, columnGroup } = this.splitColumnOrGroup(columnOrGroup);
this.showMenu(
column,
columnGroup,
(menu) => {
const ePopup = menu.getGui();
this.beans.popupSvc.positionPopupByComponent({
type: containerType,
column,
eventSource,
ePopup,
alignSide,
nudgeX,
nudgeY,
position: "under",
keepWithinBounds: true
});
if (defaultTab) {
menu.showTab?.(defaultTab);
}
this.dispatchVisibleChangedEvent(true, false, column, columnGroup, defaultTab);
},
containerType,
defaultTab,
restrictToTabs,
eventSource,
onClosedCallback
);
}
showMenu(column, columnGroup, positionCallback, containerType, defaultTab, restrictToTabs, eventSource, onClosedCallback) {
const menuParams = this.getMenuParams(column, columnGroup, restrictToTabs, eventSource);
if (!menuParams) {
return;
}
const { menu, eMenuGui, anchorToElement, restoreFocusParams } = menuParams;
const closedFuncs = [];
const { menuUtils, popupSvc } = this.beans;
closedFuncs.push((e) => {
const eComp = menu.getGui();
this.destroyBean(menu);
if (column) {
(0, import_ag_grid_community84._setColMenuVisible)(column, false, "contextMenu");
menuUtils.restoreFocusOnClose(restoreFocusParams, eComp, e);
}
onClosedCallback?.();
});
const translate = this.getLocaleTextFunc();
popupSvc.addPopup({
modal: true,
eChild: eMenuGui,
closeOnEsc: true,
closedCallback: (e) => {
closedFuncs.forEach((f) => f(e));
this.dispatchVisibleChangedEvent(false, false, column, columnGroup, defaultTab);
},
afterGuiAttached: (params) => menu.afterGuiAttached(Object.assign({}, { container: containerType }, params)),
// if defaultTab is not present, positionCallback will be called
// after `showTabBasedOnPreviousSelection` is called.
positionCallback: defaultTab ? () => positionCallback(menu) : void 0,
ariaLabel: translate("ariaLabelColumnMenu", "Column Menu")
});
if (!defaultTab) {
menu.showTabBasedOnPreviousSelection?.();
positionCallback(menu);
}
if ((0, import_ag_grid_community84._isColumnMenuAnchoringEnabled)(this.gos)) {
const stopAnchoringPromise = popupSvc.setPopupPositionRelatedToElement(eMenuGui, anchorToElement);
if (stopAnchoringPromise && column) {
this.addStopAnchoring(stopAnchoringPromise, column, closedFuncs);
}
}
menu.addEventListener("tabSelected", (event) => {
this.dispatchVisibleChangedEvent(false, true, column);
this.lastSelectedTab = event.key;
this.dispatchVisibleChangedEvent(true, true, column);
});
if (column) {
(0, import_ag_grid_community84._setColMenuVisible)(column, true, "contextMenu");
}
this.activeMenu = menu;
menu.addEventListener("destroyed", () => {
if (this.activeMenu === menu) {
this.activeMenu = null;
}
});
}
addStopAnchoring(stopAnchoringPromise, column, closedFuncsArr) {
stopAnchoringPromise.then((stopAnchoringFunc) => {
column.__addEventListener("leftChanged", stopAnchoringFunc);
column.__addEventListener("visibleChanged", stopAnchoringFunc);
closedFuncsArr.push(() => {
column.__removeEventListener("leftChanged", stopAnchoringFunc);
column.__removeEventListener("visibleChanged", stopAnchoringFunc);
});
});
}
getMenuParams(column, columnGroup, restrictToTabs, eventSource) {
const { focusSvc, visibleCols, ctrlsSvc } = this.beans;
const restoreFocusParams = {
column,
headerPosition: focusSvc.focusedHeader,
columnIndex: visibleCols.allCols.indexOf(column),
eventSource
};
const menu = this.createMenu(column, columnGroup, restoreFocusParams, restrictToTabs, eventSource);
return menu ? {
menu,
eMenuGui: menu.getGui(),
anchorToElement: eventSource || ctrlsSvc.getGridBodyCtrl().eGridBody,
restoreFocusParams
} : void 0;
}
createMenu(column, columnGroup, restoreFocusParams, restrictToTabs, eventSource) {
if ((0, import_ag_grid_community84._isLegacyMenuEnabled)(this.gos)) {
return this.createBean(
new TabbedColumnMenu(column, restoreFocusParams, this.lastSelectedTab, restrictToTabs, eventSource)
);
} else {
const menuItems = this.beans.colMenuFactory.getMenuItems(column, columnGroup);
return menuItems.length ? this.createBean(new ColumnContextMenu(menuItems, column, restoreFocusParams, eventSource)) : void 0;
}
}
dispatchVisibleChangedEvent(visible, switchingTab, column, columnGroup, defaultTab) {
this.eventSvc.dispatchEvent({
type: "columnMenuVisibleChanged",
visible,
switchingTab,
key: this.lastSelectedTab ?? defaultTab ?? ((0, import_ag_grid_community84._isLegacyMenuEnabled)(this.gos) ? TAB_GENERAL : "columnMenu"),
column: column ?? null,
columnGroup: columnGroup ?? null
});
}
isMenuEnabled(column) {
if (!(0, import_ag_grid_community84._isLegacyMenuEnabled)(this.gos)) {
return true;
}
const isFilterDisabled = !this.beans.filterManager?.isFilterAllowed(column);
const tabs = column.getColDef().menuTabs ?? TABS_DEFAULT;
const numActiveTabs = isFilterDisabled && tabs.includes(TAB_FILTER) ? tabs.length - 1 : tabs.length;
return numActiveTabs > 0;
}
showMenuAfterContextMenuEvent(column, mouseEvent, touchEvent) {
this.beans.menuUtils.onContextMenu({
mouseEvent,
touchEvent,
source: "ui",
showMenuCallback: (eventOrTouch) => {
this.showMenuAfterMouseEvent(column, eventOrTouch, "columnMenu");
return true;
}
});
}
};
var TabbedColumnMenu = class extends import_ag_grid_community84.BeanStub {
constructor(column, restoreFocusParams, initialSelection, restrictTo, sourceElement) {
super();
this.column = column;
this.restoreFocusParams = restoreFocusParams;
this.initialSelection = initialSelection;
this.restrictTo = restrictTo;
this.sourceElement = sourceElement;
this.tabFactories = {};
this.includeChecks = {};
const { tabFactories, includeChecks } = this;
tabFactories[TAB_GENERAL] = this.createMainPanel.bind(this);
tabFactories[TAB_FILTER] = this.createFilterPanel.bind(this);
tabFactories[TAB_COLUMNS] = this.createColumnsPanel.bind(this);
includeChecks[TAB_GENERAL] = () => true;
includeChecks[TAB_FILTER] = () => column ? !!this.beans.filterManager?.isFilterAllowed(column) : false;
includeChecks[TAB_COLUMNS] = () => true;
}
postConstruct() {
const tabs = this.getTabsToCreate().map((name) => this.createTab(name));
const tabbedLayout = new TabbedLayout({
items: tabs,
cssClass: "ag-menu",
onActiveItemClicked: this.onHidePopup.bind(this),
onItemClicked: this.onTabItemClicked.bind(this)
});
this.tabbedLayout = this.createBean(tabbedLayout);
this.mainMenuList?.setParentComponent(tabbedLayout);
this.addDestroyFunc(() => this.destroyBean(tabbedLayout));
}
getTabsToCreate() {
if (this.restrictTo) {
return this.restrictTo;
}
return (this.column?.getColDef().menuTabs ?? TABS_DEFAULT).filter(
(tabName) => this.isValidMenuTabItem(tabName) && this.isNotSuppressed(tabName)
);
}
isValidMenuTabItem(menuTabName) {
let isValid = true;
let itemsToConsider = TABS_DEFAULT;
if (this.restrictTo != null) {
isValid = this.restrictTo.indexOf(menuTabName) > -1;
itemsToConsider = this.restrictTo;
}
isValid = isValid && TABS_DEFAULT.indexOf(menuTabName) > -1;
if (!isValid) {
(0, import_ag_grid_community84._warn)(175, { menuTabName, itemsToConsider });
}
return isValid;
}
isNotSuppressed(menuTabName) {
return this.includeChecks[menuTabName]();
}
createTab(name) {
return this.tabFactories[name]();
}
showTabBasedOnPreviousSelection() {
this.showTab(this.initialSelection);
}
showTab(toShow) {
const { tabItemColumns, tabbedLayout, tabItemFilter, tabItemGeneral } = this;
if (tabItemColumns && toShow === TAB_COLUMNS) {
tabbedLayout.showItem(tabItemColumns);
} else if (tabItemFilter && toShow === TAB_FILTER) {
tabbedLayout.showItem(tabItemFilter);
} else if (tabItemGeneral && toShow === TAB_GENERAL) {
tabbedLayout.showItem(tabItemGeneral);
} else {
tabbedLayout.showFirstItem();
}
}
onTabItemClicked(event) {
let key = null;
switch (event.item) {
case this.tabItemColumns:
key = TAB_COLUMNS;
break;
case this.tabItemFilter:
key = TAB_FILTER;
break;
case this.tabItemGeneral:
key = TAB_GENERAL;
break;
}
if (key) {
this.activateTab(key);
}
}
activateTab(tab) {
const ev = {
type: "tabSelected",
key: tab
};
this.dispatchLocalEvent(ev);
}
createMainPanel() {
const { beans, column } = this;
const colMenuFactory = beans.colMenuFactory;
const mainMenuList = colMenuFactory.createMenu(
this,
colMenuFactory.getMenuItems(column),
this.column,
() => this.sourceElement ?? this.getGui()
);
this.mainMenuList = mainMenuList;
mainMenuList.addEventListener("closeMenu", this.onHidePopup.bind(this));
const tabItemGeneral = {
title: (0, import_ag_grid_community84._createIconNoSpan)("legacyMenu", beans, column),
titleLabel: TAB_GENERAL.replace("MenuTab", ""),
bodyPromise: import_ag_grid_community84.AgPromise.resolve(mainMenuList.getGui()),
name: TAB_GENERAL
};
this.tabItemGeneral = tabItemGeneral;
return tabItemGeneral;
}
onHidePopup(event) {
this.beans.menuUtils.closePopupAndRestoreFocusOnSelect(
this.hidePopupFunc,
this.restoreFocusParams,
event
);
}
createFilterPanel() {
const comp = this.column ? this.createBean(new import_ag_grid_community84.FilterComp(this.column, "COLUMN_MENU")) : null;
this.filterComp = comp;
if (!comp?.hasFilter()) {
(0, import_ag_grid_community84._error)(119);
}
const afterAttachedCallback = (params) => comp?.afterGuiAttached(params);
const afterDetachedCallback = () => comp?.afterGuiDetached();
this.tabItemFilter = {
title: (0, import_ag_grid_community84._createIconNoSpan)("filterTab", this.beans, this.column),
titleLabel: TAB_FILTER.replace("MenuTab", ""),
bodyPromise: import_ag_grid_community84.AgPromise.resolve(comp?.getGui()),
afterAttachedCallback,
afterDetachedCallback,
name: TAB_FILTER
};
return this.tabItemFilter;
}
createColumnsPanel() {
const eWrapperDiv = (0, import_ag_grid_community84._createElement)({ tag: "div", cls: "ag-menu-column-select-wrapper" });
const { beans, column } = this;
const columnSelectPanel = beans.colChooserFactory.createColumnSelectPanel(
this,
column
);
const columnSelectPanelGui = columnSelectPanel.getGui();
columnSelectPanelGui.classList.add("ag-menu-column-select");
eWrapperDiv.appendChild(columnSelectPanelGui);
const tabItemColumns = {
title: (0, import_ag_grid_community84._createIconNoSpan)("columns", beans, column),
//createColumnsIcon(),
titleLabel: TAB_COLUMNS.replace("MenuTab", ""),
bodyPromise: import_ag_grid_community84.AgPromise.resolve(eWrapperDiv),
name: TAB_COLUMNS
};
this.tabItemColumns = tabItemColumns;
return tabItemColumns;
}
afterGuiAttached(params) {
const { container, hidePopup } = params;
this.tabbedLayout.setAfterAttachedParams({ container, hidePopup });
if (hidePopup) {
this.hidePopupFunc = hidePopup;
this.addDestroyFunc(hidePopup);
}
}
getGui() {
return this.tabbedLayout.getGui();
}
destroy() {
super.destroy();
this.destroyBean(this.filterComp);
}
};
var ColumnContextMenu = class extends import_ag_grid_community84.Component {
constructor(menuItems, column, restoreFocusParams, sourceElement) {
super({ tag: "div", ref: "eColumnMenu", cls: "ag-menu ag-column-menu", role: "presentation" });
this.menuItems = menuItems;
this.column = column;
this.restoreFocusParams = restoreFocusParams;
this.sourceElement = sourceElement;
this.eColumnMenu = import_ag_grid_community84.RefPlaceholder;
}
postConstruct() {
const mainMenuList = this.beans.colMenuFactory.createMenu(
this,
this.menuItems,
this.column,
() => this.sourceElement ?? this.getGui()
);
this.mainMenuList = mainMenuList;
mainMenuList.addEventListener("closeMenu", this.onHidePopup.bind(this));
this.eColumnMenu.appendChild(mainMenuList.getGui());
}
onHidePopup(event) {
this.beans.menuUtils.closePopupAndRestoreFocusOnSelect(
this.hidePopupFunc,
this.restoreFocusParams,
event
);
}
afterGuiAttached({ hidePopup }) {
if (hidePopup) {
this.hidePopupFunc = hidePopup;
this.addDestroyFunc(hidePopup);
}
(0, import_ag_grid_community84._focusInto)(this.mainMenuList.getGui());
}
};
// packages/ag-grid-enterprise/src/menu/menuApi.ts
function showContextMenu(beans, params) {
const { contextMenuSvc } = beans;
if (!contextMenuSvc) {
return;
}
const { rowNode, column, value, x, y } = params || {};
let { x: clientX, y: clientY } = contextMenuSvc.getContextMenuPosition(rowNode, column);
if (x != null) {
clientX = x;
}
if (y != null) {
clientY = y;
}
contextMenuSvc.showContextMenu({
mouseEvent: new MouseEvent("mousedown", { clientX, clientY }),
rowNode,
column,
value,
source: "api"
});
}
function showColumnChooser(beans, params) {
beans.colChooserFactory?.showColumnChooser({ chooserParams: params });
}
function hideColumnChooser(beans) {
beans.colChooserFactory?.hideActiveColumnChooser();
}
// packages/ag-grid-enterprise/src/menu/menuUtils.ts
var import_ag_grid_community85 = require("ag-grid-community");
var MenuUtils = class extends import_ag_grid_community85.BeanStub {
constructor() {
super(...arguments);
this.beanName = "menuUtils";
}
restoreFocusOnClose(restoreFocusParams, eComp, e, restoreIfMouseEvent) {
const { eventSource } = restoreFocusParams;
const isKeyboardEvent = e instanceof KeyboardEvent;
if (!restoreIfMouseEvent && !isKeyboardEvent || !eventSource) {
return;
}
const activeEl = (0, import_ag_grid_community85._getActiveDomElement)(this.beans);
if (
// focus is outside of comp
!eComp.contains(activeEl) && // something else has focus
!(0, import_ag_grid_community85._isNothingFocused)(this.beans)
) {
return;
}
this.focusHeaderCell(restoreFocusParams);
}
closePopupAndRestoreFocusOnSelect(hidePopupFunc, restoreFocusParams, event) {
let keyboardEvent;
if (event && event.keyboardEvent) {
keyboardEvent = event.keyboardEvent;
}
hidePopupFunc(keyboardEvent && { keyboardEvent });
const beans = this.beans;
const focusSvc = beans.focusSvc;
const focusedCell = focusSvc.getFocusedCell();
if ((0, import_ag_grid_community85._isNothingFocused)(beans)) {
if (focusedCell) {
const { rowIndex, rowPinned, column } = focusedCell;
focusSvc.setFocusedCell({
rowIndex,
column,
rowPinned,
forceBrowserFocus: true,
preventScrollOnBrowserFocus: true
});
} else {
this.focusHeaderCell(restoreFocusParams);
}
}
}
onContextMenu(params) {
const { mouseEvent, touchEvent, showMenuCallback, source } = params;
if (!this.gos.get("allowContextMenuWithControlKey")) {
if (mouseEvent && (mouseEvent.ctrlKey || mouseEvent.metaKey)) {
return;
}
}
if (mouseEvent) {
this.blockMiddleClickScrollsIfNeeded(mouseEvent);
}
if (source === "ui" && this.gos.get("suppressContextMenu")) {
return;
}
const eventOrTouch = mouseEvent ?? touchEvent.touches[0];
if (showMenuCallback(eventOrTouch)) {
const event = mouseEvent ?? touchEvent;
if (event && event.cancelable) {
event.preventDefault();
}
}
}
// make this async for react
async focusHeaderCell(restoreFocusParams) {
const { column, columnIndex, headerPosition, eventSource } = restoreFocusParams;
const { visibleCols, headerNavigation, focusSvc } = this.beans;
const isColumnStillVisible = await visibleCols.allCols.some((col) => col === column);
if (!this.isAlive()) {
return;
}
if (column?.isAlive() && isColumnStillVisible && eventSource && (0, import_ag_grid_community85._isVisible)(eventSource)) {
const focusableEl = (0, import_ag_grid_community85._findTabbableParent)(eventSource);
if (focusableEl) {
headerNavigation?.scrollToColumn(column);
focusableEl.focus();
}
} else if (headerPosition && columnIndex !== -1) {
const allColumns = visibleCols.allCols;
const columnToFocus = allColumns[columnIndex] || (0, import_ag_grid_community85._last)(allColumns);
if (columnToFocus) {
focusSvc.focusHeaderPosition({
headerPosition: {
headerRowIndex: headerPosition.headerRowIndex,
column: columnToFocus
}
});
}
}
}
blockMiddleClickScrollsIfNeeded(mouseEvent) {
if (this.gos.get("suppressMiddleClickScrolls") && mouseEvent.which === 2) {
mouseEvent.preventDefault();
}
}
};
// packages/ag-grid-enterprise/src/menu/menuModule.ts
var MenuCoreModule = {
moduleName: "MenuCore",
version: VERSION,
beans: [MenuItemMapper, ChartMenuItemMapper, MenuUtils],
icons: {
// context menu chart item
chart: "chart",
// columns in menu (column chooser / columns tab)
columns: "columns",
// loading async menu items
loadingMenuItems: "loading",
// "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",
// context menu cut item
clipboardCut: "cut",
// context menu paste item
clipboardPaste: "paste",
// context menu export item
save: "save",
// csv export
csvExport: "csv",
// excel export,
excelExport: "excel",
// 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 colDef.unSortIcon=true
sortUnSort: "none"
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community86._PopupModule, import_ag_grid_community86._SharedMenuModule, MenuItemModule]
};
var ColumnMenuModule = {
moduleName: "ColumnMenu",
version: VERSION,
beans: [EnterpriseMenuFactory, ColumnMenuFactory, ColumnChooserFactory],
icons: {
ensureColumnVisible: "column-arrow",
// menu tab icon in legacy tabbed enterprise column menu
legacyMenu: "menu",
// filter tab icon in legacy tabbed enterprise column menu
filterTab: "filter",
// column tool panel column group contracted (click to expand)
columnSelectClosed: "tree-closed",
// column 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"
},
apiFunctions: {
showColumnChooser,
hideColumnChooser
},
dependsOn: [MenuCoreModule, import_ag_grid_community86._SharedDragAndDropModule, import_ag_grid_community86._ColumnMoveModule]
};
var ContextMenuModule = {
moduleName: "ContextMenu",
version: VERSION,
beans: [ContextMenuService],
apiFunctions: {
showContextMenu
},
dependsOn: [MenuCoreModule]
};
var MenuModule = {
moduleName: "Menu",
version: VERSION,
dependsOn: [ColumnMenuModule, ContextMenuModule]
};
// packages/ag-grid-enterprise/src/richSelect/richSelectModule.ts
var import_ag_grid_community88 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/richSelect/richSelectCellEditor.ts
var import_ag_grid_community87 = require("ag-grid-community");
var RichSelectCellEditor = class extends import_ag_grid_community87.AgAbstractCellEditor {
constructor() {
super({ tag: "div", cls: "ag-cell-edit-wrapper" });
this.isAsync = false;
}
initialiseEditor(_params) {
const { cellStartedEdit, values, eventKey } = this.params;
if ((0, import_ag_grid_community87._missing)(values)) {
(0, import_ag_grid_community87._warn)(180);
}
const { params: richSelectParams, valuesPromise } = this.buildRichSelectParams();
const richSelect = this.createManagedBean(new AgRichSelect(richSelectParams));
this.eEditor = richSelect;
richSelect.addCss("ag-cell-editor");
this.appendChild(richSelect);
if (valuesPromise) {
this.isAsync = true;
valuesPromise.then((values2) => {
richSelect.setValueList({ valueList: values2, refresh: true });
const searchStringCallback = this.getSearchStringCallback(values2);
if (searchStringCallback) {
richSelect.setSearchStringCreator(searchStringCallback);
}
this.processEventKey(eventKey);
});
}
this.addManagedListeners(richSelect, {
fieldPickerValueSelected: this.onEditorPickerValueSelected.bind(this)
});
this.focusAfterAttached = cellStartedEdit;
}
onEditorPickerValueSelected(e) {
if (this.gos.get("editType") !== "fullRow") {
setTimeout(() => this.params.stopEditing(!e.fromEnterKey));
}
}
buildRichSelectParams() {
const params = this.params;
const {
cellRenderer,
cellHeight,
value,
values,
formatValue,
searchDebounceDelay,
valueListGap,
valueListMaxHeight,
valueListMaxWidth,
allowTyping,
filterList,
searchType,
highlightMatch,
valuePlaceholder,
eventKey,
multiSelect,
suppressDeselectAll,
suppressMultiSelectPillRenderer
} = params;
const ret = {
value,
cellRenderer,
cellRowHeight: cellHeight,
searchDebounceDelay,
valueFormatter: formatValue,
pickerAriaLabelKey: "ariaLabelRichSelectField",
pickerAriaLabelValue: "Rich Select Field",
pickerType: "virtual-list",
pickerGap: valueListGap,
allowTyping,
filterList,
searchType,
highlightMatch,
maxPickerHeight: valueListMaxHeight,
maxPickerWidth: valueListMaxWidth,
placeholder: valuePlaceholder,
initialInputValue: eventKey?.length === 1 ? eventKey : void 0,
multiSelect,
suppressDeselectAll,
suppressMultiSelectPillRenderer
};
let valuesResult;
let valuesPromise;
if (typeof values === "function") {
valuesResult = values(params);
} else {
valuesResult = values ?? [];
}
if (Array.isArray(valuesResult)) {
ret.valueList = valuesResult;
ret.searchStringCreator = this.getSearchStringCallback(valuesResult);
} else {
valuesPromise = valuesResult;
}
if (multiSelect && allowTyping) {
params.allowTyping = ret.allowTyping = false;
(0, import_ag_grid_community87._warn)(181);
}
return { params: ret, valuesPromise };
}
getSearchStringCallback(values) {
if (typeof values[0] !== "object") {
return;
}
const params = this.params;
const { colDef, formatValue } = params;
if (colDef.cellEditorParams?.formatValue) {
return (values2) => values2.map(formatValue);
}
const { keyCreator } = colDef;
if (keyCreator) {
(0, import_ag_grid_community87._warn)(266);
const { column, node, data } = params;
return (values2) => values2.map((value) => {
const keyParams = (0, import_ag_grid_community87._addGridCommonParams)(this.gos, {
value,
colDef,
column,
node,
data
});
return keyCreator(keyParams);
});
}
return (values2) => values2.map(formatValue);
}
// we need to have the gui attached before we can draw the virtual rows, as the
// virtual row logic needs info about the gui state
afterGuiAttached() {
const { focusAfterAttached, params } = this;
setTimeout(() => {
if (!this.isAlive()) {
return;
}
const richSelect = this.eEditor;
const { allowTyping, eventKey, cellStartedEdit } = params;
if (focusAfterAttached) {
const focusableEl = richSelect.getFocusableElement();
focusableEl.focus();
if (allowTyping && (!eventKey || eventKey.length !== 1)) {
focusableEl.select();
}
}
if (cellStartedEdit) {
richSelect.showPicker();
}
if (!this.isAsync) {
this.processEventKey(eventKey);
}
});
}
processEventKey(eventKey) {
if (!eventKey) {
return;
}
if (eventKey?.length === 1) {
this.eEditor.searchTextFromString(eventKey);
}
}
focusIn() {
this.eEditor.getFocusableElement().focus();
}
getValue() {
const { params } = this;
const value = this.eEditor.getValue();
return params.parseValue?.(value) ?? value;
}
isPopup() {
return false;
}
getValidationElement() {
return this.eEditor.getAriaElement();
}
getValidationErrors() {
const { params } = this;
const { getValidationErrors } = params;
if (!getValidationErrors) {
return null;
}
return getValidationErrors({
value: this.getValue(),
internalErrors: null,
cellEditorParams: params
});
}
};
// packages/ag-grid-enterprise/src/richSelect/richSelectModule.ts
var RichSelectModule = {
moduleName: "RichSelect",
version: VERSION,
beans: [],
userComponents: { agRichSelect: RichSelectCellEditor, agRichSelectCellEditor: RichSelectCellEditor },
icons: {
// open icon for rich select editor
richSelectOpen: "small-down",
// remove for rich select editor pills
richSelectRemove: "cancel"
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community88._EditCoreModule]
};
// packages/ag-grid-enterprise/src/setFilter/setFilterModule.ts
var import_ag_grid_community98 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/setFilter/setFilter.ts
var import_ag_grid_community92 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/setFilter/iSetDisplayValueModel.ts
var SET_FILTER_SELECT_ALL = "__AG_SELECT_ALL__";
var SET_FILTER_ADD_SELECTION_TO_FILTER = "__AG_ADD_SELECTION_TO_FILTER__";
// packages/ag-grid-enterprise/src/setFilter/flatSetDisplayValueModel.ts
var FlatSetDisplayValueModel = class {
constructor(valueSvc, getValueFormatter, formatter, column) {
this.valueSvc = valueSvc;
this.getValueFormatter = getValueFormatter;
this.formatter = formatter;
this.column = column;
/** All keys that are currently displayed, after the mini-filter has been applied. */
this.displayedKeys = [];
}
updateDisplayedValuesToAllAvailable(_getValue, _allKeys, availableKeys) {
this.displayedKeys = Array.from(availableKeys);
}
updateDisplayedValuesToMatchMiniFilter(getValue, _allKeys, availableKeys, matchesFilter, nullMatchesFilter) {
this.displayedKeys = [];
const valueFormatter = this.getValueFormatter();
for (const key of availableKeys) {
if (key == null) {
if (nullMatchesFilter) {
this.displayedKeys.push(key);
}
} else {
const value = getValue(key);
const valueFormatterValue = this.valueSvc.formatValue(this.column, null, value, valueFormatter, false);
const textFormatterValue = this.formatter(valueFormatterValue);
if (matchesFilter(textFormatterValue)) {
this.displayedKeys.push(key);
}
}
}
}
getDisplayedValueCount() {
return this.displayedKeys.length;
}
getDisplayedItem(index) {
return this.displayedKeys[index];
}
getSelectAllItem() {
return SET_FILTER_SELECT_ALL;
}
getAddSelectionToFilterItem() {
return SET_FILTER_ADD_SELECTION_TO_FILTER;
}
getDisplayedKeys() {
return this.displayedKeys;
}
forEachDisplayedKey(func) {
this.displayedKeys.forEach(func);
}
someDisplayedKey(func) {
return this.displayedKeys.some(func);
}
hasGroups() {
return false;
}
refresh() {
}
};
// packages/ag-grid-enterprise/src/setFilter/setFilterListItem.ts
var import_ag_grid_community89 = require("ag-grid-community");
var SetFilterGroupElement = {
tag: "div",
cls: "ag-set-filter-item",
attrs: { "aria-hidden": "true" },
children: [
{
tag: "span",
cls: "ag-set-filter-group-icons",
children: [
{ tag: "span", ref: "eGroupClosedIcon", cls: "ag-set-filter-group-closed-icon" },
{ tag: "span", ref: "eGroupOpenedIcon", cls: "ag-set-filter-group-opened-icon" },
{ tag: "span", ref: "eGroupIndeterminateIcon", cls: "ag-set-filter-group-indeterminate-icon" }
]
},
{ tag: "ag-checkbox", ref: "eCheckbox", cls: "ag-set-filter-item-checkbox" }
]
};
var SetFilterElement = {
tag: "div",
cls: "ag-set-filter-item",
children: [{ tag: "ag-checkbox", ref: "eCheckbox", cls: "ag-set-filter-item-checkbox" }]
};
var SetFilterListItem = class extends import_ag_grid_community89.Component {
constructor(params) {
super(params.isGroup ? SetFilterGroupElement : SetFilterElement, [import_ag_grid_community89.AgCheckboxSelector]);
this.eCheckbox = import_ag_grid_community89.RefPlaceholder;
this.eGroupOpenedIcon = import_ag_grid_community89.RefPlaceholder;
this.eGroupClosedIcon = import_ag_grid_community89.RefPlaceholder;
this.eGroupIndeterminateIcon = import_ag_grid_community89.RefPlaceholder;
this.formattedValue = null;
this.focusWrapper = params.focusWrapper;
this.value = params.value;
this.params = params.params;
this.translate = params.translate;
this.valueFormatter = params.valueFormatter;
this.item = params.item;
this.isSelected = params.isSelected;
this.isTree = params.isTree;
this.depth = params.depth ?? 0;
this.isGroup = params.isGroup;
this.groupsExist = params.groupsExist;
this.isExpanded = params.isExpanded;
this.hasIndeterminateExpandState = params.hasIndeterminateExpandState;
}
postConstruct() {
this.tooltipFeature = this.createOptionalManagedBean(
this.beans.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.getGui(),
getColDef: () => this.params.colDef,
getColumn: () => this.params.column,
getLocation: () => "setFilterValue",
shouldDisplayTooltip: () => this.shouldDisplayTooltip?.() ?? true,
getValueFormatted: () => this.formattedValue,
getAdditionalParams: () => this.isTree ? { level: this.depth } : {}
})
);
this.addDestroyFunc(() => this.destroyCellRendererComponent?.());
this.render();
this.eCheckbox.setLabelEllipsis(true).setValue(this.isSelected, true).setDisabled(!!this.params.readOnly).getInputElement().setAttribute("tabindex", "-1");
this.refreshVariableAriaLabels();
if (this.isTree) {
if (this.depth > 0) {
this.addCss("ag-set-filter-indent-" + this.depth);
this.getGui().style.setProperty("--ag-indentation-level", String(this.depth));
}
if (this.isGroup) {
this.setupExpansion();
} else {
if (this.groupsExist) {
this.addCss("ag-set-filter-add-group-indent");
}
}
(0, import_ag_grid_community89._setAriaLevel)(this.getAriaElement(), this.depth + 1);
}
this.refreshAriaChecked();
if (this.params.readOnly) {
return;
}
this.eCheckbox.onValueChange((value) => this.onCheckboxChanged(!!value));
}
getFocusableElement() {
return this.focusWrapper;
}
setupExpansion() {
const { eGroupClosedIcon, eGroupOpenedIcon, eGroupIndeterminateIcon, hasIndeterminateExpandState, beans } = this;
eGroupClosedIcon.appendChild((0, import_ag_grid_community89._createIcon)("setFilterGroupClosed", beans, null));
eGroupOpenedIcon.appendChild((0, import_ag_grid_community89._createIcon)("setFilterGroupOpen", beans, null));
const listener = this.onExpandOrContractClicked.bind(this);
this.addManagedElementListeners(eGroupClosedIcon, { click: listener });
this.addManagedElementListeners(eGroupOpenedIcon, { click: listener });
if (hasIndeterminateExpandState) {
eGroupIndeterminateIcon.appendChild((0, import_ag_grid_community89._createIcon)("setFilterGroupIndeterminate", beans, null));
this.addManagedElementListeners(eGroupIndeterminateIcon, {
click: listener
});
}
this.setExpandedIcons();
this.refreshAriaExpanded();
}
onExpandOrContractClicked() {
this.setExpanded(!this.isExpanded);
}
setExpanded(isExpanded, silent) {
if (this.isGroup && isExpanded !== this.isExpanded) {
this.isExpanded = isExpanded;
const event = {
type: "expandedChanged",
isExpanded: !!isExpanded,
item: this.item
};
if (!silent) {
this.dispatchLocalEvent(event);
}
this.setExpandedIcons();
this.refreshAriaExpanded();
}
}
setExpandedIcons() {
const { isExpanded, hasIndeterminateExpandState, eGroupClosedIcon, eGroupOpenedIcon, eGroupIndeterminateIcon } = this;
(0, import_ag_grid_community89._setDisplayed)(eGroupClosedIcon, hasIndeterminateExpandState ? isExpanded === false : !isExpanded);
(0, import_ag_grid_community89._setDisplayed)(eGroupOpenedIcon, isExpanded === true);
if (hasIndeterminateExpandState) {
(0, import_ag_grid_community89._setDisplayed)(eGroupIndeterminateIcon, isExpanded === void 0);
}
}
onCheckboxChanged(isSelected) {
this.isSelected = isSelected;
const event = {
type: "selectionChanged",
isSelected,
item: this.item
};
this.dispatchLocalEvent(event);
this.refreshVariableAriaLabels();
this.refreshAriaChecked();
}
toggleSelected() {
if (this.params.readOnly) {
return;
}
this.setSelected(!this.isSelected);
}
setSelected(isSelected, silent) {
this.isSelected = isSelected;
this.eCheckbox.setValue(isSelected, silent);
this.refreshAriaChecked();
}
refreshVariableAriaLabels() {
if (!this.isTree) {
return;
}
const translate = this.getLocaleTextFunc();
const checkboxValue = this.eCheckbox.getValue();
const state = checkboxValue === void 0 ? translate("ariaIndeterminate", "indeterminate") : checkboxValue ? translate("ariaVisible", "visible") : translate("ariaHidden", "hidden");
const visibilityLabel = translate("ariaToggleVisibility", "Press SPACE to toggle visibility");
(0, import_ag_grid_community89._setAriaLabelledBy)(this.eCheckbox.getInputElement(), void 0);
this.eCheckbox.setInputAriaLabel(`${visibilityLabel} (${state})`);
}
setupFixedAriaLabels(value) {
if (!this.isTree) {
return;
}
const translate = this.getLocaleTextFunc();
const itemLabel = translate("ariaFilterValue", "Filter Value");
const ariaEl = this.getAriaElement();
(0, import_ag_grid_community89._setAriaLabel)(ariaEl, `${value} ${itemLabel}`);
(0, import_ag_grid_community89._setAriaDescribedBy)(ariaEl, this.eCheckbox.getInputElement().id);
}
refreshAriaChecked() {
const ariaEl = this.getAriaElement();
(0, import_ag_grid_community89._setAriaChecked)(ariaEl, this.eCheckbox.getValue());
}
refreshAriaExpanded() {
(0, import_ag_grid_community89._setAriaExpanded)(this.getAriaElement(), !!this.isExpanded);
}
refresh(item, isSelected, isExpanded) {
this.item = item;
if (isSelected !== this.isSelected) {
this.setSelected(isSelected, true);
}
this.setExpanded(isExpanded, true);
const { cellRendererComponent, cellRendererParams, beans, params } = this;
if (this.valueFunction) {
const value = this.valueFunction();
this.setTooltipAndCellRendererParams(value, value);
if (!cellRendererComponent) {
this.renderCellWithoutCellRenderer();
}
}
if (cellRendererComponent) {
const compDetails = (0, import_ag_grid_community89._getCellRendererDetails)(beans.userCompFactory, params, cellRendererParams);
const success = cellRendererComponent.refresh?.(compDetails?.params ?? cellRendererParams);
if (!success) {
const oldComponent = cellRendererComponent;
this.renderCell();
this.destroyBean(oldComponent);
}
}
}
render() {
const {
params: { column }
} = this;
let { value } = this;
let formattedValue = null;
if (typeof value === "function") {
this.valueFunction = value;
formattedValue = this.valueFunction();
value = formattedValue;
} else if (this.isTree) {
formattedValue = (0, import_ag_grid_community89._toStringOrNull)(value);
} else {
formattedValue = this.getFormattedValue(column, value);
}
this.formattedValue = formattedValue;
this.setTooltipAndCellRendererParams(value, formattedValue);
this.renderCell();
}
setTooltipAndCellRendererParams(value, formattedValue) {
const gos = this.gos;
if (this.params.showTooltips && (!(0, import_ag_grid_community89._isShowTooltipWhenTruncated)(gos) || !this.params.cellRenderer)) {
const newTooltipText = formattedValue != null ? formattedValue : (0, import_ag_grid_community89._toStringOrNull)(value);
this.shouldDisplayTooltip = (0, import_ag_grid_community89._getShouldDisplayTooltip)(
gos,
() => this.eCheckbox.getGui().querySelector(".ag-label")
);
this.tooltipFeature?.setTooltipAndRefresh(newTooltipText);
}
this.cellRendererParams = (0, import_ag_grid_community89._addGridCommonParams)(gos, {
value,
valueFormatted: formattedValue,
colDef: this.params.colDef,
column: this.params.column,
setTooltip: (value2, shouldDisplayTooltip) => {
gos.assertModuleRegistered("Tooltip", 3);
this.shouldDisplayTooltip = shouldDisplayTooltip;
this.tooltipFeature?.setTooltipAndRefresh(value2);
}
});
}
getFormattedValue(column, value) {
return this.beans.valueSvc.formatValue(column, null, value, this.valueFormatter, false);
}
renderCell() {
const compDetails = (0, import_ag_grid_community89._getCellRendererDetails)(this.beans.userCompFactory, this.params, this.cellRendererParams);
const cellRendererPromise = compDetails?.newAgStackInstance();
if (cellRendererPromise == null) {
this.renderCellWithoutCellRenderer();
return;
}
cellRendererPromise.then((component) => {
if (component) {
this.cellRendererComponent = component;
this.eCheckbox.setLabel(component.getGui());
this.destroyCellRendererComponent = () => this.destroyBean(component);
}
});
}
renderCellWithoutCellRenderer() {
const { valueFormatted, value } = this.cellRendererParams;
let valueToRender = (valueFormatted == null ? value : valueFormatted) ?? this.translate("blanks");
if (typeof valueToRender !== "string") {
(0, import_ag_grid_community89._warn)(208);
valueToRender = "";
}
this.eCheckbox.setLabel(valueToRender);
this.setupFixedAriaLabels(valueToRender);
}
getComponentHolder() {
return this.params.column.getColDef();
}
};
// packages/ag-grid-enterprise/src/setFilter/setFilterUtils.ts
var import_ag_grid_community90 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/setFilter/localeText.ts
var DEFAULT_LOCALE_TEXT = {
loadingOoo: "Loading...",
blanks: "(Blanks)",
searchOoo: "Search...",
selectAll: "(Select All)",
selectAllSearchResults: "(Select All Search Results)",
addCurrentSelectionToFilter: "Add current selection to filter",
noMatches: "No matches.",
ariaSearchFilterValues: "Search filter values",
ariaFilterList: "Filter List",
filterSummaryListInactive: "is (All)",
filterSummaryListSeparator: ", ",
filterSummaryListShort: (variableValues) => `is (${variableValues[0]})`,
filterSummaryListLong: (variableValues) => `is (${variableValues[0]}) and ${variableValues[1]} more`
};
// packages/ag-grid-enterprise/src/setFilter/setFilterUtils.ts
function processDataPath(dataPath, treeData, groupAllowUnbalanced) {
let processedDataPath = dataPath;
if (!processedDataPath) {
return null;
}
processedDataPath = processedDataPath.map((treeKey) => (0, import_ag_grid_community90._toStringOrNull)((0, import_ag_grid_community90._makeNull)(treeKey)));
if (!treeData && groupAllowUnbalanced && processedDataPath.some((treeKey) => treeKey == null)) {
if ((0, import_ag_grid_community90._last)(processedDataPath) == null) {
return null;
}
return processedDataPath.filter((treeKey) => treeKey != null);
}
return processedDataPath;
}
function translateForSetFilter(bean, key, variableValues) {
return (0, import_ag_grid_community90._translate)(bean, DEFAULT_LOCALE_TEXT, key, variableValues);
}
function applyExcelModeOptions(params) {
if (params.excelMode === "windows") {
if (!params.buttons) {
params.buttons = ["apply", "cancel"];
}
if (params.closeOnApply == null) {
params.closeOnApply = true;
}
} else if (params.excelMode === "mac") {
if (!params.buttons) {
params.buttons = ["reset"];
}
if (params.applyMiniFilterWhileTyping == null) {
params.applyMiniFilterWhileTyping = true;
}
if (params.debounceMs == null) {
params.debounceMs = 500;
}
}
if (params.excelMode && params.defaultToNothingSelected) {
params.defaultToNothingSelected = false;
(0, import_ag_grid_community90._warn)(207);
}
}
function createTreeDataOrGroupingComparator() {
return ([_aKey, aValue], [_bKey, bValue]) => {
if (aValue == null) {
return bValue == null ? 0 : -1;
} else if (bValue == null) {
return 1;
}
for (let i = 0; i < aValue.length; i++) {
if (i >= bValue.length) {
return 1;
}
const diff = (0, import_ag_grid_community90._defaultComparator)(aValue[i], bValue[i]);
if (diff !== 0) {
return diff;
}
}
return 0;
};
}
// packages/ag-grid-enterprise/src/setFilter/treeSetDisplayValueModel.ts
var import_ag_grid_community91 = require("ag-grid-community");
var TreeSetDisplayValueModel = class {
constructor(formatter, treeListPathGetter, treeListFormatter, treeDataOrGrouping) {
this.formatter = formatter;
this.treeListPathGetter = treeListPathGetter;
this.treeListFormatter = treeListFormatter;
this.treeDataOrGrouping = treeDataOrGrouping;
/** all displayed items in a tree structure */
this.allDisplayedItemsTree = /* @__PURE__ */ new Map();
/** all displayed items flattened and filtered */
this.activeDisplayedItemsFlat = [];
this.selectAllItem = {
depth: 0,
filterPasses: true,
available: true,
treeKey: SET_FILTER_SELECT_ALL,
children: this.allDisplayedItemsTree,
expanded: true,
key: SET_FILTER_SELECT_ALL,
parentTreeKeys: []
};
this.addSelectionToFilterItem = {
depth: 0,
filterPasses: true,
available: true,
treeKey: SET_FILTER_ADD_SELECTION_TO_FILTER,
expanded: true,
key: SET_FILTER_ADD_SELECTION_TO_FILTER,
parentTreeKeys: []
};
}
updateParams(treeListPathGetter, treeListFormatter) {
this.treeListPathGetter = treeListPathGetter;
this.treeListFormatter = treeListFormatter;
}
updateDisplayedValuesToAllAvailable(getValue, allKeys, availableKeys, source) {
if (source === "reload") {
this.generateItemTree(getValue, allKeys, availableKeys);
} else if (source === "otherFilter") {
this.updateAvailable(availableKeys);
this.updateExpandAll();
} else if (source === "miniFilter") {
this.resetFilter();
this.updateExpandAll();
}
this.flattenItems();
}
updateDisplayedValuesToMatchMiniFilter(getValue, allKeys, availableKeys, matchesFilter, nullMatchesFilter, source) {
if (source === "reload") {
this.generateItemTree(getValue, allKeys, availableKeys);
} else if (source === "otherFilter") {
this.updateAvailable(availableKeys);
}
this.updateFilter(matchesFilter, nullMatchesFilter);
this.updateExpandAll();
this.flattenItems();
}
generateItemTree(getValue, allKeys, availableKeys) {
const allDisplayedItemsTree = /* @__PURE__ */ new Map();
this.allDisplayedItemsTree = allDisplayedItemsTree;
let groupsExist = false;
const treeListPathGetter = this.getTreeListPathGetter(getValue, availableKeys);
for (const key of allKeys) {
const value = getValue(key);
const dataPath = treeListPathGetter(value) ?? [null];
const dataPathLength = dataPath.length;
if (dataPathLength > 1) {
groupsExist = true;
}
const available = availableKeys.has(key);
let children = allDisplayedItemsTree;
let item;
let parentTreeKeys = [];
for (let depth = 0; depth < dataPathLength; depth++) {
const treeKey = dataPath[depth];
if (!children) {
children = /* @__PURE__ */ new Map();
item.children = children;
}
const treeKeyUpper = treeKey?.toUpperCase() ?? null;
item = children.get(treeKeyUpper);
if (!item) {
item = {
treeKey,
depth,
filterPasses: true,
expanded: false,
available,
parentTreeKeys
};
if (depth === dataPath.length - 1) {
item.key = key;
}
children.set(treeKeyUpper, item);
}
children = item.children;
parentTreeKeys = [...parentTreeKeys, treeKey];
}
}
this.groupsExist = groupsExist;
this.updateAvailable(availableKeys);
this.selectAllItem.children = allDisplayedItemsTree;
this.selectAllItem.expanded = false;
}
getTreeListPathGetter(getValue, availableKeys) {
if (this.treeListPathGetter) {
return this.treeListPathGetter;
}
if (this.treeDataOrGrouping) {
return (value) => value;
}
let isDate = false;
for (const availableKey of availableKeys) {
const value = getValue(availableKey);
if (value instanceof Date) {
isDate = true;
break;
} else if (value != null) {
break;
}
}
if (isDate) {
return (value) => (0, import_ag_grid_community91._getDateParts)(value, false);
}
(0, import_ag_grid_community91._warn)(211);
return (value) => [String(value)];
}
flattenItems() {
this.activeDisplayedItemsFlat = [];
const recursivelyFlattenDisplayedItems = (items) => {
for (const item of items.values()) {
if (!item.filterPasses || !item.available) {
continue;
}
this.activeDisplayedItemsFlat.push(item);
if (item.children && item.expanded) {
recursivelyFlattenDisplayedItems(item.children);
}
}
};
recursivelyFlattenDisplayedItems(this.allDisplayedItemsTree);
}
resetFilter() {
const recursiveFilterReset = (item) => {
const children = item.children;
if (children) {
for (const child of children.values()) {
recursiveFilterReset(child);
}
}
item.filterPasses = true;
};
for (const item of this.allDisplayedItemsTree.values()) {
recursiveFilterReset(item);
}
}
updateFilter(matchesFilter, nullMatchesFilter) {
const passesFilter = (item) => {
if (!item.available) {
return false;
}
if (item.treeKey == null) {
return nullMatchesFilter;
}
return matchesFilter(
this.formatter(
this.treeListFormatter ? this.treeListFormatter(item.treeKey, item.depth, item.parentTreeKeys) : item.treeKey
)
);
};
for (const item of this.allDisplayedItemsTree.values()) {
this.recursiveItemCheck(item, false, passesFilter, "filterPasses");
}
}
getDisplayedValueCount() {
return this.activeDisplayedItemsFlat.length;
}
getDisplayedItem(index) {
return this.activeDisplayedItemsFlat[index];
}
getSelectAllItem() {
return this.selectAllItem;
}
getAddSelectionToFilterItem() {
return this.addSelectionToFilterItem;
}
getDisplayedKeys() {
const displayedKeys = [];
this.forEachDisplayedKey((key) => displayedKeys.push(key));
return displayedKeys;
}
forEachDisplayedKey(func) {
const recursiveForEachItem = (item, topParentExpanded) => {
const children = item.children;
if (children) {
if (!item.expanded || !topParentExpanded) {
for (const child of children.values()) {
if (child.filterPasses) {
recursiveForEachItem(child, false);
}
}
}
} else {
func(item.key);
}
};
this.activeDisplayedItemsFlat.forEach((item) => recursiveForEachItem(item, true));
}
someDisplayedKey(func) {
const recursiveSomeItem = (item, topParentExpanded) => {
const children = item.children;
if (children) {
if (!item.expanded || !topParentExpanded) {
for (const child of children.values()) {
if (child.filterPasses && recursiveSomeItem(child, false)) {
return true;
}
}
return false;
}
} else {
return func(item.key);
}
return false;
};
return this.activeDisplayedItemsFlat.some((item) => recursiveSomeItem(item, true));
}
hasGroups() {
return this.groupsExist;
}
refresh() {
this.updateExpandAll();
this.flattenItems();
}
updateExpandAll() {
const recursiveExpansionCheck = (items, someTrue, someFalse) => {
for (const item2 of items.values()) {
if (!item2.filterPasses || !item2.available || !item2.children) {
continue;
}
someTrue = someTrue || !!item2.expanded;
someFalse = someFalse || !item2.expanded;
if (someTrue && someFalse) {
return void 0;
}
const childExpanded = recursiveExpansionCheck(item2.children, someTrue, someFalse);
if (childExpanded === void 0) {
return void 0;
} else if (childExpanded) {
someTrue = true;
} else {
someFalse = true;
}
}
return someTrue && someFalse ? void 0 : someTrue;
};
const item = this.getSelectAllItem();
item.expanded = recursiveExpansionCheck(item.children, false, false);
}
recursiveItemCheck(item, parentPasses, checkFunction, itemProp) {
let atLeastOneChildPassed = false;
const children = item.children;
if (children) {
for (const child of children.values()) {
const childPasses = this.recursiveItemCheck(
child,
parentPasses || checkFunction(item),
checkFunction,
itemProp
);
atLeastOneChildPassed = atLeastOneChildPassed || childPasses;
}
}
const itemPasses = parentPasses || atLeastOneChildPassed || checkFunction(item);
item[itemProp] = itemPasses;
return itemPasses;
}
updateAvailable(availableKeys) {
const isAvailable = (item) => availableKeys.has(item.key);
for (const item of this.allDisplayedItemsTree.values()) {
this.recursiveItemCheck(item, false, isAvailable, "available");
}
}
};
// packages/ag-grid-enterprise/src/setFilter/setFilter.ts
var SetFilter = class extends import_ag_grid_community92.ProvidedFilter {
constructor() {
super("setFilter", "set-filter");
this.filterType = "set";
this.eMiniFilter = import_ag_grid_community92.RefPlaceholder;
this.eFilterLoading = import_ag_grid_community92.RefPlaceholder;
this.eFilterLoadingIcon = import_ag_grid_community92.RefPlaceholder;
this.eSetFilterList = import_ag_grid_community92.RefPlaceholder;
this.eFilterNoMatches = import_ag_grid_community92.RefPlaceholder;
this.hardRefreshVirtualList = false;
this.miniFilterText = null;
/** When true, in excelMode = 'windows', it adds previously selected filter items to newly checked filter selection */
this.addCurrentSelectionToFilter = false;
/** Keys that have been selected for this filter. */
this.selectedKeys = /* @__PURE__ */ new Set();
}
setParams(params) {
super.setParams(params);
const handler = this.updateHandler(params.getHandler());
const { column, textFormatter, treeList, treeListPathGetter, treeListFormatter } = params;
this.formatter = textFormatter ?? ((value) => value ?? null);
this.displayValueModel = treeList ? new TreeSetDisplayValueModel(
this.formatter,
treeListPathGetter,
treeListFormatter,
handler.isTreeDataOrGrouping()
) : new FlatSetDisplayValueModel(
this.beans.valueSvc,
() => this.handler.valueFormatter,
this.formatter,
column
);
handler.valueModel.allKeys.then((values) => {
this.updateDisplayedValues("reload", values ?? []);
this.resetSelectionState(values ?? []);
});
if (handler.valueModel.isLoading()) {
this.setIsLoading(true);
}
this.initialiseFilterBodyUi();
}
refresh(legacyNewParams) {
if (this.params.treeList !== legacyNewParams.treeList) {
return false;
}
this.updateHandler(
legacyNewParams.getHandler()
);
return super.refresh(legacyNewParams);
}
updateParams(newParams, oldParams) {
super.updateParams(newParams, oldParams);
this.updateMiniFilter();
if (newParams.suppressSelectAll !== oldParams.suppressSelectAll) {
this.createVirtualListModel(newParams);
}
const { textFormatter, treeListPathGetter, treeListFormatter } = newParams;
this.formatter = textFormatter ?? ((value) => value ?? null);
if (this.displayValueModel instanceof TreeSetDisplayValueModel) {
this.displayValueModel.updateParams(treeListPathGetter, treeListFormatter);
}
this.handler.refreshFilterValues();
}
updateHandler(handler) {
const oldHandler = this.handler;
if (oldHandler !== handler) {
this.handlerDestroyFuncs?.forEach((func) => func());
this.handlerDestroyFuncs = [
...this.addManagedListeners(handler, {
anyFilterChanged: (event) => {
handler.valueModel.allKeys.then((values) => {
if (this.isAlive()) {
this.updateDisplayedValues("otherFilter", values ?? []);
if (event.updated) {
this.checkAndRefreshVirtualList();
this.showOrHideResults();
}
}
});
},
dataChanged: ({ hardRefresh }) => {
handler.valueModel.allKeys.then((values) => {
if (this.isAlive()) {
this.updateDisplayedValues("reload", values ?? []);
this.setSelectedModel(this.state.model?.values ?? null);
if (hardRefresh) {
this.hardRefreshVirtualList = true;
}
this.checkAndRefreshVirtualList();
}
});
}
}),
...this.addManagedListeners(handler.valueModel, {
loadingStart: () => this.setIsLoading(true),
loadingEnd: () => this.setIsLoading(false)
})
];
this.handler = handler;
}
return handler;
}
// unlike the simple filters, nothing in the set filter UI shows/hides.
// maybe this method belongs in abstractSimpleFilter???
updateUiVisibility() {
}
createBodyTemplate() {
return {
tag: "div",
cls: "ag-set-filter",
children: [
{
tag: "div",
ref: "eFilterLoading",
cls: "ag-filter-loading ag-loading ag-hidden",
children: [
{ tag: "span", ref: "eFilterLoadingIcon", cls: "ag-loading-icon" },
{ tag: "span", cls: "ag-loading-text", children: translateForSetFilter(this, "loadingOoo") }
]
},
{ tag: "ag-input-text-field", ref: "eMiniFilter", cls: "ag-mini-filter" },
{
tag: "div",
ref: "eFilterNoMatches",
cls: "ag-filter-no-matches ag-hidden",
children: translateForSetFilter(this, "noMatches")
},
{ tag: "div", ref: "eSetFilterList", cls: "ag-set-filter-list", role: "presentation" }
]
};
}
getAgComponents() {
return [import_ag_grid_community92.AgInputTextFieldSelector];
}
handleKeyDown(e) {
super.handleKeyDown(e);
if (e.defaultPrevented) {
return;
}
const getComponentForKeyEvent = () => {
if (!this.eSetFilterList.contains((0, import_ag_grid_community92._getActiveDomElement)(this.beans))) {
return;
}
const currentItem = this.virtualList.getLastFocusedRow();
if (currentItem == null) {
return;
}
const component = this.virtualList.getComponentAt(currentItem);
if (component == null) {
return;
}
e.preventDefault();
const { readOnly } = this.params;
if (readOnly) {
return;
}
return component;
};
switch (e.key) {
case import_ag_grid_community92.KeyCode.SPACE:
getComponentForKeyEvent()?.toggleSelected();
break;
case import_ag_grid_community92.KeyCode.ENTER:
this.handleKeyEnter(e);
break;
case import_ag_grid_community92.KeyCode.LEFT:
getComponentForKeyEvent()?.setExpanded(false);
break;
case import_ag_grid_community92.KeyCode.RIGHT:
getComponentForKeyEvent()?.setExpanded(true);
break;
}
}
handleKeyEnter(e) {
e.preventDefault();
const { excelMode, readOnly } = this.params;
if (!excelMode || !!readOnly) {
return;
}
this.params.onAction("apply", void 0, e);
if (this.params.excelMode === "mac") {
this.eMiniFilter.getInputElement().select();
}
}
setModelAndRefresh(values) {
return this.setSelectedModel(values).then(() => {
if (this.isAlive()) {
this.checkAndRefreshVirtualList();
}
});
}
setModelIntoUi(model) {
this.setMiniFilter(this.params.state.state?.miniFilterValue ?? null);
const values = model == null ? null : model.values;
return this.setModelAndRefresh(values);
}
getModelFromUi() {
const values = this.getSelectedModel();
if (!values) {
return null;
}
return { values, filterType: this.filterType };
}
areNonNullModelsEqual(a, b) {
return (0, import_ag_grid_community92._areEqual)(a.values, b.values);
}
setIsLoading(isLoading) {
(0, import_ag_grid_community92._setDisplayed)(this.eFilterLoading, isLoading);
if (!isLoading) {
this.hardRefreshVirtualList = true;
}
}
initialiseFilterBodyUi() {
this.initVirtualList();
this.initMiniFilter();
this.initLoading();
}
initLoading() {
const loadingIcon = (0, import_ag_grid_community92._createIconNoSpan)("setFilterLoading", this.beans, this.params.column);
if (loadingIcon) {
this.eFilterLoadingIcon.appendChild(loadingIcon);
}
}
initVirtualList() {
const filterListName = translateForSetFilter(this, "ariaFilterList");
const isTree = !!this.params.treeList;
const virtualList = this.virtualList = this.createBean(
new VirtualList({
cssIdentifier: "filter",
ariaRole: isTree ? "tree" : "listbox",
listName: filterListName
})
);
const eSetFilterList = this.eSetFilterList;
if (isTree) {
eSetFilterList.classList.add("ag-set-filter-tree-list");
}
eSetFilterList.appendChild(virtualList.getGui());
const { cellHeight } = this.params;
if (cellHeight != null) {
virtualList.setRowHeight(cellHeight);
}
const componentCreator = (item, listItemElement) => this.createSetListItem(item, isTree, listItemElement);
virtualList.setComponentCreator(componentCreator);
const componentUpdater = (item, component) => this.updateSetListItem(item, component);
virtualList.setComponentUpdater(componentUpdater);
this.createVirtualListModel(this.params);
}
createVirtualListModel(params) {
let model;
if (params.suppressSelectAll) {
model = new ModelWrapper(this.displayValueModel);
} else {
model = new ModelWrapperWithSelectAll(
this.displayValueModel,
this.showAddCurrentSelectionToFilter.bind(this)
);
}
if (params.treeList) {
model = new TreeModelWrapper(model);
}
this.virtualList.setModel(model);
}
getSelectAllLabel() {
const key = this.miniFilterText == null || !this.params.excelMode ? "selectAll" : "selectAllSearchResults";
return translateForSetFilter(this, key);
}
getAddSelectionToFilterLabel() {
return translateForSetFilter(this, "addCurrentSelectionToFilter");
}
createSetListItem(item, isTree, focusWrapper) {
const groupsExist = this.displayValueModel.hasGroups();
const { isSelected, isExpanded } = this.isSelectedExpanded(item);
const { value, depth, isGroup, hasIndeterminateExpandState, selectedListener, expandedListener } = this.newSetListItemAttributes(item);
const itemParams = {
focusWrapper,
value,
params: this.params,
translate: (translateKey) => translateForSetFilter(this, translateKey),
valueFormatter: this.handler.valueFormatter,
item,
isSelected,
isTree,
depth,
groupsExist,
isGroup,
isExpanded,
hasIndeterminateExpandState
};
const listItem = this.createBean(new SetFilterListItem(itemParams));
listItem.addEventListener("selectionChanged", selectedListener);
if (expandedListener) {
listItem.addEventListener("expandedChanged", expandedListener);
}
return listItem;
}
newSetTreeItemAttributes(item) {
const groupsExist = this.displayValueModel.hasGroups();
if (item.key === SET_FILTER_SELECT_ALL) {
return {
value: () => this.getSelectAllLabel(),
isGroup: groupsExist,
depth: item.depth,
hasIndeterminateExpandState: true,
selectedListener: (e) => this.onSelectAll(e.isSelected),
expandedListener: (e) => this.onExpandAll(e.item, e.isExpanded)
};
}
if (item.key === SET_FILTER_ADD_SELECTION_TO_FILTER) {
return {
value: () => this.getAddSelectionToFilterLabel(),
depth: item.depth,
isGroup: false,
hasIndeterminateExpandState: false,
selectedListener: (e) => {
this.addCurrentSelectionToFilter = e.isSelected;
this.refreshAfterSelection();
}
};
}
if (item.children) {
return {
value: this.params.treeListFormatter?.(item.treeKey, item.depth, item.parentTreeKeys) ?? item.treeKey,
depth: item.depth,
isGroup: true,
selectedListener: (e) => this.onGroupItemSelected(e.item, e.isSelected),
expandedListener: (e) => this.onExpandedChanged(e.item, e.isExpanded)
};
}
return {
value: this.params.treeListFormatter?.(item.treeKey, item.depth, item.parentTreeKeys) ?? item.treeKey,
depth: item.depth,
selectedListener: (e) => this.onItemSelected(e.item.key, e.isSelected)
};
}
newSetListItemAttributes(item) {
if (this.isSetFilterModelTreeItem(item)) {
return this.newSetTreeItemAttributes(item);
}
if (item === SET_FILTER_SELECT_ALL) {
return {
value: () => this.getSelectAllLabel(),
selectedListener: (e) => this.onSelectAll(e.isSelected)
};
}
if (item === SET_FILTER_ADD_SELECTION_TO_FILTER) {
return {
value: () => this.getAddSelectionToFilterLabel(),
selectedListener: (e) => {
this.addCurrentSelectionToFilter = e.isSelected;
this.refreshAfterSelection();
}
};
}
return {
value: this.handler.valueModel.allValues.get(item) ?? null,
selectedListener: (e) => this.onItemSelected(e.item, e.isSelected)
};
}
updateSetListItem(item, component) {
const { isSelected, isExpanded } = this.isSelectedExpanded(item);
component.refresh(item, isSelected, isExpanded);
}
isSelectedExpanded(item) {
let isSelected;
let isExpanded;
if (this.isSetFilterModelTreeItem(item)) {
isExpanded = item.expanded;
if (item.key === SET_FILTER_SELECT_ALL) {
isSelected = this.isSelectAllSelected();
} else if (item.key === SET_FILTER_ADD_SELECTION_TO_FILTER) {
isSelected = this.isAddCurrentSelectionToFilterChecked();
} else if (item.children) {
isSelected = this.areAllChildrenSelected(item);
} else {
isSelected = this.selectedKeys.has(item.key);
}
} else {
if (item === SET_FILTER_SELECT_ALL) {
isSelected = this.isSelectAllSelected();
} else if (item === SET_FILTER_ADD_SELECTION_TO_FILTER) {
isSelected = this.isAddCurrentSelectionToFilterChecked();
} else {
isSelected = this.selectedKeys.has(item);
}
}
return { isSelected, isExpanded };
}
isSetFilterModelTreeItem(item) {
return item?.treeKey !== void 0;
}
initMiniFilter() {
const { eMiniFilter } = this;
this.updateMiniFilter();
eMiniFilter.onValueChange(() => this.onMiniFilterInput());
eMiniFilter.setInputAriaLabel(translateForSetFilter(this, "ariaSearchFilterValues"));
this.addManagedElementListeners(eMiniFilter.getInputElement(), {
keydown: (e) => this.onMiniFilterKeyDown(e)
});
}
updateMiniFilter() {
const { eMiniFilter, miniFilterText, params } = this;
eMiniFilter.setDisplayed(!params.suppressMiniFilter);
eMiniFilter.setValue(miniFilterText);
}
// we need to have the GUI attached before we can draw the virtual rows, as the
// virtual row logic needs info about the GUI state
afterGuiAttached(params) {
super.afterGuiAttached(params);
this.resetExpansion();
this.refreshVirtualList();
const { eMiniFilter } = this;
eMiniFilter.setInputPlaceholder(translateForSetFilter(this, "searchOoo"));
if (!params || !params.suppressFocus) {
if (eMiniFilter.isDisplayed()) {
eMiniFilter.getFocusableElement().focus();
} else {
this.virtualList.awaitStable(() => this.virtualList.focusRow(0));
}
}
}
afterGuiDetached() {
super.afterGuiDetached();
const { column, excelMode, model, onStateChange } = this.params;
if (this.beans.colFilter?.shouldKeepStateOnDetach(column)) {
return;
}
if (excelMode) {
this.resetMiniFilter();
}
if (excelMode || model !== this.state.model) {
onStateChange({
model,
state: this.getState()
});
this.showOrHideResults();
}
}
canApply(model) {
return this.params.excelMode ? model == null || model.values.length > 0 : true;
}
/**
* @deprecated v34 Internal method - should only be called by the grid.
*/
onNewRowsLoaded() {
}
/**
* @deprecated v34 Use the same method on the filter handler (`api.getColumnFilterHandler()`) instead.
*/
setFilterValues(values) {
(0, import_ag_grid_community92._warn)(283);
this.handler.setFilterValues(values);
}
/**
* @deprecated v34 Use the same method on the filter handler (`api.getColumnFilterHandler()`) instead.
*/
resetFilterValues() {
(0, import_ag_grid_community92._warn)(283);
this.handler.resetFilterValues();
}
/**
* @deprecated v34 Use the same method on the filter handler (`api.getColumnFilterHandler()`) instead.
*/
refreshFilterValues() {
(0, import_ag_grid_community92._warn)(283);
this.doRefreshFilterValues();
}
doRefreshFilterValues() {
this.handler.refreshFilterValues();
}
/**
* @deprecated v34 Internal method - should only be called by the grid.
*/
onAnyFilterChanged() {
}
onMiniFilterInput() {
if (!this.doSetMiniFilter(this.eMiniFilter.getValue())) {
return;
}
const { applyMiniFilterWhileTyping, readOnly, excelMode } = this.params;
const updateSelections = !readOnly && (applyMiniFilterWhileTyping || !!excelMode);
const apply = applyMiniFilterWhileTyping && !readOnly ? "debounce" : void 0;
this.updateUiAfterMiniFilterChange(updateSelections, apply);
}
updateUiAfterMiniFilterChange(updateSelections, apply) {
if (updateSelections) {
const { excelMode, readOnly, model } = this.params;
if (excelMode && !readOnly && this.miniFilterText == null) {
this.setModelAndRefresh(model?.values ?? null);
} else {
this.selectAllMatchingMiniFilter(true);
}
}
this.checkAndRefreshVirtualList();
this.onUiChanged(updateSelections ? apply : "prevent");
this.showOrHideResults();
}
showOrHideResults() {
const hideResults = this.miniFilterText != null && this.displayValueModel.getDisplayedValueCount() < 1;
(0, import_ag_grid_community92._setDisplayed)(this.eFilterNoMatches, hideResults);
(0, import_ag_grid_community92._setDisplayed)(this.eSetFilterList, !hideResults);
}
resetMiniFilter() {
this.eMiniFilter.setValue(null, true);
this.doSetMiniFilter(null);
}
onMiniFilterKeyDown(e) {
const { excelMode, readOnly } = this.params;
if (e.key === import_ag_grid_community92.KeyCode.ENTER && !excelMode && !readOnly) {
this.updateUiAfterMiniFilterChange(true, "immediately");
}
}
focusRowIfAlive(rowIndex) {
if (rowIndex == null) {
return Promise.resolve();
}
return new Promise((res) => {
window.setTimeout(() => {
if (this.isAlive()) {
this.virtualList.focusRow(rowIndex);
}
res();
}, 0);
});
}
onSelectAll(isSelected) {
if (isSelected) {
this.selectAllMatchingMiniFilter();
} else {
this.deselectAllMatchingMiniFilter();
}
this.refreshAfterSelection();
}
onGroupItemSelected(item, isSelected) {
const recursiveGroupSelection = (i) => {
if (!i.filterPasses) {
return;
}
const children = i.children;
if (children) {
for (const childItem of children.values()) {
recursiveGroupSelection(childItem);
}
} else {
this.setKeySelected(i.key, isSelected);
}
};
recursiveGroupSelection(item);
this.refreshAfterSelection();
}
onItemSelected(key, isSelected) {
this.setKeySelected(key, isSelected);
this.refreshAfterSelection();
}
onExpandAll(item, isExpanded) {
const recursiveExpansion = (i) => {
if (i.filterPasses && i.available && i.children) {
for (const childItem of i.children.values()) {
recursiveExpansion(childItem);
}
i.expanded = isExpanded;
}
};
recursiveExpansion(item);
this.refreshAfterExpansion();
}
onExpandedChanged(item, isExpanded) {
item.expanded = isExpanded;
this.refreshAfterExpansion();
}
refreshAfterExpansion() {
const focusedRow = this.virtualList.getLastFocusedRow();
this.updateDisplayedValues("expansion");
this.checkAndRefreshVirtualList();
this.focusRowIfAlive(focusedRow);
}
refreshAfterSelection() {
const focusedRow = this.virtualList.getLastFocusedRow();
this.checkAndRefreshVirtualList();
this.onUiChanged();
this.focusRowIfAlive(focusedRow);
}
setMiniFilter(newMiniFilter) {
this.eMiniFilter.setValue(newMiniFilter);
this.onMiniFilterInput();
}
/** Sets mini filter value. Returns true if it changed from last value, otherwise false. */
doSetMiniFilter(value) {
value = (0, import_ag_grid_community92._makeNull)(value);
if (this.miniFilterText === value) {
return false;
}
if (value === null) {
this.addCurrentSelectionToFilter = false;
}
this.miniFilterText = value;
this.updateDisplayedValues("miniFilter");
return true;
}
getMiniFilter() {
return this.miniFilterText;
}
getUiChangeEventParams() {
return {
miniFilterValue: this.miniFilterText
};
}
getState() {
const miniFilterValue = this.miniFilterText;
return miniFilterValue ? { miniFilterValue } : void 0;
}
checkAndRefreshVirtualList() {
this.virtualList.refresh(!this.hardRefreshVirtualList);
if (this.hardRefreshVirtualList) {
this.hardRefreshVirtualList = false;
}
}
/**
* @deprecated v34 Use the same method on the filter handler (`api.getColumnFilterHandler()`) instead.
*/
getFilterKeys() {
(0, import_ag_grid_community92._warn)(283);
return this.handler.getFilterKeys();
}
/**
* @deprecated v34 Use the same method on the filter handler (`api.getColumnFilterHandler()`) instead.
*/
getFilterValues() {
(0, import_ag_grid_community92._warn)(283);
return this.handler.getFilterValues();
}
refreshVirtualList() {
if (this.params.refreshValuesOnOpen) {
this.doRefreshFilterValues();
} else {
this.checkAndRefreshVirtualList();
}
}
isSelectAllSelected() {
if (!this.params.defaultToNothingSelected) {
if (this.hasSelections() && this.isNothingVisibleSelected()) {
return false;
}
if (this.isEverythingVisibleSelected()) {
return true;
}
} else {
if (this.hasSelections() && this.isEverythingVisibleSelected()) {
return true;
}
if (this.isNothingVisibleSelected()) {
return false;
}
}
return void 0;
}
areAllChildrenSelected(item) {
const recursiveChildSelectionCheck = (i) => {
if (i.children) {
let someTrue = false;
let someFalse = false;
for (const child of i.children.values()) {
if (!child.filterPasses || !child.available) {
continue;
}
const childSelected = recursiveChildSelectionCheck(child);
if (childSelected === void 0) {
return void 0;
}
if (childSelected) {
someTrue = true;
} else {
someFalse = true;
}
if (someTrue && someFalse) {
return void 0;
}
}
return someTrue;
} else {
return this.selectedKeys.has(i.key);
}
};
if (!this.params.defaultToNothingSelected) {
return recursiveChildSelectionCheck(item);
} else {
return this.hasSelections() && recursiveChildSelectionCheck(item);
}
}
resetExpansion() {
if (!this.params.treeList) {
return;
}
const selectAllItem = this.displayValueModel.getSelectAllItem();
if (this.isSetFilterModelTreeItem(selectAllItem)) {
const recursiveCollapse = (i) => {
const children = i.children;
if (children) {
for (const childItem of children.values()) {
recursiveCollapse(childItem);
}
i.expanded = false;
}
};
recursiveCollapse(selectAllItem);
this.updateDisplayedValues("expansion");
}
}
getModelAsString(model) {
return this.handler.getModelAsString(model);
}
getPositionableElement() {
return this.eSetFilterList;
}
updateDisplayedValues(source, allKeys) {
if (source === "expansion") {
this.displayValueModel.refresh();
return;
}
const handler = this.handler;
const valueModel = handler.valueModel;
if (this.miniFilterText == null) {
this.displayValueModel.updateDisplayedValuesToAllAvailable(
(key) => valueModel.allValues.get(key) ?? null,
allKeys,
valueModel.availableKeys,
source
);
return;
}
const formattedFilterText = handler.caseFormat(this.formatter(this.miniFilterText) || "");
const matchesFilter = (valueToCheck) => valueToCheck != null && handler.caseFormat(valueToCheck).indexOf(formattedFilterText) >= 0;
const nullMatchesFilter = !!this.params.excelMode && matchesFilter(translateForSetFilter(this, "blanks"));
this.displayValueModel.updateDisplayedValuesToMatchMiniFilter(
(key) => valueModel.allValues.get(key) ?? null,
allKeys,
valueModel.availableKeys,
matchesFilter,
nullMatchesFilter,
source
);
}
hasSelections() {
return this.params.defaultToNothingSelected ? this.selectedKeys.size > 0 : this.handler.valueModel.allValues.size !== this.selectedKeys.size;
}
isInWindowsExcelMode() {
return this.params.excelMode === "windows";
}
isAddCurrentSelectionToFilterChecked() {
return this.isInWindowsExcelMode() && this.addCurrentSelectionToFilter;
}
showAddCurrentSelectionToFilter() {
return this.isInWindowsExcelMode() && (0, import_ag_grid_community92._exists)(this.miniFilterText) && this.miniFilterText.length > 0;
}
selectAllMatchingMiniFilter(clearExistingSelection = false) {
if (this.miniFilterText == null) {
this.selectedKeys = new Set(this.handler.valueModel.allValues.keys());
} else {
if (clearExistingSelection) {
this.selectedKeys.clear();
}
this.displayValueModel.forEachDisplayedKey((key) => this.selectedKeys.add(key));
}
}
deselectAllMatchingMiniFilter() {
if (this.miniFilterText == null) {
this.selectedKeys.clear();
} else {
this.displayValueModel.forEachDisplayedKey((key) => this.selectedKeys.delete(key));
}
}
setKeySelected(key, selected) {
if (selected) {
this.selectedKeys.add(key);
} else {
if (this.params.excelMode && this.isEverythingVisibleSelected()) {
this.resetSelectionState(this.displayValueModel.getDisplayedKeys());
}
this.selectedKeys.delete(key);
}
}
isEverythingVisibleSelected() {
return !this.displayValueModel.someDisplayedKey((it) => !this.selectedKeys.has(it));
}
isNothingVisibleSelected() {
return !this.displayValueModel.someDisplayedKey((it) => this.selectedKeys.has(it));
}
getSelectedModel() {
if (!this.hasSelections()) {
return null;
}
const filteringKeys = this.isAddCurrentSelectionToFilterChecked() ? this.params.model?.values : void 0;
if (filteringKeys?.length) {
if (this.selectedKeys) {
const modelKeys = /* @__PURE__ */ new Set([...filteringKeys, ...this.selectedKeys]);
return Array.from(modelKeys);
}
return Array.from(filteringKeys);
}
return Array.from(this.selectedKeys);
}
setSelectedModel(model) {
const handler = this.handler;
const valueModel = handler.valueModel;
return valueModel.allKeys.then((keys) => {
if (model == null) {
this.resetSelectionState(keys ?? []);
} else {
this.selectedKeys.clear();
const existingFormattedKeys = /* @__PURE__ */ new Map();
valueModel.allValues.forEach((_value, key) => {
existingFormattedKeys.set(handler.caseFormat(key), key);
});
model.forEach((unformattedKey) => {
const formattedKey = handler.caseFormat((0, import_ag_grid_community92._makeNull)(unformattedKey));
const existingUnformattedKey = existingFormattedKeys.get(formattedKey);
if (existingUnformattedKey !== void 0) {
this.selectedKeys.add(existingUnformattedKey);
}
});
}
});
}
resetSelectionState(keys) {
if (this.params.defaultToNothingSelected) {
this.selectedKeys.clear();
} else {
this.selectedKeys = new Set(keys);
}
}
getFilterHandler() {
return this.handler;
}
destroy() {
this.virtualList = this.destroyBean(this.virtualList);
this.handlerDestroyFuncs?.forEach((func) => func());
this.handler = void 0;
this.displayValueModel = void 0;
this.selectedKeys.clear();
super.destroy();
}
};
var ModelWrapper = class {
constructor(model) {
this.model = model;
}
getRowCount() {
return this.model.getDisplayedValueCount();
}
getRow(index) {
return this.model.getDisplayedItem(index);
}
areRowsEqual(oldRow, newRow) {
return oldRow === newRow;
}
};
var ModelWrapperWithSelectAll = class {
constructor(model, showAddCurrentSelectionToFilter) {
this.model = model;
this.showAddCurrentSelectionToFilter = showAddCurrentSelectionToFilter;
}
getRowCount() {
const showAddCurrentSelectionToFilter = this.showAddCurrentSelectionToFilter();
const outboundItems = showAddCurrentSelectionToFilter ? 2 : 1;
return this.model.getDisplayedValueCount() + outboundItems;
}
getRow(index) {
if (index === 0) {
return this.model.getSelectAllItem();
}
const showAddCurrentSelectionToFilter = this.showAddCurrentSelectionToFilter();
const outboundItems = showAddCurrentSelectionToFilter ? 2 : 1;
if (index === 1 && showAddCurrentSelectionToFilter) {
return this.model.getAddSelectionToFilterItem();
}
return this.model.getDisplayedItem(index - outboundItems);
}
areRowsEqual(oldRow, newRow) {
return oldRow === newRow;
}
};
var TreeModelWrapper = class {
constructor(model) {
this.model = model;
}
getRowCount() {
return this.model.getRowCount();
}
getRow(index) {
return this.model.getRow(index);
}
areRowsEqual(oldRow, newRow) {
if (oldRow == null && newRow == null) {
return true;
}
return oldRow != null && newRow != null && oldRow.treeKey === newRow.treeKey && oldRow.depth === newRow.depth;
}
};
// packages/ag-grid-enterprise/src/setFilter/setFilterHandler.ts
var import_ag_grid_community96 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/setFilter/clientSideValueExtractor.ts
var import_ag_grid_community93 = require("ag-grid-community");
var import_ag_grid_community94 = require("ag-grid-community");
var ClientSideValuesExtractor = class extends import_ag_grid_community94.BeanStub {
constructor(createKey, caseFormat, getValue, isTreeDataOrGrouping, isTreeData) {
super();
this.createKey = createKey;
this.caseFormat = caseFormat;
this.getValue = getValue;
this.isTreeDataOrGrouping = isTreeDataOrGrouping;
this.isTreeData = isTreeData;
}
extractUniqueValuesAsync(predicate, existingValues) {
return new import_ag_grid_community93.AgPromise((resolve) => {
if (this.beans.rowModel.isRowDataLoaded()) {
resolve(this.extractUniqueValues(predicate, existingValues));
} else {
const [destroyFunc] = this.addManagedEventListeners({
rowCountReady: () => {
destroyFunc?.();
resolve(this.extractUniqueValues(predicate, existingValues));
}
});
}
});
}
extractUniqueValues(predicate, existingValues) {
const values = /* @__PURE__ */ new Map();
const existingFormattedKeys = this.extractExistingFormattedKeys(existingValues);
const formattedKeys = /* @__PURE__ */ new Set();
const treeData = this.isTreeData();
const treeDataOrGrouping = this.isTreeDataOrGrouping();
const groupedCols = this.beans.rowGroupColsSvc?.columns;
const groupAllowUnbalanced = this.gos.get("groupAllowUnbalanced");
const addValue = (unformattedKey, value) => {
const formattedKey = this.caseFormat(unformattedKey);
if (!formattedKeys.has(formattedKey)) {
formattedKeys.add(formattedKey);
let keyToAdd = unformattedKey;
let valueToAdd = (0, import_ag_grid_community93._makeNull)(value);
const existingUnformattedKey = existingFormattedKeys?.get(formattedKey);
if (existingUnformattedKey != null) {
keyToAdd = existingUnformattedKey;
valueToAdd = existingValues.get(existingUnformattedKey);
}
values.set(keyToAdd, valueToAdd);
}
};
this.beans.rowModel.forEachLeafNode((node) => {
if (!node.data || !predicate(node)) {
return;
}
if (treeDataOrGrouping) {
this.addValueForTreeDataOrGrouping(node, treeData, groupedCols, addValue, groupAllowUnbalanced);
return;
}
const value = this.getValue(node);
if (value != null && Array.isArray(value)) {
value.forEach((x) => {
addValue(this.createKey(x, node), x);
});
if (value.length === 0) {
addValue(null, null);
}
} else {
addValue(this.createKey(value, node), value);
}
});
return values;
}
addValueForTreeDataOrGrouping(node, treeData, groupedCols = [], addValue, groupAllowUnbalanced) {
let dataPath;
if (treeData) {
if (node.childrenAfterGroup?.length) {
return;
}
dataPath = node.getRoute() ?? [node.key ?? node.id];
} else {
dataPath = groupedCols.map((groupCol) => this.beans.valueSvc.getKeyForNode(groupCol, node));
dataPath.push(this.getValue(node));
}
const processedDataPath = processDataPath(dataPath, treeData, groupAllowUnbalanced);
addValue(this.createKey(processedDataPath), processedDataPath);
}
extractExistingFormattedKeys(existingValues) {
if (!existingValues) {
return null;
}
const existingFormattedKeys = /* @__PURE__ */ new Map();
existingValues.forEach((_value, key) => {
existingFormattedKeys.set(this.caseFormat(key), key);
});
return existingFormattedKeys;
}
};
// packages/ag-grid-enterprise/src/setFilter/setFilterAppliedModel.ts
var SetFilterAppliedModel = class {
constructor(caseFormat) {
this.caseFormat = caseFormat;
// This attribute contains keys that are actually used for filtering.
// These keys take into account case sensitivity:
// - When filtering is case-insensitive, all filtering keys are converted to upper case and stored here.
this.keys = null;
}
/** No model applied */
isNull() {
return this.keys == null;
}
/** Nothing selected */
isEmpty() {
return !this.keys?.size;
}
update(appliedModel) {
const keys = /* @__PURE__ */ new Set();
this.keys = keys;
const values = appliedModel?.values;
if (values) {
const caseFormat = this.caseFormat;
for (let i = 0, len = values.length; i < len; i++) {
keys.add(caseFormat(values[i]));
}
}
}
has(key) {
return !!this.keys?.has(this.caseFormat(key));
}
destroy() {
this.keys = null;
}
};
// packages/ag-grid-enterprise/src/setFilter/setValueModel.ts
var import_ag_grid_community95 = require("ag-grid-community");
var SetFilterModelValuesType = /* @__PURE__ */ ((SetFilterModelValuesType2) => {
SetFilterModelValuesType2[SetFilterModelValuesType2["PROVIDED_LIST"] = 0] = "PROVIDED_LIST";
SetFilterModelValuesType2[SetFilterModelValuesType2["PROVIDED_CALLBACK"] = 1] = "PROVIDED_CALLBACK";
SetFilterModelValuesType2[SetFilterModelValuesType2["TAKEN_FROM_GRID_VALUES"] = 2] = "TAKEN_FROM_GRID_VALUES";
return SetFilterModelValuesType2;
})(SetFilterModelValuesType || {});
var setValueModel_default = SetFilterModelValuesType;
var SetValueModel = class extends import_ag_grid_community95.BeanStub {
constructor(clientSideValuesExtractor, caseFormat, createKey, isTreeDataOrGrouping, params) {
super();
this.clientSideValuesExtractor = clientSideValuesExtractor;
this.caseFormat = caseFormat;
this.createKey = createKey;
this.isTreeDataOrGrouping = isTreeDataOrGrouping;
this.params = params;
/** All possible values for the filter, sorted if required. */
this.allValues = /* @__PURE__ */ new Map();
/** Remaining keys when filters from other columns have been applied. */
this.availableKeys = /* @__PURE__ */ new Set();
this.providedValues = null;
this.initialised = false;
}
postConstruct() {
const params = this.params;
const values = params.handlerParams.filterParams.values;
this.updateParams(params);
if (values == null) {
this.valuesType = 2 /* TAKEN_FROM_GRID_VALUES */;
} else {
this.valuesType = Array.isArray(values) ? 0 /* PROVIDED_LIST */ : 1 /* PROVIDED_CALLBACK */;
this.providedValues = values;
}
this.updateAllValues();
}
refresh(params) {
const handlerParams = params.handlerParams;
if (handlerParams.source !== "colDef") {
return;
}
const { values, suppressSorting } = handlerParams.filterParams;
const currentProvidedValues = this.providedValues;
const currentSuppressSorting = this.params.handlerParams.filterParams.suppressSorting;
this.params = params;
this.updateParams(params);
this.providedValues = values ?? null;
if (this.providedValues !== currentProvidedValues || suppressSorting !== currentSuppressSorting) {
if (!values || values.length === 0) {
this.valuesType = 2 /* TAKEN_FROM_GRID_VALUES */;
this.providedValues = null;
} else {
this.valuesType = Array.isArray(values) ? 0 /* PROVIDED_LIST */ : 1 /* PROVIDED_CALLBACK */;
}
this.updateAllValues();
}
}
updateParams(params) {
const {
handlerParams: {
colDef,
filterParams: { comparator, treeList, treeListPathGetter }
},
usingComplexObjects
} = params;
const keyComparator = comparator ?? colDef.comparator;
const treeDataOrGrouping = this.isTreeDataOrGrouping();
let entryComparator;
if (treeDataOrGrouping && !keyComparator) {
entryComparator = createTreeDataOrGroupingComparator();
} else if (treeList && !treeListPathGetter && !keyComparator) {
entryComparator = ([_aKey, aValue], [_bKey, bValue]) => (0, import_ag_grid_community95._defaultComparator)(aValue, bValue);
} else {
entryComparator = ([_aKey, aValue], [_bKey, bValue]) => keyComparator(aValue, bValue);
}
this.entryComparator = entryComparator;
this.keyComparator = keyComparator ?? import_ag_grid_community95._defaultComparator;
this.compareByValue = !!(usingComplexObjects && keyComparator || treeDataOrGrouping || treeList && !treeListPathGetter);
}
updateAllValues() {
this.allKeys = new import_ag_grid_community95.AgPromise((resolve) => {
switch (this.valuesType) {
case 2 /* TAKEN_FROM_GRID_VALUES */:
this.getValuesFromRowsAsync().then((values) => resolve(this.processAllValues(values)));
break;
case 0 /* PROVIDED_LIST */: {
resolve(
this.processAllValues(
this.uniqueValues(this.validateProvidedValues(this.providedValues))
)
);
break;
}
case 1 /* PROVIDED_CALLBACK */: {
this.dispatchLocalEvent({ type: "loadingStart" });
const callback = this.providedValues;
const { column, colDef } = this.params.handlerParams;
const params = (0, import_ag_grid_community95._addGridCommonParams)(this.gos, {
success: (values) => {
this.dispatchLocalEvent({ type: "loadingEnd" });
resolve(this.processAllValues(this.uniqueValues(this.validateProvidedValues(values))));
},
colDef,
column
});
window.setTimeout(() => callback(params), 0);
break;
}
}
});
this.allKeys.then((values) => {
this.updateAvailableKeys(values ?? []);
this.initialised = true;
});
return this.allKeys;
}
getAvailableValues(predicate) {
return this.sortKeys(this.getValuesFromRows(predicate));
}
overrideValues(valuesToUse) {
return this.allKeys.then(() => {
this.valuesType = 0 /* PROVIDED_LIST */;
this.providedValues = valuesToUse;
});
}
refreshAvailable() {
return new import_ag_grid_community95.AgPromise((resolve) => {
if (this.showAvailableOnly()) {
this.allKeys.then((keys) => {
const updatedKeys = keys ?? [];
this.updateAvailableKeys(updatedKeys);
resolve(true);
});
return;
}
resolve(false);
});
}
refreshAll() {
return new import_ag_grid_community95.AgPromise((resolve) => {
this.allKeys.then(() => {
this.updateAllValues().then(() => {
resolve();
});
});
});
}
isLoading() {
return !this.initialised && this.valuesType === 1 /* PROVIDED_CALLBACK */;
}
isInitialised() {
return this.initialised;
}
getValueForFormatter(key) {
return this.initialised ? this.allValues.get(key) : key;
}
getAvailableKeys(values) {
return this.initialised ? values.filter((v) => this.availableKeys.has(v)) : values;
}
getParamsForValuesFromRows(removeUnavailableValues) {
if (!this.clientSideValuesExtractor) {
(0, import_ag_grid_community95._error)(113);
return void 0;
}
const existingValues = removeUnavailableValues && !this.params.handlerParams.filterParams.caseSensitive ? this.allValues : void 0;
return existingValues;
}
getValuesFromRows(predicate) {
const existingValues = this.getParamsForValuesFromRows(true);
return this.clientSideValuesExtractor?.extractUniqueValues(predicate, existingValues) ?? null;
}
getValuesFromRowsAsync() {
const existingValues = this.getParamsForValuesFromRows(false);
return this.clientSideValuesExtractor?.extractUniqueValuesAsync(() => true, existingValues) ?? import_ag_grid_community95.AgPromise.resolve(null);
}
processAllValues(values) {
const sortedKeys = this.sortKeys(values);
this.allValues = values ?? /* @__PURE__ */ new Map();
return sortedKeys;
}
uniqueValues(values) {
const uniqueValues = /* @__PURE__ */ new Map();
const formattedKeys = /* @__PURE__ */ new Set();
const { caseFormat, createKey } = this;
(values ?? []).forEach((value) => {
const valueToUse = (0, import_ag_grid_community95._makeNull)(value);
const unformattedKey = createKey(valueToUse);
const formattedKey = caseFormat(unformattedKey);
if (!formattedKeys.has(formattedKey)) {
formattedKeys.add(formattedKey);
uniqueValues.set(unformattedKey, valueToUse);
}
});
return uniqueValues;
}
validateProvidedValues(values) {
if (this.params.usingComplexObjects && values?.length) {
const firstValue = values[0];
if (firstValue && typeof firstValue !== "object" && typeof firstValue !== "function") {
const firstKey = this.createKey(firstValue);
if (firstKey == null) {
(0, import_ag_grid_community95._warn)(209);
} else {
(0, import_ag_grid_community95._warn)(210);
}
}
}
return values;
}
sortKeys(nullableValues) {
const values = nullableValues ?? /* @__PURE__ */ new Map();
const filterParams = this.params.handlerParams.filterParams;
if (filterParams.suppressSorting) {
return Array.from(values.keys());
}
let sortedKeys;
if (this.compareByValue) {
sortedKeys = Array.from(values.entries()).sort(this.entryComparator).map(([key]) => key);
} else {
sortedKeys = Array.from(values.keys()).sort(this.keyComparator);
}
if (filterParams.excelMode && values.has(null)) {
sortedKeys = sortedKeys.filter((v) => v != null);
sortedKeys.push(null);
}
return sortedKeys;
}
showAvailableOnly() {
return this.valuesType === 2 /* TAKEN_FROM_GRID_VALUES */;
}
updateAvailableKeys(allKeys) {
const availableKeys = this.showAvailableOnly() ? this.getAvailableValues((node) => this.params.handlerParams.doesRowPassOtherFilter(node)) : allKeys;
this.availableKeys = new Set(availableKeys);
this.dispatchLocalEvent({ type: "availableValuesChanged" });
}
};
// packages/ag-grid-enterprise/src/setFilter/setFilterHandler.ts
var SetFilterHandler = class extends import_ag_grid_community96.BeanStub {
constructor() {
super(...arguments);
/** Used to get the filter type for filter models. */
this.filterType = "set";
this.treeDataTreeList = false;
this.groupingTreeList = false;
this.caseSensitive = false;
this.noValueFormatterSupplied = false;
}
init(params) {
this.updateParams(params);
const isTreeDataOrGrouping = this.isTreeDataOrGrouping.bind(this);
const isTreeData = () => this.treeDataTreeList;
const createKey = this.createKey;
const caseFormat = this.caseFormat.bind(this);
const { gos, beans } = this;
const clientSideValuesExtractor = (0, import_ag_grid_community96._isClientSideRowModel)(gos, beans.rowModel) ? this.createManagedBean(
new ClientSideValuesExtractor(
createKey,
caseFormat,
params.getValue,
isTreeDataOrGrouping,
isTreeData
)
) : void 0;
this.valueModel = this.createManagedBean(
new SetValueModel(clientSideValuesExtractor, caseFormat, createKey, isTreeDataOrGrouping, {
handlerParams: params,
usingComplexObjects: !!(params.filterParams.keyCreator ?? params.colDef.keyCreator)
})
);
this.appliedModel = new SetFilterAppliedModel(this.caseFormat.bind(this));
this.appliedModel.update(params.model);
this.validateModel(params);
this.addEventListenersForDataChanges();
}
refresh(params) {
this.updateParams(params);
this.valueModel.refresh({
handlerParams: params,
usingComplexObjects: !!(params.filterParams.keyCreator ?? params.colDef.keyCreator)
});
this.appliedModel.update(params.model);
this.validateModel(params);
}
updateParams(params) {
this.params = params;
const {
colDef,
filterParams: { caseSensitive, treeList, keyCreator, valueFormatter }
} = params;
this.caseSensitive = !!caseSensitive;
const isGroupCol = !!colDef.showRowGroup;
this.treeDataTreeList = this.gos.get("treeData") && !!treeList && isGroupCol;
this.groupingTreeList = !!this.beans.rowGroupColsSvc?.columns.length && !!treeList && isGroupCol;
const resolvedKeyCreator = keyCreator ?? colDef.keyCreator;
this.createKey = this.generateCreateKey(resolvedKeyCreator, this.isTreeDataOrGrouping());
this.setValueFormatter(valueFormatter, resolvedKeyCreator, !!treeList, !!colDef.refData);
}
doesFilterPass(params) {
const { appliedModel, treeDataTreeList, groupingTreeList } = this;
if (appliedModel.isNull()) {
return true;
}
if (appliedModel.isEmpty()) {
return false;
}
const { node } = params;
if (treeDataTreeList) {
return this.doesFilterPassForTreeData(node);
}
if (groupingTreeList) {
return this.doesFilterPassForGrouping(node);
}
const value = this.params.getValue(node);
if (value != null && Array.isArray(value)) {
if (value.length === 0) {
return appliedModel.has(null);
}
return value.some((v) => appliedModel.has(this.createKey(v, node)));
}
return appliedModel.has(this.createKey(value, node));
}
getFormattedValue(key) {
let value = this.valueModel.getValueForFormatter(key);
if (this.noValueFormatterSupplied && this.isTreeDataOrGrouping() && Array.isArray(value)) {
value = (0, import_ag_grid_community96._last)(value);
}
const formattedValue = this.beans.valueSvc.formatValue(
this.params.column,
null,
value,
this.valueFormatter,
false
);
return (formattedValue == null ? (0, import_ag_grid_community96._toStringOrNull)(value) : formattedValue) ?? translateForSetFilter(this, "blanks");
}
getModelAsString(model, source) {
const { values } = model ?? {};
const forToolPanel = source === "filterToolPanel";
if (values == null) {
return forToolPanel ? translateForSetFilter(this, "filterSummaryListInactive") : "";
}
const availableKeys = this.valueModel.getAvailableKeys(values);
const numValues = availableKeys.length;
const numToDisplay = forToolPanel ? 3 : 10;
const formattedValues = availableKeys.slice(0, numToDisplay).map((key) => this.getFormattedValue(key));
if (forToolPanel) {
const valueList = formattedValues.join(translateForSetFilter(this, "filterSummaryListSeparator"));
if (numValues > 3) {
return translateForSetFilter(this, "filterSummaryListLong", [valueList, String(numValues - 3)]);
} else {
return translateForSetFilter(this, "filterSummaryListShort", [valueList]);
}
}
return `(${numValues}) ${formattedValues.join(",")}${numValues > 10 ? ",..." : ""}`;
}
onAnyFilterChanged() {
window.setTimeout(() => {
if (!this.isAlive()) {
return;
}
this.valueModel.refreshAvailable().then((updated) => {
this.dispatchLocalEvent({ type: "anyFilterChanged", updated: !!updated });
});
});
}
onNewRowsLoaded() {
this.syncAfterDataChange();
}
setFilterValues(values) {
this.valueModel.overrideValues(values).then(() => {
this.refreshFilterValues();
});
}
resetFilterValues() {
this.valueModel.valuesType = setValueModel_default.TAKEN_FROM_GRID_VALUES;
this.syncAfterDataChange();
}
refreshFilterValues() {
if (!this.valueModel.isInitialised()) {
return;
}
this.valueModel.refreshAll().then(() => {
this.dispatchLocalEvent({ type: "dataChanged", hardRefresh: true });
this.validateModel(this.params, void 0, true);
});
}
getFilterKeys() {
return Array.from(this.valueModel.allValues.keys());
}
getFilterValues() {
return Array.from(this.valueModel.allValues.values());
}
isTreeDataOrGrouping() {
return this.treeDataTreeList || this.groupingTreeList;
}
caseFormat(valueToFormat) {
if (valueToFormat == null || typeof valueToFormat !== "string") {
return valueToFormat;
}
return this.caseSensitive ? valueToFormat : valueToFormat.toUpperCase();
}
addEventListenersForDataChanges() {
this.addManagedPropertyListeners(["groupAllowUnbalanced"], () => this.syncAfterDataChange());
const syncAfterDataChangeDebounced = (0, import_ag_grid_community96._debounce)(this, this.syncAfterDataChange.bind(this), 0);
this.addManagedEventListeners({
cellValueChanged: (event) => {
if (event.column === this.params.column) {
syncAfterDataChangeDebounced();
}
}
});
}
syncAfterDataChange() {
if (!this.isValuesTakenFromGrid()) {
return;
}
this.valueModel.refreshAll().then(() => {
this.dispatchLocalEvent({ type: "dataChanged" });
this.validateModel(this.params, { afterDataChange: true });
});
}
validateModel(params, additionalEventAttributes, restrictToAvailableValues) {
const valueModel = this.valueModel;
valueModel.allKeys.then(() => {
const model = params.model;
if (model == null) {
return;
}
const existingFormattedKeys = /* @__PURE__ */ new Map();
const addKey = (key) => existingFormattedKeys.set(this.caseFormat(key), key);
if (restrictToAvailableValues) {
for (const key of valueModel.availableKeys) {
addKey(key);
}
} else {
valueModel.allValues.forEach((_value, key) => addKey(key));
}
const newValues = [];
let updated = false;
for (const unformattedKey of model.values) {
const formattedKey = this.caseFormat((0, import_ag_grid_community96._makeNull)(unformattedKey));
const existingUnformattedKey = existingFormattedKeys.get(formattedKey);
if (existingUnformattedKey !== void 0) {
newValues.push(existingUnformattedKey);
if (existingUnformattedKey !== unformattedKey) {
updated = true;
}
} else {
updated = true;
}
}
const numNewValues = newValues.length;
if (numNewValues === 0 && params.filterParams.excelMode) {
params.onModelChange(null, additionalEventAttributes);
return;
}
const clearOnAllSelected = this.valueModel.valuesType === setValueModel_default.TAKEN_FROM_GRID_VALUES || !params.filterParams.suppressClearModelOnRefreshValues;
const allSelected = clearOnAllSelected && numNewValues === existingFormattedKeys.size;
if (updated || !model.filterType || allSelected) {
const newModel = allSelected ? null : { filterType: this.filterType, values: newValues };
params.onModelChange(newModel, additionalEventAttributes);
return;
}
});
}
isValuesTakenFromGrid() {
return this.valueModel.valuesType === setValueModel_default.TAKEN_FROM_GRID_VALUES;
}
doesFilterPassForTreeData(node) {
if (node.childrenAfterGroup?.length) {
return false;
}
const { gos, appliedModel } = this;
return appliedModel.has(
this.createKey(
processDataPath(
node.getRoute() ?? [node.key ?? node.id],
true,
gos.get("groupAllowUnbalanced")
)
)
);
}
doesFilterPassForGrouping(node) {
const {
appliedModel,
params,
gos,
beans: { rowGroupColsSvc, valueSvc }
} = this;
const dataPath = (rowGroupColsSvc?.columns ?? []).map((groupCol) => valueSvc.getKeyForNode(groupCol, node));
dataPath.push(params.getValue(node));
return appliedModel.has(
this.createKey(processDataPath(dataPath, false, gos.get("groupAllowUnbalanced")))
);
}
generateCreateKey(keyCreator, treeDataOrGrouping) {
if (treeDataOrGrouping && !keyCreator) {
(0, import_ag_grid_community96._error)(250);
return () => null;
}
if (keyCreator) {
return (value, node = null) => {
const params = this.getKeyCreatorParams(value, node);
return (0, import_ag_grid_community96._makeNull)(keyCreator(params));
};
}
return (value) => (0, import_ag_grid_community96._makeNull)((0, import_ag_grid_community96._toStringOrNull)(value));
}
getKeyCreatorParams(value, node = null) {
const { colDef, column } = this.params;
return (0, import_ag_grid_community96._addGridCommonParams)(this.gos, {
value,
colDef,
column,
node,
data: node?.data
});
}
setValueFormatter(providedValueFormatter, keyCreator, treeList, isRefData) {
let valueFormatter = providedValueFormatter;
if (!valueFormatter) {
if (keyCreator && !treeList) {
(0, import_ag_grid_community96._error)(249);
return;
}
this.noValueFormatterSupplied = true;
if (!isRefData) {
valueFormatter = (params) => (0, import_ag_grid_community96._toStringOrNull)(params.value);
}
}
this.valueFormatter = valueFormatter;
}
destroy() {
this.appliedModel.destroy();
super.destroy();
this.valueModel = void 0;
}
};
// packages/ag-grid-enterprise/src/setFilter/setFloatingFilter.ts
var import_ag_grid_community97 = require("ag-grid-community");
var SetFloatingFilterElement = {
tag: "div",
cls: "ag-floating-filter-input ag-set-floating-filter-input",
role: "presentation",
children: [
{
tag: "ag-input-text-field",
ref: "eFloatingFilterText"
}
]
};
var SetFloatingFilterComp = class extends import_ag_grid_community97.Component {
constructor() {
super(SetFloatingFilterElement, [import_ag_grid_community97.AgInputTextFieldSelector]);
this.eFloatingFilterText = import_ag_grid_community97.RefPlaceholder;
this.listenerAdded = false;
}
init(params) {
this.params = params;
this.eFloatingFilterText.setDisabled(true).addGuiEventListener("click", () => this.params.showParentFilter());
this.setParams(params);
}
setParams(params) {
const displayName = this.beans.colNames.getDisplayNameForColumn(params.column, "header", true);
const translate = this.getLocaleTextFunc();
this.eFloatingFilterText.setInputAriaLabel(`${displayName} ${translate("ariaFilterInput", "Filter Input")}`);
if (this.gos.get("enableFilterHandlers")) {
const reactiveParams = params;
this.updateFloatingFilterText(reactiveParams.model);
}
}
refresh(params) {
this.params = params;
this.setParams(params);
}
onParentModelChanged(parentModel) {
this.updateFloatingFilterText(parentModel);
}
parentSetFilterInstance(cb) {
this.params.parentFilterInstance((filter) => {
if (!(filter instanceof SetFilter)) {
(0, import_ag_grid_community97._error)(248);
return;
}
cb(filter);
});
}
addAvailableValuesListener() {
const addListener = (handler) => {
if (handler == null || !handler.isAlive()) {
return;
}
const valueModel = handler.valueModel;
this.destroyListeners = valueModel.addManagedListeners(valueModel, {
availableValuesChanged: () => this.updateFloatingFilterText(handler.params.model),
destroyed: () => {
this.listenerAdded = false;
this.destroyListeners = void 0;
}
});
};
if (this.gos.get("enableFilterHandlers")) {
addListener(this.params.getHandler());
} else {
this.parentSetFilterInstance((setFilter) => {
addListener(setFilter.handler);
});
}
this.listenerAdded = true;
}
updateFloatingFilterText(parentModel) {
if (!this.listenerAdded) {
this.addAvailableValuesListener();
}
if (parentModel == null) {
this.eFloatingFilterText.setValue("");
} else {
if (this.gos.get("enableFilterHandlers")) {
this.eFloatingFilterText.setValue(
this.params.getHandler().getModelAsString?.(parentModel) ?? ""
);
} else {
this.parentSetFilterInstance((setFilter) => {
this.eFloatingFilterText.setValue(setFilter.getModelAsString(parentModel));
});
}
}
}
destroy() {
const destroyListeners = this.destroyListeners;
if (destroyListeners) {
destroyListeners.forEach((destroyFunc) => destroyFunc());
destroyListeners.length = 0;
}
super.destroy();
}
};
// packages/ag-grid-enterprise/src/setFilter/setFilterModule.ts
var SetFilterModule = {
moduleName: "SetFilter",
version: VERSION,
userComponents: {
agSetColumnFilter: {
classImp: SetFilter,
params: {
useForm: true
},
processParams: (params) => {
applyExcelModeOptions(params);
return params;
}
},
agSetColumnFloatingFilter: SetFloatingFilterComp
},
dynamicBeans: {
agSetColumnFilterHandler: SetFilterHandler
},
icons: {
// set filter tree list group contracted (click to expand)
setFilterGroupClosed: "tree-closed",
// set filter tree list group expanded (click to contract)
setFilterGroupOpen: "tree-open",
// set filter tree list expand/collapse all button, shown when some children are expanded and
// others are collapsed
setFilterGroupIndeterminate: "tree-indeterminate",
// set filter async values loading
setFilterLoading: "loading"
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community98._ColumnFilterModule]
};
// packages/ag-grid-enterprise/src/statusBar/statusBarModule.ts
var import_ag_grid_community108 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/statusBar/agStatusBar.ts
var import_ag_grid_community99 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/statusBar/agStatusBar.css-GENERATED.ts
var agStatusBarCSS = (
/*css*/
`.ag-status-bar{border-top:var(--ag-footer-row-border);display:flex;justify-content:space-between;line-height:1.5;overflow:hidden;padding-left:calc(var(--ag-spacing)*4);padding-right:calc(var(--ag-spacing)*4)}.ag-status-panel,:where(.ag-status-panel.ag-status-panel-aggregations .ag-status-name-value){display:inline-flex}.ag-status-name-value{color:var(--ag-status-bar-label-color);font-weight:var(--ag-status-bar-label-font-weight);margin-left:var(--ag-spacing);margin-right:var(--ag-spacing);padding-bottom:var(--ag-widget-container-vertical-padding);padding-top:var(--ag-widget-container-vertical-padding);white-space:nowrap}.ag-status-name-value-value{color:var(--ag-status-bar-value-color);font-weight:var(--ag-status-bar-value-font-weight)}.ag-status-bar-left{display:inline-flex}.ag-status-bar-center{display:inline-flex;text-align:center}.ag-status-bar-right{display:inline-flex}`
);
// packages/ag-grid-enterprise/src/statusBar/agStatusBar.ts
function getStatusPanelCompDetails(userCompFactory, def, params) {
return userCompFactory.getCompDetails(def, StatusPanelComponent, void 0, params, true);
}
var StatusPanelComponent = {
name: "statusPanel",
optionalMethods: ["refresh"]
};
var AgStatusBarElement = {
tag: "div",
cls: "ag-status-bar",
children: [
{
tag: "div",
ref: "eStatusBarLeft",
cls: "ag-status-bar-left",
role: "status"
},
{
tag: "div",
ref: "eStatusBarCenter",
cls: "ag-status-bar-center",
role: "status"
},
{
tag: "div",
ref: "eStatusBarRight",
cls: "ag-status-bar-right",
role: "status"
}
]
};
var AgStatusBar = class extends import_ag_grid_community99.Component {
constructor() {
super(AgStatusBarElement);
this.updateQueued = false;
this.panelsPromise = import_ag_grid_community99.AgPromise.resolve();
this.eStatusBarLeft = import_ag_grid_community99.RefPlaceholder;
this.eStatusBarCenter = import_ag_grid_community99.RefPlaceholder;
this.eStatusBarRight = import_ag_grid_community99.RefPlaceholder;
this.compDestroyFunctions = {};
this.registerCSS(agStatusBarCSS);
}
wireBeans(beans) {
this.userCompFactory = beans.userCompFactory;
this.statusBarSvc = beans.statusBarSvc;
}
postConstruct() {
this.processStatusPanels(/* @__PURE__ */ new Map());
this.addManagedPropertyListeners(["statusBar"], this.handleStatusBarChanged.bind(this));
}
processStatusPanels(existingStatusPanelsToReuse) {
const statusPanels = this.gos.get("statusBar")?.statusPanels;
if (statusPanels) {
const leftStatusPanelComponents = statusPanels.filter(
(componentConfig) => componentConfig.align === "left"
);
const centerStatusPanelComponents = statusPanels.filter(
(componentConfig) => componentConfig.align === "center"
);
const rightStatusPanelComponents = statusPanels.filter(
(componentConfig) => !componentConfig.align || componentConfig.align === "right"
);
this.panelsPromise = import_ag_grid_community99.AgPromise.all([
this.createAndRenderComponents(
leftStatusPanelComponents,
this.eStatusBarLeft,
existingStatusPanelsToReuse
),
this.createAndRenderComponents(
centerStatusPanelComponents,
this.eStatusBarCenter,
existingStatusPanelsToReuse
),
this.createAndRenderComponents(
rightStatusPanelComponents,
this.eStatusBarRight,
existingStatusPanelsToReuse
)
]);
} else {
this.setDisplayed(false);
}
}
handleStatusBarChanged() {
if (this.updateQueued) {
return;
}
this.updateQueued = true;
this.panelsPromise.then(() => {
this.updateStatusBar();
this.updateQueued = false;
});
}
updateStatusBar() {
const statusPanels = this.gos.get("statusBar")?.statusPanels;
const validStatusBarPanelsProvided = Array.isArray(statusPanels) && statusPanels.length > 0;
this.setDisplayed(validStatusBarPanelsProvided);
const existingStatusPanelsToReuse = /* @__PURE__ */ new Map();
if (validStatusBarPanelsProvided) {
statusPanels.forEach((statusPanelConfig) => {
const key = statusPanelConfig.key ?? statusPanelConfig.statusPanel;
const existingStatusPanel = this.statusBarSvc.getStatusPanel(key);
if (existingStatusPanel?.refresh) {
const newParams = (0, import_ag_grid_community99._addGridCommonParams)(this.gos, {
...statusPanelConfig.statusPanelParams ?? {},
key
});
const hasRefreshed = existingStatusPanel.refresh(newParams);
if (hasRefreshed) {
existingStatusPanelsToReuse.set(key, existingStatusPanel);
delete this.compDestroyFunctions[key];
(0, import_ag_grid_community99._removeFromParent)(existingStatusPanel.getGui());
}
}
});
}
this.resetStatusBar();
if (validStatusBarPanelsProvided) {
this.processStatusPanels(existingStatusPanelsToReuse);
}
}
resetStatusBar() {
(0, import_ag_grid_community99._clearElement)(this.eStatusBarLeft);
(0, import_ag_grid_community99._clearElement)(this.eStatusBarCenter);
(0, import_ag_grid_community99._clearElement)(this.eStatusBarRight);
this.destroyComponents();
this.statusBarSvc.unregisterAllComponents();
}
destroy() {
this.destroyComponents();
super.destroy();
}
destroyComponents() {
Object.values(this.compDestroyFunctions).forEach((func) => func());
this.compDestroyFunctions = {};
}
createAndRenderComponents(statusBarComponents, ePanelComponent, existingStatusPanelsToReuse) {
const componentDetails = [];
statusBarComponents.forEach((componentConfig) => {
const key = componentConfig.key || componentConfig.statusPanel;
const existingStatusPanel = existingStatusPanelsToReuse.get(key);
let promise;
if (existingStatusPanel) {
promise = import_ag_grid_community99.AgPromise.resolve(existingStatusPanel);
} else {
const compDetails = getStatusPanelCompDetails(
this.userCompFactory,
componentConfig,
(0, import_ag_grid_community99._addGridCommonParams)(this.gos, { key })
);
if (compDetails == null) {
return;
}
promise = compDetails.newAgStackInstance();
}
componentDetails.push({
key,
promise
});
});
return import_ag_grid_community99.AgPromise.all(componentDetails.map((details) => details.promise)).then(() => {
componentDetails.forEach((componentDetail) => {
componentDetail.promise.then((component) => {
const destroyFunc = () => {
this.destroyBean(component);
};
if (this.isAlive()) {
this.statusBarSvc.registerStatusPanel(componentDetail.key, component);
ePanelComponent.appendChild(component.getGui());
this.compDestroyFunctions[componentDetail.key] = destroyFunc;
} else {
destroyFunc();
}
});
});
});
}
};
var AgStatusBarSelector = {
selector: "AG-STATUS-BAR",
component: AgStatusBar
};
// packages/ag-grid-enterprise/src/statusBar/providedPanels/aggregationComp.ts
var import_ag_grid_community101 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/statusBar/providedPanels/agNameValue.ts
var import_ag_grid_community100 = require("ag-grid-community");
var AgNameValueElement = {
tag: "div",
cls: "ag-status-name-value",
children: [
{ tag: "span", ref: "eLabel" },
":\xA0",
{ tag: "span", ref: "eValue", cls: "ag-status-name-value-value" }
]
};
var AgNameValue = class extends import_ag_grid_community100.Component {
constructor() {
super(AgNameValueElement);
this.eLabel = import_ag_grid_community100.RefPlaceholder;
this.eValue = import_ag_grid_community100.RefPlaceholder;
}
setLabel(key, defaultValue) {
this.setDisplayed(false);
this.eLabel.textContent = this.getLocaleTextFunc()(key, defaultValue);
}
setValue(value, totalRows) {
this.eValue.textContent = this.valueFormatter(
(0, import_ag_grid_community100._addGridCommonParams)(this.gos, { value, totalRows, key: this.key })
);
}
};
var AgNameValueSelector = {
selector: "AG-NAME-VALUE",
component: AgNameValue
};
// packages/ag-grid-enterprise/src/statusBar/providedPanels/utils.ts
var _getFilteredRowCount = (rowModel) => {
let filteredRowCount = 0;
rowModel.forEachNodeAfterFilter((node) => {
if (node.data) {
filteredRowCount++;
}
});
return filteredRowCount;
};
var _getTotalRowCount = (rowModel) => {
let totalRowCount = 0;
rowModel.forEachNode((node) => {
if (node.data) {
totalRowCount++;
}
});
return totalRowCount;
};
// packages/ag-grid-enterprise/src/statusBar/providedPanels/aggregationComp.ts
function _formatNumberTwoDecimalPlacesAndCommas(value, getLocaleTextFunc) {
if (typeof value !== "number") {
return "";
}
return (0, import_ag_grid_community101._formatNumberCommas)(Math.round(value * 100) / 100, getLocaleTextFunc);
}
var AggregationCompElement = {
tag: "div",
cls: "ag-status-panel ag-status-panel-aggregations",
children: [
{
tag: "ag-name-value",
ref: "avgAggregationComp"
},
{
tag: "ag-name-value",
ref: "countAggregationComp"
},
{
tag: "ag-name-value",
ref: "minAggregationComp"
},
{
tag: "ag-name-value",
ref: "maxAggregationComp"
},
{
tag: "ag-name-value",
ref: "sumAggregationComp"
}
]
};
var AggregationComp = class extends import_ag_grid_community101.Component {
constructor() {
super(AggregationCompElement, [AgNameValueSelector]);
this.sumAggregationComp = import_ag_grid_community101.RefPlaceholder;
this.countAggregationComp = import_ag_grid_community101.RefPlaceholder;
this.minAggregationComp = import_ag_grid_community101.RefPlaceholder;
this.maxAggregationComp = import_ag_grid_community101.RefPlaceholder;
this.avgAggregationComp = import_ag_grid_community101.RefPlaceholder;
}
postConstruct() {
if (!(0, import_ag_grid_community101._isClientSideRowModel)(this.gos) && !(0, import_ag_grid_community101._isServerSideRowModel)(this.gos)) {
(0, import_ag_grid_community101._warn)(221);
return;
}
this.avgAggregationComp.setLabel("avg", "Average");
this.countAggregationComp.setLabel("count", "Count");
this.minAggregationComp.setLabel("min", "Min");
this.maxAggregationComp.setLabel("max", "Max");
this.sumAggregationComp.setLabel("sum", "Sum");
this.addManagedEventListeners({
cellSelectionChanged: this.onCellSelectionChanged.bind(this),
modelUpdated: this.onCellSelectionChanged.bind(this)
});
}
init(params) {
this.refresh(params);
}
refresh(params) {
this.params = params;
const valueFormatter = params.valueFormatter ?? (({ value }) => _formatNumberTwoDecimalPlacesAndCommas(value, this.getLocaleTextFunc.bind(this)));
const aggFuncNames = ["avg", "count", "min", "max", "sum"];
for (const key of aggFuncNames) {
const comp = this.getAllowedAggregationValueComponent(key);
if (comp) {
comp.key = key;
comp.valueFormatter = valueFormatter.bind(this);
}
}
this.onCellSelectionChanged();
return true;
}
setAggregationComponentValue(aggFuncName, value, visible) {
const statusBarValueComponent = this.getAllowedAggregationValueComponent(aggFuncName);
const totalRow = _getTotalRowCount(this.beans.rowModel);
if ((0, import_ag_grid_community101._exists)(statusBarValueComponent) && statusBarValueComponent) {
statusBarValueComponent.setValue(value, totalRow);
statusBarValueComponent.setDisplayed(visible);
} else {
this.getAggregationValueComponent(aggFuncName)?.setDisplayed(false);
}
}
getAllowedAggregationValueComponent(aggFuncName) {
const { aggFuncs } = this.params;
if (!aggFuncs || aggFuncs.includes(aggFuncName)) {
return this.getAggregationValueComponent(aggFuncName);
}
return null;
}
getAggregationValueComponent(aggFuncName) {
const refComponentName = `${aggFuncName}AggregationComp`;
return this[refComponentName];
}
onCellSelectionChanged() {
const beans = this.beans;
const { rangeSvc, valueSvc } = beans;
const cellRanges = rangeSvc?.getCellRanges();
let sum = 0;
let count = 0;
let numberCount = 0;
let min = null;
let max = null;
const cellsSoFar = {};
if (cellRanges?.length && rangeSvc) {
for (let i = 0; i < cellRanges.length; i++) {
const cellRange = cellRanges[i];
let currentRow = rangeSvc.getRangeStartRow(cellRange);
const lastRow = rangeSvc.getRangeEndRow(cellRange);
while (true) {
const finishedAllRows = (0, import_ag_grid_community101._missing)(currentRow) || !currentRow || (0, import_ag_grid_community101._isRowBefore)(lastRow, currentRow);
if (finishedAllRows || !currentRow || !cellRange.columns) {
break;
}
cellRange.columns.forEach((col) => {
if (currentRow === null) {
return;
}
const cellId = (0, import_ag_grid_community101._createCellId)({
rowPinned: currentRow.rowPinned,
column: col,
rowIndex: currentRow.rowIndex
});
if (cellsSoFar[cellId]) {
return;
}
cellsSoFar[cellId] = true;
const rowNode = (0, import_ag_grid_community101._getRowNode)(beans, currentRow);
if ((0, import_ag_grid_community101._missing)(rowNode)) {
return;
}
let value = valueSvc.getValue(col, rowNode);
if ((0, import_ag_grid_community101._missing)(value) || value === "") {
return;
}
count++;
if (typeof value === "object" && "value" in value) {
value = value.value;
if (value === "") {
return;
}
}
if (typeof value === "string") {
value = Number(value);
}
if (typeof value === "number" && !isNaN(value)) {
sum += value;
if (max === null || value > max) {
max = value;
}
if (min === null || value < min) {
min = value;
}
numberCount++;
}
});
currentRow = (0, import_ag_grid_community101._getRowBelow)(beans, currentRow);
}
}
}
const gotResult = count > 1;
const gotNumberResult = numberCount > 1;
this.setAggregationComponentValue("count", count, gotResult);
this.setAggregationComponentValue("sum", sum, gotNumberResult);
this.setAggregationComponentValue("min", min, gotNumberResult);
this.setAggregationComponentValue("max", max, gotNumberResult);
this.setAggregationComponentValue("avg", sum / numberCount, gotNumberResult);
}
};
// packages/ag-grid-enterprise/src/statusBar/providedPanels/filteredRowsComp.ts
var import_ag_grid_community102 = require("ag-grid-community");
var FilteredRowsComp = class extends AgNameValue {
postConstruct() {
this.setLabel("filteredRows", "Filtered");
if (!(0, import_ag_grid_community102._isClientSideRowModel)(this.gos)) {
(0, import_ag_grid_community102._warn)(222);
return;
}
this.addCss("ag-status-panel");
this.addCss("ag-status-panel-filtered-row-count");
this.setDisplayed(true);
const listener = this.onDataChanged.bind(this);
this.addManagedEventListeners({ modelUpdated: listener });
}
onDataChanged() {
const { rowModel } = this.beans;
const totalRowCountValue = _getTotalRowCount(rowModel);
const filteredRowCountValue = _getFilteredRowCount(rowModel);
this.setValue(filteredRowCountValue, totalRowCountValue);
this.setDisplayed(totalRowCountValue !== filteredRowCountValue);
}
init(params) {
this.refresh(params);
this.onDataChanged();
}
updateValueFormatter(valueFormatter) {
this.valueFormatter = valueFormatter ?? (({ value }) => (0, import_ag_grid_community102._formatNumberCommas)(value, this.getLocaleTextFunc.bind(this)));
}
refresh(params) {
const { key, valueFormatter } = params;
this.key = key;
this.updateValueFormatter(valueFormatter);
return true;
}
};
// packages/ag-grid-enterprise/src/statusBar/providedPanels/selectedRowsComp.ts
var import_ag_grid_community103 = require("ag-grid-community");
var SelectedRowsComp = class extends AgNameValue {
postConstruct() {
const gos = this.gos;
if (!(0, import_ag_grid_community103._isClientSideRowModel)(gos) && !(0, import_ag_grid_community103._isServerSideRowModel)(gos)) {
(0, import_ag_grid_community103._warn)(223);
return;
}
this.setLabel("selectedRows", "Selected");
this.addCss("ag-status-panel");
this.addCss("ag-status-panel-selected-row-count");
const eventListener = this.onRowSelectionChanged.bind(this);
this.addManagedEventListeners({ modelUpdated: eventListener, selectionChanged: eventListener });
}
onRowSelectionChanged() {
const { selectionSvc, rowModel } = this.beans;
const selectedRowCount = selectionSvc?.getSelectionCount() ?? 0;
const totalRowCount = _getTotalRowCount(rowModel);
this.setValue(selectedRowCount, totalRowCount);
if (selectedRowCount < 0) {
this.setDisplayed(true);
return;
}
this.setDisplayed(selectedRowCount > 0);
}
init(params) {
this.refresh(params);
this.onRowSelectionChanged();
}
updateValueFormatter(valueFormatter) {
this.valueFormatter = valueFormatter ?? (({ value }) => {
if (value == null || value >= 0) {
return (0, import_ag_grid_community103._formatNumberCommas)(value, this.getLocaleTextFunc.bind(this));
}
return this.getLocaleTextFunc()("statusBarLastRowUnknown", "?");
});
}
refresh(params) {
const { key, valueFormatter } = params;
this.key = key;
this.updateValueFormatter(valueFormatter);
return true;
}
};
// packages/ag-grid-enterprise/src/statusBar/providedPanels/totalAndFilteredRowsComp.ts
var import_ag_grid_community104 = require("ag-grid-community");
var TotalAndFilteredRowsComp = class extends AgNameValue {
postConstruct() {
if (!(0, import_ag_grid_community104._isClientSideRowModel)(this.gos)) {
(0, import_ag_grid_community104._warn)(224);
return;
}
this.setLabel("totalAndFilteredRows", "Rows");
this.addCss("ag-status-panel");
this.addCss("ag-status-panel-total-and-filtered-row-count");
this.setDisplayed(true);
this.addManagedEventListeners({ modelUpdated: this.onDataChanged.bind(this) });
}
onDataChanged() {
const { rowModel } = this.beans;
const rowCount = _getFilteredRowCount(rowModel);
const totalRowCount = _getTotalRowCount(rowModel);
this.setValue(rowCount, totalRowCount);
}
init(params) {
this.refresh(params);
this.onDataChanged();
}
updateValueFormatter(valueFormatter) {
this.valueFormatter = valueFormatter ?? (({ value, totalRows }) => {
const getLocaleTextFunc = this.getLocaleTextFunc.bind(this);
const rowCount = (0, import_ag_grid_community104._formatNumberCommas)(value, getLocaleTextFunc);
const totalRowCount = (0, import_ag_grid_community104._formatNumberCommas)(totalRows ?? value, getLocaleTextFunc);
if (value === totalRows) {
return rowCount;
}
const localeTextFunc = getLocaleTextFunc();
return `${rowCount} ${localeTextFunc("of", "of")} ${totalRowCount}`;
});
}
refresh(params) {
const { key, valueFormatter } = params;
this.key = key;
this.updateValueFormatter(valueFormatter);
return true;
}
};
// packages/ag-grid-enterprise/src/statusBar/providedPanels/totalRowsComp.ts
var import_ag_grid_community105 = require("ag-grid-community");
var TotalRowsComp = class extends AgNameValue {
postConstruct() {
this.setLabel("totalRows", "Total Rows");
if (!(0, import_ag_grid_community105._isClientSideRowModel)(this.gos)) {
(0, import_ag_grid_community105._warn)(225);
return;
}
this.addCss("ag-status-panel");
this.addCss("ag-status-panel-total-row-count");
this.setDisplayed(true);
this.addManagedEventListeners({ modelUpdated: this.onDataChanged.bind(this) });
}
onDataChanged() {
const totalRow = _getTotalRowCount(this.beans.rowModel);
this.setValue(totalRow, totalRow);
}
init(params) {
this.refresh(params);
this.onDataChanged();
}
updateValueFormatter(valueFormatter) {
this.valueFormatter = valueFormatter ?? (({ value }) => (0, import_ag_grid_community105._formatNumberCommas)(value, this.getLocaleTextFunc.bind(this)));
}
refresh(params) {
const { key, valueFormatter } = params;
this.key = key;
this.updateValueFormatter(valueFormatter);
return true;
}
};
// packages/ag-grid-enterprise/src/statusBar/statusBarApi.ts
var import_ag_grid_community106 = require("ag-grid-community");
function getStatusPanel(beans, key) {
const comp = beans.statusBarSvc?.getStatusPanel(key);
return (0, import_ag_grid_community106._unwrapUserComp)(comp);
}
// packages/ag-grid-enterprise/src/statusBar/statusBarService.ts
var import_ag_grid_community107 = require("ag-grid-community");
var StatusBarService = class extends import_ag_grid_community107.BeanStub {
// tslint:disable-next-line
constructor() {
super();
this.beanName = "statusBarSvc";
this.comps = /* @__PURE__ */ new Map();
}
registerStatusPanel(key, component) {
this.comps.set(key, component);
}
unregisterStatusPanel(key) {
this.comps.delete(key);
}
unregisterAllComponents() {
this.comps.clear();
}
getStatusPanel(key) {
return this.comps.get(key);
}
destroy() {
this.unregisterAllComponents();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/statusBar/statusBarModule.ts
var StatusBarModule = {
moduleName: "StatusBar",
version: VERSION,
beans: [StatusBarService],
userComponents: {
agAggregationComponent: AggregationComp,
agTotalRowCountComponent: TotalRowsComp,
agFilteredRowCountComponent: FilteredRowsComp,
agTotalAndFilteredRowCountComponent: TotalAndFilteredRowsComp,
agSelectedRowCountComponent: SelectedRowsComp
},
selectors: [AgStatusBarSelector],
apiFunctions: {
getStatusPanel
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community108._KeyboardNavigationModule]
};
// packages/ag-grid-enterprise/src/excelExport/excelExportModule.ts
var import_ag_grid_community110 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/excelExport/excelExportApi.ts
var import_ag_grid_community109 = require("ag-grid-community");
function assertNotExcelMultiSheet(beans) {
if (beans.excelCreator?.getFactoryMode() === "MULTI_SHEET") {
(0, import_ag_grid_community109._warn)(161);
return false;
}
return true;
}
function getDataAsExcel(beans, params) {
if (assertNotExcelMultiSheet(beans)) {
return beans.excelCreator?.getDataAsExcel(params);
}
return void 0;
}
function exportDataAsExcel(beans, params) {
if (assertNotExcelMultiSheet(beans)) {
beans.excelCreator?.exportDataAsExcel(params);
}
}
function getSheetDataForExcel(beans, params) {
beans.excelCreator?.setFactoryMode("MULTI_SHEET");
return beans.excelCreator?.getSheetDataForExcel(params);
}
function getMultipleSheetsAsExcel2(beans, params) {
return beans.excelCreator?.getMultipleSheetsAsExcel(params);
}
function exportMultipleSheetsAsExcel2(beans, params) {
beans.excelCreator?.exportMultipleSheetsAsExcel(params);
}
// packages/ag-grid-enterprise/src/excelExport/excelExportModule.ts
var ExcelExportModule = {
moduleName: "ExcelExport",
version: VERSION,
beans: [ExcelCreator],
apiFunctions: {
getDataAsExcel,
exportDataAsExcel,
getSheetDataForExcel,
getMultipleSheetsAsExcel: getMultipleSheetsAsExcel2,
exportMultipleSheetsAsExcel: exportMultipleSheetsAsExcel2
},
dependsOn: [import_ag_grid_community110._SharedExportModule, EnterpriseCoreModule]
};
// packages/ag-grid-enterprise/src/multiFilter/multiFilterModule.ts
var import_ag_grid_community119 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/multiFilter/multiFilter.ts
var import_ag_grid_community114 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/multiFilter/baseMultiFilter.ts
var import_ag_grid_community113 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/widgets/agGroupComponent.ts
var import_ag_grid_community111 = require("ag-grid-community");
function getAgGroupComponentTemplate(params) {
const cssIdentifier = params.cssIdentifier || "default";
const direction = params.direction || "vertical";
return {
tag: "div",
cls: `ag-group ag-${cssIdentifier}-group`,
role: "presentation",
children: [
{
tag: "div",
ref: "eToolbar",
cls: `ag-group-toolbar ag-${cssIdentifier}-group-toolbar`,
children: [{ tag: "ag-checkbox", ref: "cbGroupEnabled" }]
},
{
tag: "div",
ref: "eContainer",
cls: `ag-group-container ag-group-container-${direction} ag-${cssIdentifier}-group-container`
}
]
};
}
var AgGroupComponent = class extends import_ag_grid_community111.Component {
constructor(params = {}) {
super(getAgGroupComponentTemplate(params), [import_ag_grid_community111.AgCheckboxSelector]);
this.params = params;
this.suppressEnabledCheckbox = true;
this.suppressToggleExpandOnEnableChange = false;
this.eToolbar = import_ag_grid_community111.RefPlaceholder;
this.cbGroupEnabled = import_ag_grid_community111.RefPlaceholder;
this.eContainer = import_ag_grid_community111.RefPlaceholder;
const {
enabled,
items,
suppressEnabledCheckbox,
expanded,
suppressToggleExpandOnEnableChange,
useToggle: toggleMode
} = params;
this.cssIdentifier = params.cssIdentifier || "default";
this.enabled = enabled != null ? enabled : true;
this.items = items || [];
this.useToggle = toggleMode ?? false;
this.alignItems = params.alignItems || "center";
this.expanded = expanded == null ? true : expanded;
if (suppressEnabledCheckbox != null) {
this.suppressEnabledCheckbox = suppressEnabledCheckbox;
}
if (suppressToggleExpandOnEnableChange != null) {
this.suppressToggleExpandOnEnableChange = suppressToggleExpandOnEnableChange;
}
}
postConstruct() {
this.setupTitleBar();
if (this.items.length) {
const initialItems = this.items;
this.items = [];
this.addItems(initialItems);
}
const localeTextFunc = this.getLocaleTextFunc();
this.cbGroupEnabled.setLabel(localeTextFunc("enabled", "Enabled"));
if (this.enabled) {
this.setEnabled(this.enabled, void 0, true);
}
this.setAlignItems(this.alignItems);
const { onEnableChange, onExpandedChange, suppressOpenCloseIcons } = this.params;
this.hideEnabledCheckbox(this.suppressEnabledCheckbox);
this.hideOpenCloseIcons(suppressOpenCloseIcons ?? false);
this.refreshChildDisplay();
(0, import_ag_grid_community111._setDisplayed)(this.eContainer, this.expanded);
this.cbGroupEnabled.onValueChange((newSelection) => {
this.setEnabled(newSelection, true, this.suppressToggleExpandOnEnableChange);
this.dispatchEnableChangeEvent(newSelection);
});
if (onEnableChange != null) {
this.onEnableChange(onEnableChange);
}
if (onExpandedChange != null) {
this.onExpandedChange(onExpandedChange);
}
}
refreshChildDisplay() {
(0, import_ag_grid_community111._setDisplayed)(this.eToolbar, this.expanded && !this.suppressEnabledCheckbox);
this.eTitleBar?.refreshOnExpand(this.expanded);
}
isExpanded() {
return this.expanded;
}
setAlignItems(alignment) {
if (this.alignItems !== alignment) {
this.removeCss(`ag-group-item-alignment-${this.alignItems}`);
}
this.alignItems = alignment;
const newCls = `ag-group-item-alignment-${this.alignItems}`;
this.addCss(newCls);
return this;
}
toggleGroupExpand(expanded, silent) {
if (this.eTitleBar?.isSuppressCollapse() && !this.useToggle) {
expanded = true;
silent = true;
} else {
expanded = expanded != null ? expanded : !this.expanded;
if (this.expanded === expanded) {
return this;
}
}
this.expanded = expanded;
this.refreshChildDisplay();
(0, import_ag_grid_community111._setDisplayed)(this.eContainer, expanded);
if (!silent) {
this.dispatchLocalEvent({
type: expanded ? "expanded" : "collapsed"
});
}
return this;
}
addItems(items) {
items.forEach((item) => this.addItem(item));
}
prependItem(item) {
this.insertItem(item, true);
}
addItem(item) {
this.insertItem(item, false);
}
insertItem(item, prepend) {
const container = this.eContainer;
const el = item instanceof import_ag_grid_community111.Component ? item.getGui() : item;
el.classList.add("ag-group-item", `ag-${this.cssIdentifier}-group-item`);
if (prepend) {
container.insertAdjacentElement("afterbegin", el);
this.items.unshift(el);
} else {
container.appendChild(el);
this.items.push(el);
}
}
hideItem(hide, index) {
const itemToHide = this.items[index];
(0, import_ag_grid_community111._setDisplayed)(itemToHide, !hide);
}
getItemIndex(item) {
const el = item instanceof import_ag_grid_community111.Component ? item.getGui() : item;
return this.items.indexOf(el);
}
setTitle(title) {
this.eTitleBar?.setTitle(title);
return this;
}
addTitleBarWidget(el) {
this.eTitleBar?.addWidget(el);
return this;
}
addCssClassToTitleBar(cssClass) {
this.eTitleBar?.addCss(cssClass);
}
dispatchEnableChangeEvent(enabled) {
const event = {
type: "enableChange",
enabled
};
this.dispatchLocalEvent(event);
}
setEnabled(enabled, skipToggle, skipExpand) {
this.enabled = enabled;
this.refreshDisabledStyles();
if (!skipExpand) {
this.toggleGroupExpand(enabled);
}
if (!skipToggle) {
this.cbGroupEnabled.setValue(enabled);
this.eToggle?.setValue(enabled);
}
return this;
}
isEnabled() {
return this.enabled;
}
onEnableChange(callbackFn) {
this.addManagedListeners(this, { enableChange: (event) => callbackFn(event.enabled) });
return this;
}
onExpandedChange(callbackFn) {
this.addManagedListeners(this, {
expanded: () => callbackFn(true),
collapsed: () => callbackFn(false)
});
return this;
}
hideEnabledCheckbox(hide) {
this.suppressEnabledCheckbox = hide;
this.refreshChildDisplay();
this.refreshDisabledStyles();
return this;
}
hideOpenCloseIcons(hide) {
this.eTitleBar?.hideOpenCloseIcons(hide);
return this;
}
refreshDisabledStyles() {
const disabled = !this.enabled;
this.eContainer.classList.toggle("ag-disabled", disabled);
this.eTitleBar?.refreshDisabledStyles(this.suppressEnabledCheckbox && disabled);
this.eContainer.classList.toggle("ag-disabled-group-container", disabled);
}
setupTitleBar() {
const titleBar = this.useToggle ? this.createToggleTitleBar() : this.createDefaultTitleBar();
this.eToolbar.insertAdjacentElement("beforebegin", titleBar.getGui());
}
createDefaultTitleBar() {
const titleBar = this.createManagedBean(new DefaultTitleBar(this.params));
this.eTitleBar = titleBar;
titleBar.refreshOnExpand(this.expanded);
this.addManagedListeners(titleBar, {
expandedChanged: (event) => this.toggleGroupExpand(event.expanded)
});
return titleBar;
}
createToggleTitleBar() {
const eToggle = this.createManagedBean(
new import_ag_grid_community111.AgToggleButton({
value: this.enabled,
label: this.params.title,
labelAlignment: "left",
labelWidth: "flex",
onValueChange: (enabled) => {
this.setEnabled(enabled, true);
this.dispatchEnableChangeEvent(enabled);
}
})
);
eToggle.addCss("ag-group-title-bar");
eToggle.addCss(`ag-${this.params.cssIdentifier ?? "default"}-group-title-bar ag-unselectable`);
this.eToggle = eToggle;
this.toggleGroupExpand(this.enabled);
return eToggle;
}
};
var TITLE_BAR_DISABLED_CLASS = "ag-disabled-group-title-bar";
function getDefaultTitleBarTemplate(params) {
const cssIdentifier = params.cssIdentifier ?? "default";
return {
tag: "div",
cls: `ag-group-title-bar ag-${cssIdentifier}-group-title-bar ag-unselectable`,
role: params.suppressKeyboardNavigation ? "presentation" : "role",
children: [
{
tag: "span",
ref: "eGroupOpenedIcon",
cls: `ag-group-title-bar-icon ag-${cssIdentifier}-group-title-bar-icon`,
role: "presentation"
},
{
tag: "span",
ref: "eGroupClosedIcon",
cls: `ag-group-title-bar-icon ag-${cssIdentifier}-group-title-bar-icon`,
role: "presentation"
},
{ tag: "span", ref: "eTitle", cls: `ag-group-title ag-${cssIdentifier}-group-title` }
]
};
}
var DefaultTitleBar = class extends import_ag_grid_community111.Component {
constructor(params = {}) {
super(getDefaultTitleBarTemplate(params));
this.suppressOpenCloseIcons = false;
this.suppressKeyboardNavigation = false;
this.eGroupOpenedIcon = import_ag_grid_community111.RefPlaceholder;
this.eGroupClosedIcon = import_ag_grid_community111.RefPlaceholder;
this.eTitle = import_ag_grid_community111.RefPlaceholder;
const { title, suppressOpenCloseIcons, suppressKeyboardNavigation } = params;
if (!!title && title.length > 0) {
this.title = title;
}
if (suppressOpenCloseIcons != null) {
this.suppressOpenCloseIcons = suppressOpenCloseIcons;
}
this.suppressKeyboardNavigation = suppressKeyboardNavigation ?? false;
}
postConstruct() {
this.setTitle(this.title);
this.hideOpenCloseIcons(this.suppressOpenCloseIcons);
this.setupExpandContract();
}
setupExpandContract() {
this.eGroupClosedIcon.appendChild((0, import_ag_grid_community111._createIcon)("accordionClosed", this.beans, null));
this.eGroupOpenedIcon.appendChild((0, import_ag_grid_community111._createIcon)("accordionOpen", this.beans, null));
this.addManagedElementListeners(this.getGui(), {
click: () => this.dispatchExpandChanged(),
keydown: (e) => {
switch (e.key) {
case import_ag_grid_community111.KeyCode.ENTER:
case import_ag_grid_community111.KeyCode.SPACE:
e.preventDefault();
this.dispatchExpandChanged();
break;
case import_ag_grid_community111.KeyCode.RIGHT:
case import_ag_grid_community111.KeyCode.LEFT:
e.preventDefault();
this.dispatchExpandChanged(e.key === import_ag_grid_community111.KeyCode.RIGHT);
break;
}
}
});
}
refreshOnExpand(expanded) {
this.refreshAriaStatus(expanded);
this.refreshOpenCloseIcons(expanded);
}
refreshAriaStatus(expanded) {
if (!this.suppressOpenCloseIcons) {
(0, import_ag_grid_community111._setAriaExpanded)(this.getGui(), expanded);
}
}
refreshOpenCloseIcons(expanded) {
const showIcon = !this.suppressOpenCloseIcons;
(0, import_ag_grid_community111._setDisplayed)(this.eGroupOpenedIcon, showIcon && expanded);
(0, import_ag_grid_community111._setDisplayed)(this.eGroupClosedIcon, showIcon && !expanded);
}
isSuppressCollapse() {
return this.suppressOpenCloseIcons;
}
dispatchExpandChanged(expanded) {
const event = {
type: "expandedChanged",
expanded
};
this.dispatchLocalEvent(event);
}
setTitle(title) {
const eGui = this.getGui();
const hasTitle = !!title && title.length > 0;
title = hasTitle ? title : void 0;
this.eTitle.textContent = title ?? "";
(0, import_ag_grid_community111._setDisplayed)(eGui, hasTitle);
if (title !== this.title) {
this.title = title;
}
const disabled = eGui.classList.contains(TITLE_BAR_DISABLED_CLASS);
this.refreshDisabledStyles(disabled);
return this;
}
addWidget(el) {
this.getGui().appendChild(el);
return this;
}
hideOpenCloseIcons(hide) {
this.suppressOpenCloseIcons = hide;
if (hide) {
this.dispatchExpandChanged(true);
}
return this;
}
refreshDisabledStyles(disabled) {
const eGui = this.getGui();
if (disabled) {
eGui.classList.add(TITLE_BAR_DISABLED_CLASS);
eGui.removeAttribute("tabindex");
} else {
eGui.classList.remove(TITLE_BAR_DISABLED_CLASS);
if (typeof this.title === "string" && !this.suppressKeyboardNavigation) {
eGui.setAttribute("tabindex", "0");
} else {
eGui.removeAttribute("tabindex");
}
}
}
};
var AgGroupComponentSelector = {
selector: "AG-GROUP-COMPONENT",
component: AgGroupComponent
};
// packages/ag-grid-enterprise/src/multiFilter/multiFilterUtil.ts
var import_ag_grid_community112 = require("ag-grid-community");
function getMultiFilterDefs(params) {
const { filters } = params;
return filters && filters.length > 0 ? filters : [{ filter: "agTextColumnFilter" }, { filter: "agSetColumnFilter" }];
}
function forEachReverse(list, action) {
if (list == null) {
return;
}
for (let i = list.length - 1; i >= 0; i--) {
action(list[i], i);
}
}
function getFilterTitle(filter, filterDef) {
if (filterDef.title != null) {
return filterDef.title;
}
return filter instanceof import_ag_grid_community112.ProvidedFilter ? filter.getFilterTitle() : "Filter";
}
function getUpdatedMultiFilterModel(existingModel, numFilters, newModel, index) {
const filterModels = [];
const existingFilterModels = existingModel?.filterModels;
for (let i = 0; i < numFilters; i++) {
filterModels[i] = (i === index ? newModel : existingFilterModels?.[i]) ?? null;
}
return filterModels.every((childModel) => childModel == null) ? null : {
filterType: "multi",
filterModels
};
}
function getFilterModelForIndex(model, index) {
return model?.filterModels?.[index] ?? null;
}
function updateGetValue(beans, column, filterDef, existingGetValue) {
const filterValueGetter = filterDef.filterValueGetter;
return filterValueGetter ? beans.colFilter.createGetValue(column, filterValueGetter) : existingGetValue;
}
// packages/ag-grid-enterprise/src/multiFilter/baseMultiFilter.ts
var BaseMultiFilter = class extends import_ag_grid_community113.TabGuardComp {
constructor() {
super({ tag: "div", cls: "ag-multi-filter ag-menu-list-compact" });
this.filterDefs = [];
this.guiDestroyFuncs = [];
// this could be the accordion/sub menu element depending on the display type
this.filterGuis = [];
this.lastActivatedMenuItem = null;
}
postConstruct() {
this.initialiseTabGuard({
onFocusIn: (e) => this.onFocusIn(e)
});
}
refreshGui(container) {
if (container === this.lastOpenedInContainer) {
return import_ag_grid_community113.AgPromise.resolve();
}
this.tabGuardFeature.removeAllChildrenExceptTabGuards();
this.destroyChildren();
return import_ag_grid_community113.AgPromise.all(
this.getFilterWrappers().map((wrapper, index) => {
if (!wrapper) {
return import_ag_grid_community113.AgPromise.resolve(null);
}
const filter = this.getFilterFromWrapper(wrapper);
const comp = this.getCompFromWrapper(wrapper);
const filterDef = this.filterDefs[index];
const filterTitle = getFilterTitle(filter, filterDef);
let filterGuiPromise;
if (filterDef.display === "subMenu" && container !== "toolPanel") {
filterGuiPromise = this.insertFilterMenu(comp, filter, filterTitle).then(
(menuItem) => menuItem.getGui()
);
} else if (filterDef.display === "subMenu" || filterDef.display === "accordion") {
const group = this.insertFilterGroup(filter, comp, filterTitle);
filterGuiPromise = import_ag_grid_community113.AgPromise.resolve(group.getGui());
} else {
filterGuiPromise = import_ag_grid_community113.AgPromise.resolve(comp.getGui());
}
return filterGuiPromise;
})
).then((filterGuis) => {
filterGuis.forEach((filterGui, index) => {
if (!filterGui) {
return;
}
if (index > 0) {
this.appendChild((0, import_ag_grid_community113._createElement)({ tag: "div", cls: "ag-filter-separator" }));
}
this.appendChild(filterGui);
});
this.filterGuis = filterGuis;
this.lastOpenedInContainer = container;
});
}
destroyChildren() {
this.guiDestroyFuncs.forEach((func) => func());
this.guiDestroyFuncs.length = 0;
this.filterGuis.length = 0;
}
insertFilterMenu(comp, filter, name) {
const eGui = comp.getGui();
(0, import_ag_grid_community113._setAriaRole)(eGui, "dialog");
const menuItem = this.createBean(new AgMenuItemComponent());
const childComponent = {
getGui: () => comp.getGui(),
afterGuiAttached: (params) => {
comp.afterGuiAttached?.(params);
if (comp !== filter) {
filter.afterGuiAttached?.(params);
}
}
};
return menuItem.init({
menuItemDef: {
name,
subMenu: [],
subMenuRole: "dialog",
cssClasses: ["ag-multi-filter-menu-item"],
menuItem: AgMenuItemRenderer,
menuItemParams: {
cssClassPrefix: "ag-compact-menu-option",
isCompact: true
}
},
level: 0,
isAnotherSubMenuOpen: () => false,
childComponent,
contextParams: {
column: null,
node: null,
value: null
}
}).then(() => {
menuItem.setParentComponent(this);
this.guiDestroyFuncs.push(() => this.destroyBean(menuItem));
this.addManagedListeners(menuItem, {
menuItemActivated: (event) => {
if (this.lastActivatedMenuItem && this.lastActivatedMenuItem !== event.menuItem) {
this.lastActivatedMenuItem.deactivate();
}
this.lastActivatedMenuItem = event.menuItem;
}
});
const menuItemGui = menuItem.getGui();
menuItem.addManagedElementListeners(menuItemGui, {
// `AgMenuList` normally handles keyboard navigation, so need to do here
keydown: (e) => {
const { key } = e;
switch (key) {
case import_ag_grid_community113.KeyCode.UP:
case import_ag_grid_community113.KeyCode.RIGHT:
case import_ag_grid_community113.KeyCode.DOWN:
case import_ag_grid_community113.KeyCode.LEFT:
e.preventDefault();
if (key === import_ag_grid_community113.KeyCode.RIGHT) {
menuItem.openSubMenu(true);
}
break;
}
},
focusin: () => menuItem.activate(),
focusout: () => {
if (!menuItem.isSubMenuOpen() && !menuItem.isSubMenuOpening()) {
menuItem.deactivate();
}
}
});
return menuItem;
});
}
insertFilterGroup(filter, comp, title) {
const group = this.createBean(
new AgGroupComponent({
title,
cssIdentifier: "multi-filter"
})
);
this.guiDestroyFuncs.push(() => this.destroyBean(group));
group.addItem(comp.getGui());
group.toggleGroupExpand(false);
if (filter.afterGuiAttached) {
group.addManagedListeners(group, {
expanded: () => filter.afterGuiAttached({
container: this.lastOpenedInContainer,
suppressFocus: true,
hidePopup: this.hidePopup
})
});
}
return group;
}
afterGuiAttached(params) {
let refreshPromise;
if (params) {
this.hidePopup = params.hidePopup;
refreshPromise = this.refreshGui(params.container);
} else {
this.hidePopup = void 0;
refreshPromise = import_ag_grid_community113.AgPromise.resolve();
}
const suppressFocus = params?.suppressFocus;
refreshPromise.then(() => {
const { filterDefs, filterGuis, beans } = this;
const wrappers = this.getFilterWrappers();
let hasFocused = !!suppressFocus;
if (filterDefs) {
forEachReverse(filterDefs, (filterDef, index) => {
const isFirst = index === 0;
const notInlineDisplayType = filterDef.display && filterDef.display !== "inline";
const suppressFocusForFilter = suppressFocus || !isFirst || notInlineDisplayType;
const afterGuiAttachedParams = { ...params ?? {}, suppressFocus: suppressFocusForFilter };
const wrapper = wrappers[index];
const filter = wrapper ? this.getFilterFromWrapper(wrapper) : void 0;
if (wrapper) {
const comp = this.getCompFromWrapper(wrapper);
if (comp !== filter) {
comp.afterGuiAttached(afterGuiAttachedParams);
}
}
if (filter) {
this.executeFunctionIfExistsOnFilter(filter, "afterGuiAttached", afterGuiAttachedParams);
if (isFirst && !suppressFocusForFilter) {
hasFocused = true;
}
}
if (!suppressFocus && isFirst && notInlineDisplayType) {
const filterGui = filterGuis[index];
if (filterGui) {
if (!(0, import_ag_grid_community113._focusInto)(filterGui)) {
filterGui.focus({ preventScroll: true });
}
hasFocused = true;
}
}
});
}
const activeEl = (0, import_ag_grid_community113._getActiveDomElement)(beans);
if (!hasFocused && ((0, import_ag_grid_community113._isNothingFocused)(beans) || this.getGui().contains(activeEl))) {
this.forceFocusOutOfContainer(true);
}
});
}
afterGuiDetached() {
this.executeFunctionIfExists("afterGuiDetached");
}
onAnyFilterChanged() {
this.executeFunctionIfExists(
"onAnyFilterChanged",
(wrapper) => this.executeOnWrapper(wrapper, "onAnyFilterChanged")
);
}
onNewRowsLoaded() {
this.executeFunctionIfExists("onNewRowsLoaded", (wrapper) => this.executeOnWrapper(wrapper, "onNewRowsLoaded"));
}
destroy() {
this.destroyChildren();
this.hidePopup = void 0;
super.destroy();
}
executeOnWrapper(_wrapper, _name) {
}
executeFunctionIfExists(name, executeOnHandler) {
forEachReverse(this.getFilterWrappers(), (wrapper) => {
if (wrapper) {
executeOnHandler?.(wrapper);
this.executeFunctionIfExistsOnFilter(this.getFilterFromWrapper(wrapper), name);
}
});
}
executeFunctionIfExistsOnFilter(filter, name, ...params) {
const func = filter[name];
if (typeof func === "function") {
func.apply(filter, params);
}
}
onFocusIn(e) {
const lastActivatedMenuItem = this.lastActivatedMenuItem;
if (lastActivatedMenuItem != null && !lastActivatedMenuItem.getGui().contains(e.target)) {
lastActivatedMenuItem.deactivate();
this.lastActivatedMenuItem = null;
}
}
};
// packages/ag-grid-enterprise/src/multiFilter/multiFilter.ts
var MultiFilter = class extends BaseMultiFilter {
constructor() {
super(...arguments);
this.filterType = "multi";
this.wrappers = [];
this.activeFilterIndices = [];
this.afterFiltersReadyFuncs = [];
}
init(params) {
this.params = params;
this.filterDefs = getMultiFilterDefs(params);
const initialModel = (0, import_ag_grid_community114._getFilterModel)(this.beans.colFilter.model, params.column.getColId());
const { filterChangedCallback } = params;
this.filterChangedCallback = filterChangedCallback;
const filterPromises = this.filterDefs.map(
(filterDef, index) => this.createFilter(filterDef, index, initialModel)
);
return new import_ag_grid_community114.AgPromise((resolve) => {
import_ag_grid_community114.AgPromise.all(filterPromises).then((wrappers) => {
this.wrappers = wrappers;
this.refreshGui("columnMenu").then(() => {
resolve();
});
});
}).then(() => {
this.afterFiltersReadyFuncs.forEach((f) => f());
this.afterFiltersReadyFuncs.length = 0;
});
}
refresh(params) {
this.params = params;
return true;
}
isFilterActive() {
return this.wrappers.some((wrapper) => {
if (!wrapper) {
return false;
}
const { filter, handler, model } = wrapper;
if (handler) {
return model != null;
}
return filter.isFilterActive();
});
}
getLastActiveFilterIndex() {
const activeFilterIndices = this.activeFilterIndices;
return activeFilterIndices.length > 0 ? activeFilterIndices[activeFilterIndices.length - 1] : null;
}
doesFilterPass(params, indexToSkip) {
return this.wrappers.every((wrapper, index) => {
if (!wrapper || indexToSkip != null && index === indexToSkip) {
return true;
}
const { handler, filter, model } = wrapper;
if (handler) {
return model == null || handler.doesFilterPass({
...params,
model,
handlerParams: wrapper.handlerParams
});
}
return !filter.isFilterActive() || filter.doesFilterPass(params);
});
}
getModelFromUi() {
const model = {
filterType: this.filterType,
filterModels: this.wrappers.map((wrapper) => {
if (!wrapper) {
return null;
}
const providedFilter = wrapper.filter;
if (typeof providedFilter.getModelFromUi === "function") {
return providedFilter.getModelFromUi();
}
return null;
})
};
return model;
}
getModel() {
if (!this.isFilterActive()) {
return null;
}
const model = {
filterType: this.filterType,
filterModels: this.wrappers.map((wrapper) => {
if (!wrapper) {
return null;
}
const { filter, handler, model: model2 } = wrapper;
if (handler) {
return model2;
}
return filter.isFilterActive() ? filter.getModel() : null;
})
};
return model;
}
setModel(model) {
const setFilterModel = (filter, filterModel) => {
return new import_ag_grid_community114.AgPromise((resolve) => {
const promise = filter.setModel(filterModel);
promise ? promise.then(() => resolve()) : resolve();
});
};
const promises = [];
this.wrappers.forEach((wrapper, index) => {
if (!wrapper) {
return;
}
const modelForFilter = getFilterModelForIndex(model, index);
const { filter, filterParams, handler, handlerParams, state } = wrapper;
if (handler) {
promises.push(
(0, import_ag_grid_community114._refreshHandlerAndUi)(
() => import_ag_grid_community114.AgPromise.resolve({ filter, filterParams }),
handler,
handlerParams,
modelForFilter,
state ?? { model: modelForFilter },
"api"
).then(() => {
wrapper.model = modelForFilter;
this.updateActiveListForHandler(index, modelForFilter);
})
);
} else {
promises.push(
setFilterModel(filter, modelForFilter).then(() => {
this.updateActiveListForFilter(index, filter);
})
);
}
});
return import_ag_grid_community114.AgPromise.all(promises).then(() => {
});
}
applyModel(source = "api") {
let result = false;
this.wrappers.forEach((wrapper) => {
if (wrapper) {
const filter = wrapper.filter;
if (filter instanceof import_ag_grid_community114.ProvidedFilter) {
result = filter.applyModel(source) || result;
}
}
});
return result;
}
getChildFilterInstance(index) {
return this.wrappers[index]?.filter;
}
destroy() {
this.wrappers.forEach((wrapper) => {
this.destroyBean(wrapper?.filter);
this.destroyBean(wrapper?.handler);
});
this.wrappers.length = 0;
super.destroy();
}
getFilterWrappers() {
return this.wrappers;
}
getFilterFromWrapper(wrapper) {
return wrapper.filter;
}
getCompFromWrapper(wrapper) {
return wrapper.comp;
}
executeOnWrapper(wrapper, name) {
wrapper.handler?.[name]?.();
}
createFilter(filterDef, index, initialModel) {
const column = this.params.column;
let initialModelForFilter = null;
let createWrapperComp;
const beans = this.beans;
const {
compDetails,
handler,
handlerParams: originalHandlerParams,
createFilterUi
} = beans.colFilter.createFilterInstance(
column,
filterDef,
"agTextColumnFilter",
(defaultParams, isHandler) => {
const updatedParams = {
...defaultParams,
filterChangedCallback: isHandler ? () => {
} : (additionalEventAttributes) => {
this.executeWhenAllFiltersReady(
() => this.onFilterModelChanged(index, additionalEventAttributes)
);
},
doesRowPassOtherFilter: (node) => defaultParams.doesRowPassOtherFilter(node) && this.doesFilterPass({ node, data: node.data }, index),
getValue: updateGetValue(beans, column, filterDef, defaultParams.getValue)
};
if (isHandler) {
initialModelForFilter = getFilterModelForIndex(initialModel, index);
createWrapperComp = this.updateDisplayParams(
updatedParams,
index,
initialModelForFilter,
() => compDetails,
() => handler
);
}
return updatedParams;
}
);
if (!createFilterUi) {
return import_ag_grid_community114.AgPromise.resolve(null);
}
let handlerParams;
if (handler) {
const { onModelChange, doesRowPassOtherFilter, getValue } = originalHandlerParams;
handlerParams = {
...originalHandlerParams,
onModelChange: (newModel, additionalEventAttributes) => onModelChange(
getUpdatedMultiFilterModel(this.params.model, this.wrappers.length, newModel, index),
additionalEventAttributes
),
doesRowPassOtherFilter: (node) => doesRowPassOtherFilter(node) && this.doesFilterPass({ node, data: node.data }, index),
getValue: updateGetValue(beans, column, filterDef, getValue)
};
handler.init?.({ ...handlerParams, model: initialModelForFilter, source: "init" });
}
return createFilterUi().then((filter) => {
if (!handler) {
return { filter, comp: filter };
}
const filterParams = compDetails?.params;
const comp = createWrapperComp(filter);
return {
filter,
comp,
filterParams,
handler,
handlerParams,
model: initialModelForFilter
};
});
}
updateDisplayParams(displayParams, index, initialModelForFilter, getCompDetails, getHandler) {
const column = this.params.column;
const eventSvc = new import_ag_grid_community114.LocalEventService();
displayParams.model = initialModelForFilter;
displayParams.state = { model: initialModelForFilter };
displayParams.onModelChange = (model, additionalEventAttributes) => {
const wrapper = this.wrappers[index];
if (!wrapper) {
return;
}
(0, import_ag_grid_community114._refreshHandlerAndUi)(
() => import_ag_grid_community114.AgPromise.resolve({
filter: wrapper.filter,
filterParams: wrapper.filterParams
}),
wrapper.handler,
wrapper.handlerParams,
model,
wrapper.state ?? { model },
"ui"
).then(() => {
wrapper.model = model;
this.onHandlerModelChanged(index, model, additionalEventAttributes);
});
};
displayParams.getHandler = getHandler;
const updateState = (wrapper, state) => {
wrapper.state = state;
eventSvc.dispatchEvent({
type: "filterStateChanged",
column,
state
});
};
displayParams.onStateChange = (state) => {
const wrapper = this.wrappers[index];
if (!wrapper) {
return;
}
updateState(wrapper, state);
(0, import_ag_grid_community114._refreshFilterUi)(wrapper.filter, wrapper.filterParams, wrapper.model ?? null, state, "ui");
};
const updateModel = (_column, action, additionalEventAttributes) => {
const wrapper = this.wrappers[index];
if (!wrapper) {
return;
}
const getModel = () => wrapper?.model ?? null;
(0, import_ag_grid_community114._updateFilterModel)(
action,
() => {
const promise = import_ag_grid_community114.AgPromise.resolve(wrapper.filter);
return {
created: true,
filterParams: wrapper.filterParams,
compDetails: getCompDetails(),
create: () => promise,
promise
};
},
getModel,
() => wrapper?.state ?? { model: getModel() },
(state) => updateState(wrapper, state),
(newModel) => wrapper.filterParams?.onModelChange(newModel, additionalEventAttributes)
);
};
displayParams.onAction = (action, additionalEventAttributes, event) => {
updateModel(column, action, additionalEventAttributes);
eventSvc.dispatchEvent({
type: "filterAction",
column,
action,
event
});
};
return (filter) => {
const filterParams = getCompDetails()?.params;
return this.createManagedBean(
new import_ag_grid_community114.FilterWrapperComp(
column,
{
comp: filter,
params: filterParams,
isHandler: true
},
eventSvc,
updateModel,
false
)
);
};
}
executeWhenAllFiltersReady(action) {
if ((this.wrappers?.length ?? 0) > 0) {
action();
} else {
this.afterFiltersReadyFuncs.push(action);
}
}
updateActiveListForFilter(index, filter) {
this.updateActiveList(index, () => filter?.isFilterActive());
}
updateActiveListForHandler(index, model) {
this.updateActiveList(index, () => model != null);
}
updateActiveList(index, isActive) {
const activeFilterIndices = this.activeFilterIndices;
(0, import_ag_grid_community114._removeFromArray)(this.activeFilterIndices, index);
if (isActive()) {
activeFilterIndices.push(index);
}
}
/** Only called for non-handlers */
onFilterModelChanged(index, additionalEventAttributes) {
this.updateActiveListForFilter(index, this.wrappers[index]?.filter);
this.filterChanged(index, additionalEventAttributes);
}
onHandlerModelChanged(index, model, additionalEventAttributes) {
this.updateActiveListForHandler(index, model);
this.filterChanged(index, additionalEventAttributes);
}
filterChanged(index, additionalEventAttributes) {
this.filterChangedCallback(additionalEventAttributes);
this.wrappers.forEach((wrapper, childIndex) => {
if (index === childIndex || !wrapper) {
return;
}
const { filter, handler } = wrapper;
handler?.onAnyFilterChanged?.();
if (typeof filter.onAnyFilterChanged === "function") {
filter.onAnyFilterChanged();
}
});
}
getModelAsString(model) {
if (!model?.filterModels?.length) {
return "";
}
const lastActiveIndex = this.getLastActiveFilterIndex() ?? 0;
const activeFilter = this.wrappers[lastActiveIndex]?.filter;
return activeFilter?.getModelAsString?.(model.filterModels[lastActiveIndex]) ?? "";
}
};
// packages/ag-grid-enterprise/src/multiFilter/multiFilterHandler.ts
var import_ag_grid_community115 = require("ag-grid-community");
var MultiFilterHandler = class extends import_ag_grid_community115.BeanStub {
constructor() {
super(...arguments);
/** Used to get the filter type for filter models. */
this.filterType = "multi";
this.handlerWrappers = [];
/** ui active. could still have null model */
this.activeFilterIndices = [];
this.filterDefs = [];
}
init(params) {
this.params = params;
const filterDefs = getMultiFilterDefs(params.filterParams);
this.filterDefs = filterDefs;
filterDefs.forEach((def, index) => {
const wrapper = this.beans.colFilter.createHandler(params.column, def, "agTextColumnFilter");
this.handlerWrappers.push(wrapper);
if (!wrapper) {
(0, import_ag_grid_community115._warn)(278, { colId: params.column.getColId() });
return;
}
const { handler, handlerParams } = wrapper;
handler.init?.({
...this.updateHandlerParams(handlerParams, index),
model: getFilterModelForIndex(params.model, index),
source: "init"
});
});
this.resetActiveList(params.model);
}
refresh(params) {
this.params = params;
const { model, source, filterParams } = params;
const filters = filterParams?.filters;
this.handlerWrappers.forEach((wrapper, index) => {
if (wrapper) {
const handlerParams = this.updateHandlerParams(params, index);
const originalFilterParams = handlerParams.filterParams;
const providedFilterParams = filters?.[index].filterParams;
const filterParamsForFilter = providedFilterParams ? { ...originalFilterParams, ...providedFilterParams } : originalFilterParams;
const updatedParams = {
...this.updateHandlerParams(params, index),
filterParams: filterParamsForFilter
};
wrapper.handlerParams = updatedParams;
wrapper.handler.refresh?.({
...updatedParams,
model: getFilterModelForIndex(model, index),
source
});
}
});
if (params.source !== "floating" && params.source !== "ui") {
this.resetActiveList(params.model);
}
}
updateHandlerParams(params, index) {
const { onModelChange, doesRowPassOtherFilter, getValue } = params;
const handlerParams = {
...params,
onModelChange: (newModel, additionalEventAttributes) => onModelChange(
getUpdatedMultiFilterModel(this.params.model, this.handlerWrappers.length, newModel, index),
additionalEventAttributes
),
doesRowPassOtherFilter: (node) => doesRowPassOtherFilter(node) && this.doesFilterPass({ node, data: node.data, model: this.params.model, handlerParams }, index),
getValue: updateGetValue(this.beans, params.column, this.filterDefs[index], getValue)
};
return handlerParams;
}
doesFilterPass(params, indexToSkip) {
const filterModels = params.model?.filterModels;
if (filterModels == null) {
return true;
}
return this.handlerWrappers.every((wrapper, index) => {
const model = filterModels[index];
if (model == null || indexToSkip != null && index === indexToSkip) {
return true;
}
const handler = wrapper?.handler;
return !handler || handler.doesFilterPass({ ...params, model, handlerParams: wrapper.handlerParams });
});
}
resetActiveList(model) {
this.activeFilterIndices = [];
const filterModels = model?.filterModels;
if (filterModels == null) {
return;
}
for (let i = 0; i < this.handlerWrappers.length; i++) {
const isActive = filterModels[i] != null;
if (isActive) {
this.activeFilterIndices.push(i);
}
}
}
updateActiveList(index, childModel) {
const activeFilterIndices = this.activeFilterIndices;
(0, import_ag_grid_community115._removeFromArray)(activeFilterIndices, index);
if (childModel != null) {
activeFilterIndices.push(index);
}
}
getLastActiveFilterIndex() {
const activeFilterIndices = this.activeFilterIndices;
return activeFilterIndices.length > 0 ? activeFilterIndices[activeFilterIndices.length - 1] : null;
}
getModelAsString(model, source) {
const isForToolPanel = source === "filterToolPanel";
const defaultOption = () => isForToolPanel ? this.getLocaleTextFunc()("filterSummaryInactive", "is (All)") : "";
if (!model?.filterModels?.length) {
return defaultOption();
}
const lastActiveIndex = this.getLastActiveFilterIndex() ?? 0;
const activeWrapper = this.handlerWrappers[lastActiveIndex];
return activeWrapper?.handler.getModelAsString?.(model.filterModels[lastActiveIndex], source) ?? defaultOption();
}
getHandler(index) {
return this.handlerWrappers[index]?.handler;
}
onAnyFilterChanged() {
forEachReverse(this.handlerWrappers, (wrapper) => wrapper?.handler?.onAnyFilterChanged?.());
}
onNewRowsLoaded() {
forEachReverse(this.handlerWrappers, (wrapper) => wrapper?.handler?.onNewRowsLoaded?.());
}
destroy() {
this.handlerWrappers.forEach((wrapper) => this.destroyBean(wrapper?.handler));
this.handlerWrappers.length = 0;
super.destroy();
}
};
// packages/ag-grid-enterprise/src/multiFilter/multiFilterService.ts
var import_ag_grid_community116 = require("ag-grid-community");
var MultiFilterService = class extends import_ag_grid_community116.BeanStub {
constructor() {
super(...arguments);
this.beanName = "multiFilter";
}
getParamsForDataType(existingFilterParams, existingFilterValueGetter, dataTypeDefinition, formatValue) {
let filters = existingFilterParams?.filters;
const beans = this.beans;
if (!filters) {
const simpleFilter = (0, import_ag_grid_community116._getDefaultSimpleFilter)(dataTypeDefinition.baseDataType);
filters = [{ filter: simpleFilter }, { filter: "agSetColumnFilter" }];
}
const translate = this.getLocaleTextFunc();
filters = filters.map((filterDef) => {
const {
filter,
filterParams: existingChildFilterParams,
filterValueGetter: existingChildFilterValueGetter
} = filterDef;
if (typeof filter !== "string") {
return filterDef;
}
const { filterParams, filterValueGetter } = (0, import_ag_grid_community116._getFilterParamsForDataType)(
filter,
existingChildFilterParams,
existingChildFilterValueGetter ?? existingFilterValueGetter,
dataTypeDefinition,
formatValue,
beans,
translate
);
return {
...filterDef,
filterParams,
filterValueGetter
};
});
return {
filterParams: {
...existingFilterParams,
filters
}
};
}
};
// packages/ag-grid-enterprise/src/multiFilter/multiFilterUi.ts
var import_ag_grid_community117 = require("ag-grid-community");
var MultiFilterUi = class extends BaseMultiFilter {
constructor() {
super(...arguments);
this.filterType = "multi";
this.filters = [];
this.filterParams = [];
this.validity = [];
}
init(params) {
this.params = params;
this.filterDefs = getMultiFilterDefs(params);
this.allState = params.state;
const filterPromises = this.filterDefs.map(
(filterDef, index) => this.createFilter(filterDef, index)
);
return new import_ag_grid_community117.AgPromise((resolve) => {
import_ag_grid_community117.AgPromise.all(filterPromises).then((filters) => {
this.filters = filters;
this.refreshGui("columnMenu").then(() => {
resolve();
});
});
});
}
refresh(params) {
const { model, state, source } = params;
if (source === "colDef") {
return false;
}
this.params = params;
const filterParams = this.filterParams;
if (state === this.allState) {
return true;
}
this.allState = state;
const newAllStateState = state.state;
this.filters.forEach((filter, index) => {
const modelForFilter = getFilterModelForIndex(model, index);
const stateForFilter = {
state: newAllStateState?.[index],
model: getFilterModelForIndex(state.model, index)
};
(0, import_ag_grid_community117._refreshFilterUi)(filter, filterParams[index], modelForFilter, stateForFilter, source);
});
return true;
}
getLastActiveFilterIndex() {
return this.getHandler().getLastActiveFilterIndex?.() ?? null;
}
getChildFilterInstance(index) {
return this.filters[index] ?? void 0;
}
destroy() {
this.filters.forEach((filter) => this.destroyBean(filter));
this.filters.length = 0;
super.destroy();
}
getFilterWrappers() {
return this.filters;
}
getFilterFromWrapper(wrapper) {
return wrapper;
}
getCompFromWrapper(wrapper) {
return wrapper;
}
createFilter(filterDef, index) {
const userCompFactory = this.beans.userCompFactory;
const filterParams = this.updateParams(filterDef, this.params, index);
const compDetails = (0, import_ag_grid_community117._getFilterDetails)(
userCompFactory,
filterDef,
filterParams,
"agTextColumnFilter"
);
if (!compDetails) {
return import_ag_grid_community117.AgPromise.resolve(null);
}
this.filterParams[index] = compDetails.params;
return compDetails.newAgStackInstance();
}
updateParams(filterDef, params, index) {
const {
doesRowPassOtherFilter,
model,
onModelChange,
state,
onStateChange,
column,
source,
onAction,
onUiChange,
getValue
} = params;
const filterModel = getFilterModelForIndex(model, index);
const filterState = state ? {
model: getFilterModelForIndex(state.model, index),
state: state.state?.[index]
} : { model: filterModel };
const onAnyFilterChanged = () => {
const handler = this.getHandler();
this.filters.forEach((filter, otherIndex) => {
if (index !== otherIndex) {
handler.getHandler(otherIndex)?.onAnyFilterChanged?.();
filter?.onAnyFilterChanged?.();
}
});
};
const colFilter = this.beans.colFilter;
return {
...colFilter.createBaseFilterParams(column),
...filterDef,
doesRowPassOtherFilter: (node) => doesRowPassOtherFilter(node) && this.getHandler().doesFilterPass(
{
node,
data: node.data,
model: this.params.model,
handlerParams: colFilter.getHandlerParams(column)
},
index
),
model: filterModel,
state: filterState,
onModelChange: (childModel, additionalEventAttributes) => {
const { filters, params: params2 } = this;
const newModel = getUpdatedMultiFilterModel(params2.model, filters.length, childModel, index);
this.updateActiveList(index, childModel);
onModelChange(newModel, additionalEventAttributes);
onAnyFilterChanged();
},
onStateChange: (newState) => this.onStateChange(onStateChange, index, newState),
getHandler: () => this.getHandler().getHandler(index),
onAction: (action, additionalEventAttributes, event) => {
if ((0, import_ag_grid_community117._isUseApplyButton)(params)) {
return;
}
const isChange = action === "apply" || action === "reset";
if (isChange) {
this.updateActiveList(index, getFilterModelForIndex(this.params.state.model, index));
}
onAction(action, additionalEventAttributes, event);
if (isChange) {
onAnyFilterChanged();
}
},
onUiChange,
source,
getValue: updateGetValue(this.beans, column, filterDef, getValue)
};
}
updateActiveList(index, childModel) {
this.getHandler().updateActiveList?.(index, childModel);
}
getHandler() {
return this.params.getHandler();
}
onStateChange(onStateChange, index, newState) {
const { model, state, valid } = newState;
const validity = this.validity;
validity[index] = valid;
const allState = this.allState;
const newModel = getUpdatedMultiFilterModel(allState.model, this.filters.length, model, index);
const allValid = validity.every((filterValid) => filterValid !== false);
const allStateState = [...allState.state ?? []];
allStateState[index] = state;
const newAllState = {
state: allStateState,
model: newModel,
valid: allValid
};
this.allState = newAllState;
onStateChange(newAllState);
}
getModelAsString(model) {
return this.getHandler().getModelAsString?.(model) ?? "";
}
};
// packages/ag-grid-enterprise/src/multiFilter/multiFloatingFilter.ts
var import_ag_grid_community118 = require("ag-grid-community");
var MultiFloatingFilterElement = {
tag: "div",
cls: "ag-multi-floating-filter ag-floating-filter-input"
};
var MultiFloatingFilterComp = class extends import_ag_grid_community118.Component {
constructor() {
super(MultiFloatingFilterElement);
this.floatingFilters = [];
this.compDetailsList = [];
}
init(params) {
this.params = params;
const { compDetailsList } = this.getCompDetailsList(params);
return this.setParams(compDetailsList);
}
setParams(compDetailsList) {
const floatingFilterPromises = [];
compDetailsList.forEach((compDetails) => {
const floatingFilterPromise = compDetails?.newAgStackInstance();
if (floatingFilterPromise != null) {
this.compDetailsList.push(compDetails);
floatingFilterPromises.push(floatingFilterPromise);
}
});
return import_ag_grid_community118.AgPromise.all(floatingFilterPromises).then((floatingFilters) => {
floatingFilters.forEach((floatingFilter, index) => {
this.floatingFilters.push(floatingFilter);
const gui = floatingFilter.getGui();
this.appendChild(gui);
if (index > 0) {
(0, import_ag_grid_community118._setDisplayed)(gui, false);
}
});
});
}
refresh(params) {
this.params = params;
const { compDetailsList: newCompDetailsList, floatingFilterParamsList } = this.getCompDetailsList(params);
const allFloatingFilterCompsUnchanged = newCompDetailsList.length === this.compDetailsList.length && newCompDetailsList.every(
(newCompDetails, index) => !this.beans.colFilter?.areFilterCompsDifferent(this.compDetailsList[index], newCompDetails)
);
if (allFloatingFilterCompsUnchanged) {
floatingFilterParamsList.forEach((floatingFilterParams, index) => {
const floatingFilter = this.floatingFilters[index];
floatingFilter.refresh?.(floatingFilterParams);
});
if (this.gos.get("enableFilterHandlers")) {
const reactiveParams = params;
if (reactiveParams.model == null) {
this.floatingFilters.forEach((filter, i) => {
(0, import_ag_grid_community118._setDisplayed)(filter.getGui(), i === 0);
});
} else {
const lastActiveFloatingFilterIndex = reactiveParams.getHandler()?.getLastActiveFilterIndex?.();
this.floatingFilters.forEach((filter, i) => {
const shouldShow = lastActiveFloatingFilterIndex == null ? i === 0 : i === lastActiveFloatingFilterIndex;
(0, import_ag_grid_community118._setDisplayed)(filter.getGui(), shouldShow);
});
}
}
} else {
(0, import_ag_grid_community118._clearElement)(this.getGui());
this.destroyBeans(this.floatingFilters);
this.floatingFilters = [];
this.compDetailsList = [];
this.setParams(newCompDetailsList);
}
}
getCompDetailsList(params) {
const compDetailsList = [];
const floatingFilterParamsList = [];
const filterParams = params.filterParams;
const currentParentModel = params.currentParentModel;
const filterDefs = getMultiFilterDefs(filterParams);
filterDefs.forEach((filterDef, index) => {
const floatingFilterParams = {
...params,
// set the parent filter instance for each floating filter to the relevant child filter instance
parentFilterInstance: (callback) => {
this.parentMultiFilterInstance((parent) => {
const child = parent.getChildFilterInstance(index);
if (child == null) {
return;
}
callback(child);
});
},
// return the parent model for the specific filter
currentParentModel: () => currentParentModel()?.filterModels?.[index] ?? null
};
if (this.gos.get("enableFilterHandlers")) {
const reactiveParams = floatingFilterParams;
reactiveParams.model = reactiveParams.model?.filterModels?.[index] ?? null;
const { onModelChange, getHandler } = reactiveParams;
reactiveParams.onModelChange = (newModel, additionalEventAttributes) => onModelChange(
getUpdatedMultiFilterModel(
this.params.model,
filterDefs.length,
newModel,
index
),
additionalEventAttributes
);
reactiveParams.getHandler = () => {
const multiFilterHandler = getHandler();
return multiFilterHandler.getHandler(index);
};
}
(0, import_ag_grid_community118._mergeDeep)(floatingFilterParams.filterParams, filterDef.filterParams);
const compDetails = this.getCompDetails(filterDef, floatingFilterParams);
if (compDetails) {
compDetailsList.push(compDetails);
floatingFilterParamsList.push(floatingFilterParams);
}
});
return { compDetailsList, floatingFilterParamsList };
}
onParentModelChanged(model, event) {
if (event && event.afterFloatingFilter) {
return;
}
this.parentMultiFilterInstance((parent) => {
if (model == null) {
this.floatingFilters.forEach((filter, i) => {
filter.onParentModelChanged(null, event);
(0, import_ag_grid_community118._setDisplayed)(filter.getGui(), i === 0);
});
} else {
const lastActiveFloatingFilterIndex = parent.getLastActiveFilterIndex();
this.floatingFilters.forEach((filter, i) => {
const filterModel = model.filterModels.length > i ? model.filterModels[i] : null;
filter.onParentModelChanged(filterModel, event);
const shouldShow = lastActiveFloatingFilterIndex == null ? i === 0 : i === lastActiveFloatingFilterIndex;
(0, import_ag_grid_community118._setDisplayed)(filter.getGui(), shouldShow);
});
}
});
}
destroy() {
this.destroyBeans(this.floatingFilters);
this.floatingFilters.length = 0;
super.destroy();
}
getCompDetails(filterDef, params) {
const { colFilter, frameworkOverrides, userCompFactory } = this.beans;
const defaultComponentName = (0, import_ag_grid_community118._getDefaultFloatingFilterType)(
frameworkOverrides,
filterDef,
() => colFilter.getDefaultFloatingFilter(this.params.column)
) ?? "agReadOnlyFloatingFilter";
return (0, import_ag_grid_community118._getFloatingFilterCompDetails)(userCompFactory, filterDef, params, defaultComponentName);
}
parentMultiFilterInstance(cb) {
this.params.parentFilterInstance((parent) => {
if (!(parent instanceof MultiFilter || parent instanceof MultiFilterUi)) {
(0, import_ag_grid_community118._error)(120);
}
cb(parent);
});
}
};
// packages/ag-grid-enterprise/src/multiFilter/multiFilterModule.ts
var MultiFilterModule = {
moduleName: "MultiFilter",
version: VERSION,
userComponents: {
agMultiColumnFilter: {
getComp: (beans) => beans.gos.get("enableFilterHandlers") ? {
classImp: MultiFilterUi,
params: {
useForm: true
}
} : MultiFilter
},
agMultiColumnFloatingFilter: MultiFloatingFilterComp
},
beans: [MultiFilterService],
dynamicBeans: {
agMultiColumnFilterHandler: MultiFilterHandler
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community119._ColumnFilterModule, MenuItemModule]
};
// packages/ag-grid-enterprise/src/rowGrouping/rowGroupingModule.ts
var import_ag_grid_community149 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/aggregation/aggColumnNameService.ts
var import_ag_grid_community120 = require("ag-grid-community");
var AggColumnNameService = class extends import_ag_grid_community120.BeanStub {
constructor() {
super(...arguments);
this.beanName = "aggColNameSvc";
}
getHeaderName(column, headerName) {
if (this.gos.get("suppressAggFuncInHeader")) {
return headerName;
}
const { valueColsSvc, colModel, rowGroupColsSvc } = this.beans;
const pivotValueColumn = column.getColDef().pivotValueColumn;
const pivotActiveOnThisColumn = (0, import_ag_grid_community120._exists)(pivotValueColumn);
let aggFunc = null;
let aggFuncFound;
if (pivotActiveOnThisColumn) {
const valueColumns = valueColsSvc?.columns ?? [];
const isCollapsedHeaderEnabled = this.gos.get("removePivotHeaderRowWhenSingleValueColumn") && valueColumns.length === 1;
const isTotalColumn = column.getColDef().pivotTotalColumnIds !== void 0;
if (isCollapsedHeaderEnabled && !isTotalColumn) {
return headerName;
}
aggFunc = pivotValueColumn ? pivotValueColumn.getAggFunc() : null;
aggFuncFound = true;
} else {
const measureActive = column.isValueActive();
const aggregationPresent = colModel.isPivotMode() || rowGroupColsSvc?.columns.length !== 0;
if (measureActive && aggregationPresent) {
aggFunc = column.getAggFunc();
aggFuncFound = true;
} else {
aggFuncFound = false;
}
}
if (aggFuncFound) {
const aggFuncString = typeof aggFunc === "string" ? aggFunc : "func";
const localeTextFunc = this.getLocaleTextFunc();
const aggFuncStringTranslated = localeTextFunc(aggFuncString, aggFuncString);
return `${aggFuncStringTranslated}(${headerName})`;
}
return headerName;
}
};
// packages/ag-grid-enterprise/src/aggregation/aggFuncService.ts
var import_ag_grid_community121 = require("ag-grid-community");
var defaultAggFuncNames = {
sum: "Sum",
first: "First",
last: "Last",
min: "Min",
max: "Max",
count: "Count",
avg: "Average"
};
var AggFuncService = class extends import_ag_grid_community121.BeanStub {
constructor() {
super(...arguments);
this.beanName = "aggFuncSvc";
this.aggFuncsMap = {};
this.initialised = false;
}
postConstruct() {
this.init();
}
init() {
if (this.initialised) {
return;
}
this.initialiseWithDefaultAggregations();
this.addAggFuncs(this.gos.get("aggFuncs"));
}
initialiseWithDefaultAggregations() {
const aggMap = this.aggFuncsMap;
aggMap["sum"] = aggSum;
aggMap["first"] = aggFirst;
aggMap["last"] = aggLast;
aggMap["min"] = aggMin;
aggMap["max"] = aggMax;
aggMap["count"] = aggCount;
aggMap["avg"] = aggAvg;
this.initialised = true;
}
isAggFuncPossible(column, func) {
const allKeys = this.getFuncNames(column);
const allowed = allKeys.includes(func);
const funcExists = (0, import_ag_grid_community121._exists)(this.aggFuncsMap[func]);
return allowed && funcExists;
}
getDefaultFuncLabel(fctName) {
return defaultAggFuncNames[fctName] ?? fctName;
}
getDefaultAggFunc(column) {
const defaultAgg = column.getColDef().defaultAggFunc;
if ((0, import_ag_grid_community121._exists)(defaultAgg) && this.isAggFuncPossible(column, defaultAgg)) {
return defaultAgg;
}
if (this.isAggFuncPossible(column, "sum")) {
return "sum";
}
const allKeys = this.getFuncNames(column);
return allKeys?.length ? allKeys[0] : null;
}
addAggFuncs(aggFuncs) {
this.init();
if (!aggFuncs) {
return;
}
for (const key of Object.keys(aggFuncs)) {
if (aggFuncs[key]) {
this.aggFuncsMap[key] = aggFuncs[key];
}
}
}
getAggFunc(name) {
this.init();
return this.aggFuncsMap[name];
}
getFuncNames(column) {
const userAllowedFuncs = column.getColDef().allowedAggFuncs;
return userAllowedFuncs == null ? Object.keys(this.aggFuncsMap).sort() : userAllowedFuncs;
}
clear() {
this.aggFuncsMap = {};
}
};
function aggSum(params) {
const { values } = params;
let result = null;
for (let i = 0; i < values.length; i++) {
const value = values[i];
if (typeof value === "number") {
if (result === null) {
result = value;
} else {
result += typeof result === "number" ? value : BigInt(value);
}
} else if (typeof value === "bigint") {
if (result === null) {
result = value;
} else {
result = (typeof result === "bigint" ? result : BigInt(result)) + value;
}
}
}
return result;
}
function aggFirst(params) {
return params.values.length > 0 ? params.values[0] : null;
}
function aggLast(params) {
return params.values.length > 0 ? (0, import_ag_grid_community121._last)(params.values) : null;
}
function aggMin(params) {
const { values } = params;
let result = null;
for (let i = 0; i < values.length; i++) {
const value = values[i];
if ((typeof value === "number" || typeof value === "bigint") && (result === null || result > value)) {
result = value;
}
}
return result;
}
function aggMax(params) {
const { values } = params;
let result = null;
for (let i = 0; i < values.length; i++) {
const value = values[i];
if ((typeof value === "number" || typeof value === "bigint") && (result === null || result < value)) {
result = value;
}
}
return result;
}
var COUNT_PROTO = Object.freeze({
// the grid by default uses toString to render values for an object, so this
// is a trick to get the default cellRenderer to display the avg value
toString: function() {
return this.value.toString();
},
// used for sorting
toNumber: function() {
return this.value;
}
});
function aggCount(params) {
const { values } = params;
let count = 0;
for (let i = 0; i < values.length; i++) {
const value = values[i];
count += value != null && typeof value.value === "number" ? value.value : 1;
}
const existingAggData = params.rowNode?.aggData?.[params.column.getColId()];
if (existingAggData && existingAggData.value === count) {
return existingAggData;
}
const result = Object.create(COUNT_PROTO);
result.value = count;
return result;
}
var AVERAGE_PROTO = Object.freeze({
// the grid by default uses toString to render values for an object, so this
// is a trick to get the default cellRenderer to display the avg value
toString: function() {
return typeof this.value === "number" || typeof this.value === "bigint" ? this.value.toString() : "";
},
// used for sorting
toNumber: function() {
return this.value;
}
});
function aggAvg(params) {
const { values } = params;
let sum = 0;
let count = 0;
for (let i = 0; i < values.length; i++) {
const currentValue = values[i];
let valueToAdd = null;
if (typeof currentValue === "number" || typeof currentValue === "bigint") {
valueToAdd = currentValue;
count++;
} else if (currentValue != null && (typeof currentValue.value === "number" || typeof currentValue.value === "bigint") && typeof currentValue.count === "number") {
valueToAdd = currentValue.value * (typeof currentValue.value === "number" ? currentValue.count : BigInt(currentValue.count));
count += currentValue.count;
}
if (typeof valueToAdd === "number") {
sum += typeof sum === "number" ? valueToAdd : BigInt(valueToAdd);
} else if (typeof valueToAdd === "bigint") {
sum = (typeof sum === "bigint" ? sum : BigInt(sum)) + valueToAdd;
}
}
let value = null;
if (count > 0) {
value = sum / (typeof sum === "number" ? count : BigInt(count));
}
const existingAggData = params.rowNode?.aggData?.[params.column?.getColId()];
if (existingAggData && existingAggData.count === count && existingAggData.value === value) {
return existingAggData;
}
const result = Object.create(AVERAGE_PROTO);
result.count = count;
result.value = value;
return result;
}
// packages/ag-grid-enterprise/src/aggregation/aggregationApi.ts
function addAggFuncs(beans, aggFuncs) {
if (beans.aggFuncSvc) {
beans.aggFuncSvc.addAggFuncs(aggFuncs);
}
}
function clearAggFuncs(beans) {
if (beans.aggFuncSvc) {
beans.aggFuncSvc.clear();
}
}
function setColumnAggFunc(beans, key, aggFunc) {
beans.valueColsSvc?.setColumnAggFunc?.(key, aggFunc, "api");
}
// packages/ag-grid-enterprise/src/aggregation/aggregationStage.ts
var import_ag_grid_community124 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/aggregation/aggUtils.ts
var import_ag_grid_community122 = require("ag-grid-community");
var import_ag_grid_community123 = require("ag-grid-community");
function _aggregateValues(beans, values, aggFuncOrString, column, rowNode, pivotResultColumn) {
const aggFunc = typeof aggFuncOrString === "string" ? beans.aggFuncSvc.getAggFunc(aggFuncOrString) : aggFuncOrString;
if (typeof aggFunc !== "function") {
(0, import_ag_grid_community122._warn)(109, { inputValue: aggFuncOrString.toString(), allSuggestions: beans.aggFuncSvc.getFuncNames(column) });
return null;
}
const params = (0, import_ag_grid_community123._addGridCommonParams)(beans.gos, {
values,
column,
colDef: column.colDef,
pivotResultColumn,
rowNode,
// this is typed incorrectly. Within CSRM, this will always be defined. When called from integrated charts, this will never be defined.
data: rowNode?.data
});
return aggFunc(params);
}
// packages/ag-grid-enterprise/src/aggregation/aggregationStage.ts
var AggregationStage = class extends import_ag_grid_community124.BeanStub {
constructor() {
super(...arguments);
this.beanName = "aggStage";
this.refreshProps = /* @__PURE__ */ new Set([
"getGroupRowAgg",
"alwaysAggregateAtRootLevel",
"suppressAggFilteredOnly",
"grandTotalRow"
]);
this.step = "aggregate";
}
wireBeans(beans) {
this.colModel = beans.colModel;
this.pivotColsSvc = beans.pivotColsSvc;
this.valueColsSvc = beans.valueColsSvc;
this.pivotResultCols = beans.pivotResultCols;
this.valueSvc = beans.valueSvc;
}
// it's possible to recompute the aggregate without doing the other parts
// + api.refreshClientSideRowModel('aggregate')
execute(params) {
const noValueColumns = !this.valueColsSvc?.columns?.length;
const noUserAgg = !this.gos.getCallback("getGroupRowAgg");
if (noValueColumns && noUserAgg && params.changedPath?.active) {
return;
}
const aggDetails = this.createAggDetails(params);
this.recursivelyCreateAggData(aggDetails);
}
createAggDetails(params) {
const pivotActive = this.colModel.isPivotActive();
const measureColumns = this.valueColsSvc?.columns;
const pivotColumns = pivotActive && this.pivotColsSvc ? this.pivotColsSvc.columns : [];
const aggDetails = {
alwaysAggregateAtRootLevel: this.gos.get("alwaysAggregateAtRootLevel"),
groupIncludeTotalFooter: !!(0, import_ag_grid_community124._getGrandTotalRow)(this.gos),
changedPath: params.changedPath,
valueColumns: measureColumns ?? [],
pivotColumns,
filteredOnly: !this.isSuppressAggFilteredOnly(),
userAggFunc: this.gos.getCallback("getGroupRowAgg")
};
return aggDetails;
}
isSuppressAggFilteredOnly() {
const isGroupAggFiltering = (0, import_ag_grid_community124._getGroupAggFiltering)(this.gos) !== void 0;
return isGroupAggFiltering || this.gos.get("suppressAggFilteredOnly");
}
recursivelyCreateAggData(aggDetails) {
const callback = (rowNode) => {
const hasNoChildren = !rowNode.hasChildren();
if (hasNoChildren) {
if (rowNode.aggData) {
this.setAggData(rowNode, null);
}
return;
}
const isRootNode = rowNode.level === -1;
if (isRootNode && !aggDetails.groupIncludeTotalFooter) {
const notPivoting = !this.colModel.isPivotMode();
if (!aggDetails.alwaysAggregateAtRootLevel && notPivoting) {
this.setAggData(rowNode, null);
return;
}
}
this.aggregateRowNode(rowNode, aggDetails);
};
aggDetails.changedPath.forEachChangedNodeDepthFirst(callback, true);
}
aggregateRowNode(rowNode, aggDetails) {
const measureColumnsMissing = aggDetails.valueColumns.length === 0;
const pivotColumnsMissing = aggDetails.pivotColumns.length === 0;
let aggResult;
if (aggDetails.userAggFunc) {
aggResult = aggDetails.userAggFunc({ nodes: rowNode.childrenAfterFilter });
} else if (measureColumnsMissing) {
aggResult = null;
} else if (pivotColumnsMissing) {
aggResult = this.aggregateRowNodeUsingValuesOnly(rowNode, aggDetails);
} else {
aggResult = this.aggregateRowNodeUsingValuesAndPivot(rowNode);
}
this.setAggData(rowNode, aggResult);
if (rowNode.sibling) {
this.setAggData(rowNode.sibling, aggResult);
if (rowNode.sibling.pinnedSibling) {
this.setAggData(rowNode.sibling.pinnedSibling, aggResult);
}
}
}
aggregateRowNodeUsingValuesAndPivot(rowNode) {
const result = {};
const secondaryColumns = this.pivotResultCols?.getPivotResultCols()?.list ?? [];
let canSkipTotalColumns = true;
const beans = this.beans;
for (let i = 0; i < secondaryColumns.length; i++) {
const secondaryCol = secondaryColumns[i];
const colDef = secondaryCol.getColDef();
if (colDef.pivotTotalColumnIds != null) {
canSkipTotalColumns = false;
continue;
}
const keys = colDef.pivotKeys ?? [];
let values;
if (rowNode.leafGroup) {
values = this.getValuesFromMappedSet(rowNode.childrenMapped, keys, colDef.pivotValueColumn);
} else {
values = this.getValuesPivotNonLeaf(rowNode, colDef.colId);
}
result[colDef.colId] = _aggregateValues(
beans,
values,
colDef.pivotValueColumn.getAggFunc(),
colDef.pivotValueColumn,
rowNode,
secondaryCol
);
}
if (!canSkipTotalColumns) {
for (let i = 0; i < secondaryColumns.length; i++) {
const secondaryCol = secondaryColumns[i];
const colDef = secondaryCol.getColDef();
if (colDef.pivotTotalColumnIds == null || !colDef.pivotTotalColumnIds.length) {
continue;
}
const aggResults = colDef.pivotTotalColumnIds.map(
(currentColId) => result[currentColId]
);
result[colDef.colId] = _aggregateValues(
beans,
aggResults,
colDef.pivotValueColumn.getAggFunc(),
colDef.pivotValueColumn,
rowNode,
secondaryCol
);
}
}
return result;
}
aggregateRowNodeUsingValuesOnly(rowNode, aggDetails) {
const result = {};
const { changedPath, valueColumns, filteredOnly } = aggDetails;
const changedValueColumns = changedPath.active ? changedPath.getValueColumnsForNode(rowNode, valueColumns) : valueColumns;
const notChangedValueColumns = changedPath.active ? changedPath.getNotValueColumnsForNode(rowNode, valueColumns) : null;
const values2d = this.getValuesNormal(rowNode, changedValueColumns, filteredOnly);
const oldValues = rowNode.aggData;
const beans = this.beans;
changedValueColumns.forEach((valueColumn, index) => {
result[valueColumn.getId()] = _aggregateValues(
beans,
values2d[index],
valueColumn.getAggFunc(),
valueColumn,
rowNode
);
});
if (notChangedValueColumns && oldValues) {
notChangedValueColumns.forEach((valueColumn) => {
result[valueColumn.getId()] = oldValues[valueColumn.getId()];
});
}
return result;
}
getValuesPivotNonLeaf(rowNode, colId) {
return rowNode.childrenAfterFilter.map((childNode) => childNode.aggData[colId]);
}
getValuesFromMappedSet(mappedSet, keys, valueColumn) {
let mapPointer = mappedSet;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
mapPointer = mapPointer ? mapPointer[key] : null;
}
if (!mapPointer) {
return [];
}
return mapPointer.map((rowNode) => this.valueSvc.getValue(valueColumn, rowNode));
}
getValuesNormal(rowNode, valueColumns, filteredOnly) {
const values = [];
valueColumns.forEach(() => values.push([]));
const valueColumnCount = valueColumns.length;
const nodeList = filteredOnly ? rowNode.childrenAfterFilter : rowNode.childrenAfterGroup;
const rowCount = nodeList.length;
for (let i = 0; i < rowCount; i++) {
const childNode = nodeList[i];
for (let j = 0; j < valueColumnCount; j++) {
const valueColumn = valueColumns[j];
const value = this.valueSvc.getValue(valueColumn, childNode);
values[j].push(value);
}
}
return values;
}
setAggData(rowNode, newAggData) {
const oldAggData = rowNode.aggData;
rowNode.aggData = newAggData;
if (rowNode.__localEventService) {
const eventFunc = (colId) => {
const value = rowNode.aggData ? rowNode.aggData[colId] : void 0;
const oldValue = oldAggData ? oldAggData[colId] : void 0;
if (value === oldValue) {
return;
}
const column = this.colModel.getColById(colId);
if (!column) {
return;
}
rowNode.dispatchCellChangedEvent(column, value, oldValue);
};
if (oldAggData) {
for (const key of Object.keys(oldAggData)) {
eventFunc(key);
}
}
if (newAggData) {
for (const key of Object.keys(newAggData)) {
if (!oldAggData || !(key in oldAggData)) {
eventFunc(key);
}
}
}
}
}
};
// packages/ag-grid-enterprise/src/aggregation/filterAggregatesStage.ts
var import_ag_grid_community125 = require("ag-grid-community");
var FilterAggregatesStage = class extends import_ag_grid_community125.BeanStub {
constructor() {
super(...arguments);
this.beanName = "filterAggStage";
this.refreshProps = /* @__PURE__ */ new Set([]);
this.step = "filter_aggregates";
}
wireBeans(beans) {
this.filterManager = beans.filterManager;
}
execute(params) {
const isPivotMode2 = this.beans.colModel.isPivotMode();
const isAggFilterActive = this.filterManager?.isAggregateFilterPresent() || this.filterManager?.isAggregateQuickFilterPresent();
const defaultPrimaryColumnPredicate = (params2) => !params2.node.group;
const defaultSecondaryColumnPredicate = (params2) => params2.node.leafGroup;
const applyFilterToNode = (0, import_ag_grid_community125._getGroupAggFiltering)(this.gos) || (isPivotMode2 ? defaultSecondaryColumnPredicate : defaultPrimaryColumnPredicate);
const { changedPath } = params;
const preserveChildren = (node, recursive = false) => {
if (node.childrenAfterFilter) {
node.childrenAfterAggFilter = node.childrenAfterFilter;
if (recursive) {
node.childrenAfterAggFilter.forEach((child) => preserveChildren(child, recursive));
}
this.setAllChildrenCount(node);
}
if (node.sibling) {
node.sibling.childrenAfterAggFilter = node.childrenAfterAggFilter;
}
};
const filterChildren = (node) => {
node.childrenAfterAggFilter = node.childrenAfterFilter?.filter((child) => {
const shouldFilterRow = applyFilterToNode({ node: child });
if (shouldFilterRow) {
const doesNodePassFilter = this.filterManager.doesRowPassAggregateFilters({ rowNode: child });
if (doesNodePassFilter) {
preserveChildren(child, true);
return true;
}
}
const hasChildPassed = child.childrenAfterAggFilter?.length;
return hasChildPassed;
}) || null;
this.setAllChildrenCount(node);
if (node.sibling) {
node.sibling.childrenAfterAggFilter = node.childrenAfterAggFilter;
}
};
changedPath.forEachChangedNodeDepthFirst(isAggFilterActive ? filterChildren : preserveChildren, true);
}
/** for tree data, we include all children, groups and leafs */
setAllChildrenCountTreeData(rowNode) {
const childrenAfterAggFilter = rowNode.childrenAfterAggFilter;
let allChildrenCount = 0;
if (childrenAfterAggFilter) {
const length = childrenAfterAggFilter.length;
allChildrenCount = length;
for (let i = 0; i < length; ++i) {
allChildrenCount += childrenAfterAggFilter[i].allChildrenCount ?? 0;
}
}
rowNode.setAllChildrenCount(
// Maintain the historical behaviour:
// - allChildrenCount is 0 in the root if there are no children
// - allChildrenCount is null in any non-root row if there are no children
allChildrenCount === 0 && rowNode.level >= 0 ? null : allChildrenCount
);
}
/* for grid data, we only count the leafs */
setAllChildrenCountGridGrouping(rowNode) {
let allChildrenCount = 0;
rowNode.childrenAfterAggFilter.forEach((child) => {
if (child.group) {
allChildrenCount += child.allChildrenCount;
} else {
allChildrenCount++;
}
});
rowNode.setAllChildrenCount(allChildrenCount);
}
setAllChildrenCount(rowNode) {
if (!rowNode.hasChildren()) {
rowNode.setAllChildrenCount(null);
return;
}
if (this.gos.get("treeData")) {
this.setAllChildrenCountTreeData(rowNode);
} else {
this.setAllChildrenCountGridGrouping(rowNode);
}
}
};
// packages/ag-grid-enterprise/src/aggregation/footerService.ts
var import_ag_grid_community127 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/aggregation/footerUtils.ts
var import_ag_grid_community126 = require("ag-grid-community");
function _createRowNodeFooter(rowNode, beans) {
if (rowNode.sibling) {
return;
}
const footerNode = (0, import_ag_grid_community126._createRowNodeSibling)(rowNode, beans);
footerNode.footer = true;
footerNode.setRowTop(null);
footerNode.setRowIndex(null);
footerNode.oldRowTop = null;
footerNode.id = "rowGroupFooter_" + rowNode.id;
footerNode.sibling = rowNode;
rowNode.sibling = footerNode;
}
function _destroyRowNodeFooter(rowNode) {
if (!rowNode.sibling) {
return;
}
rowNode.sibling.setRowTop(null);
rowNode.sibling.setRowIndex(null);
rowNode.sibling = void 0;
}
// packages/ag-grid-enterprise/src/aggregation/footerService.ts
var FooterService = class extends import_ag_grid_community127.BeanStub {
constructor() {
super(...arguments);
this.beanName = "footerSvc";
}
addTotalRows(startIndex, node, callback, includeFooterNodes, isRootNode, position) {
let index = startIndex;
if (isRootNode) {
const grandTotal = includeFooterNodes && (0, import_ag_grid_community127._getGrandTotalRow)(this.gos);
if (_positionMatchesGrandTotalRow(position, grandTotal)) {
_createRowNodeFooter(node, this.beans);
callback(node.sibling, index++);
}
return index;
}
const isGroupIncludeFooter = (0, import_ag_grid_community127._getGroupTotalRowCallback)(this.gos);
const groupTotal = includeFooterNodes && isGroupIncludeFooter({ node });
if (groupTotal === position) {
_createRowNodeFooter(node, this.beans);
callback(node.sibling, index++);
}
return index;
}
getTopDisplayIndex(rowsToDisplay, topLevelIndex, childrenAfterSort, getDefaultIndex) {
let adjustedIndex = topLevelIndex;
if (rowsToDisplay[0].footer) {
if (topLevelIndex === 0) {
return 0;
}
adjustedIndex -= 1;
}
const lastRow = rowsToDisplay[rowsToDisplay.length - 1];
const indexOutsideGroupBounds = adjustedIndex >= childrenAfterSort.length;
if (lastRow.footer && indexOutsideGroupBounds) {
return lastRow.rowIndex;
}
return getDefaultIndex(adjustedIndex);
}
doesCellShowTotalPrefix(node, col) {
if (!node.footer || !col?.getColDef().showRowGroup) {
return false;
}
if (this.gos.get("treeData")) {
return true;
}
if (node.level === -1) {
return this.beans.showRowGroupCols?.getShowRowGroupCols()[0] === col;
}
return !!node.rowGroupColumn && col && col.isRowGroupDisplayed(node.rowGroupColumn.getId());
}
applyTotalPrefix(value, formattedValue, node, column) {
const totalValueGetter = column.getColDef().cellRendererParams?.totalValueGetter;
if (totalValueGetter) {
const valueGetterParams = (0, import_ag_grid_community127._addGridCommonParams)(this.gos, { column, node, value, formattedValue });
const getterType = typeof totalValueGetter;
if (getterType === "function") {
return totalValueGetter(valueGetterParams);
}
if (typeof totalValueGetter === "string") {
return this.beans.expressionSvc?.evaluate(totalValueGetter, valueGetterParams);
}
(0, import_ag_grid_community127._warn)(179);
}
if (node.level === -1) {
return this.getLocaleTextFunc()("footerTotal", "Total") + " ";
}
return this.getTotalValue(formattedValue ?? value) ?? "";
}
getTotalValue(value) {
return this.getLocaleTextFunc()("footerTotal", "Total") + " " + (value ?? "");
}
};
function _positionMatchesGrandTotalRow(position, grandTotaRow) {
switch (grandTotaRow) {
case "top":
case "pinnedTop":
return position === "top";
case "bottom":
case "pinnedBottom":
return position === "bottom";
default:
return false;
}
}
// packages/ag-grid-enterprise/src/aggregation/valueColsSvc.ts
var import_ag_grid_community128 = require("ag-grid-community");
var ValueColsSvc = class extends import_ag_grid_community128.BaseColsService {
constructor() {
super(...arguments);
this.beanName = "valueColsSvc";
this.eventName = "columnValueChanged";
this.columnProcessors = {
set: (column, added, source) => this.setValueActive(added, column, source),
add: (column, added, source) => this.setValueActive(true, column, source),
remove: (column, added, source) => this.setValueActive(false, column, source)
};
this.columnExtractors = {
setFlagFunc: (col, flag, source) => this.setColValueActive(col, flag, source),
getIndexFunc: () => void 0,
getInitialIndexFunc: () => void 0,
getValueFunc: (colDef) => {
const aggFunc = colDef.aggFunc;
if (aggFunc === null || aggFunc === "") {
return null;
}
if (aggFunc === void 0) {
return;
}
return !!aggFunc;
},
getInitialValueFunc: (colDef) => {
return colDef.initialAggFunc != null && colDef.initialAggFunc != "";
}
};
this.modifyColumnsNoEventsCallbacks = {
addCol: (column) => this.columns.push(column),
removeCol: (column) => (0, import_ag_grid_community128._removeFromArray)(this.columns, column)
};
}
extractCols(source, oldProvidedCols) {
this.columns = super.extractCols(source, oldProvidedCols);
this.columns.forEach((col) => {
const colDef = col.getColDef();
if (colDef.aggFunc != null && colDef.aggFunc != "") {
this.setColAggFunc(col, colDef.aggFunc);
} else {
if (!col.getAggFunc()) {
this.setColAggFunc(col, colDef.initialAggFunc);
}
}
});
return this.columns;
}
setColumnAggFunc(key, aggFunc, source) {
if (!key) {
return;
}
const column = this.colModel.getColDefCol(key);
if (!column) {
return;
}
this.setColAggFunc(column, aggFunc);
this.dispatchColumnChangedEvent(this.eventSvc, this.eventName, [column], source);
}
syncColumnWithState(column, source, getValue) {
const aggFunc = getValue("aggFunc").value1;
if (aggFunc !== void 0) {
if (typeof aggFunc === "string") {
this.setColAggFunc(column, aggFunc);
if (!column.isValueActive()) {
this.setColValueActive(column, true, source);
this.modifyColumnsNoEventsCallbacks.addCol(column);
}
} else {
if ((0, import_ag_grid_community128._exists)(aggFunc)) {
(0, import_ag_grid_community128._warn)(33);
}
if (column.isValueActive()) {
this.setColValueActive(column, false, source);
this.modifyColumnsNoEventsCallbacks.removeCol(column);
}
}
}
}
setValueActive(active, column, source) {
if (active === column.isValueActive()) {
return;
}
this.setColValueActive(column, active, source);
if (active && !column.getAggFunc() && this.aggFuncSvc) {
const initialAggFunc = this.aggFuncSvc.getDefaultAggFunc(column);
this.setColAggFunc(column, initialAggFunc);
}
}
setColAggFunc(column, aggFunc) {
column.aggFunc = aggFunc;
column.dispatchStateUpdatedEvent("aggFunc");
}
setColValueActive(column, value, source) {
if (column.aggregationActive !== value) {
column.aggregationActive = value;
column.dispatchColEvent("columnValueChanged", source);
}
}
};
// packages/ag-grid-enterprise/src/aggregation/aggregationModule.ts
var SharedAggregationModule = {
moduleName: "SharedAggregation",
version: VERSION,
beans: [AggFuncService, AggColumnNameService, FooterService, ValueColsSvc],
apiFunctions: {
addAggFuncs,
clearAggFuncs,
setColumnAggFunc
},
dependsOn: [EnterpriseCoreModule]
};
var AggregationModule = {
moduleName: "Aggregation",
version: VERSION,
beans: [AggregationStage, FilterAggregatesStage],
rowModels: ["clientSide"],
dependsOn: [SharedAggregationModule]
};
// packages/ag-grid-enterprise/src/pivot/pivotColsSvc.ts
var import_ag_grid_community129 = require("ag-grid-community");
var PivotColsSvc = class extends import_ag_grid_community129.BaseColsService {
constructor() {
super(...arguments);
this.beanName = "pivotColsSvc";
this.eventName = "columnPivotChanged";
this.columnProcessors = {
set: (column, added, source) => this.setColPivotActive(column, added, source),
add: (column, added, source) => this.setColPivotActive(column, true, source),
remove: (column, added, source) => this.setColPivotActive(column, false, source)
};
this.columnOrdering = {
enableProp: "pivot",
initialEnableProp: "initialPivot",
indexProp: "pivotIndex",
initialIndexProp: "initialPivotIndex"
};
this.columnExtractors = {
setFlagFunc: (col, flag, source) => this.setColPivotActive(col, flag, source),
getIndexFunc: (colDef) => colDef.pivotIndex,
getInitialIndexFunc: (colDef) => colDef.initialPivotIndex,
getValueFunc: (colDef) => colDef.pivot,
getInitialValueFunc: (colDef) => colDef.initialPivot
};
this.modifyColumnsNoEventsCallbacks = {
addCol: (column) => this.columns.push(column),
removeCol: (column) => (0, import_ag_grid_community129._removeFromArray)(this.columns, column)
};
}
syncColumnWithState(column, source, getValue, rowIndex) {
const { value1: pivot, value2: pivotIndex } = getValue("pivot", "pivotIndex");
if (pivot !== void 0 || pivotIndex !== void 0) {
if (typeof pivotIndex === "number" || pivot) {
if (!column.isPivotActive()) {
this.setColPivotActive(column, true, source);
this.modifyColumnsNoEventsCallbacks.addCol(column);
}
if (rowIndex && typeof pivotIndex === "number") {
rowIndex[column.getId()] = pivotIndex;
}
} else {
if (column.isPivotActive()) {
this.setColPivotActive(column, false, source);
this.modifyColumnsNoEventsCallbacks.removeCol(column);
}
}
}
}
setColPivotActive(column, pivot, source) {
if (column.pivotActive !== pivot) {
column.pivotActive = pivot;
column.dispatchColEvent("columnPivotChanged", source);
}
column.dispatchStateUpdatedEvent("pivot");
}
};
// packages/ag-grid-enterprise/src/rowGrouping/rowGroupColsSvc.ts
var import_ag_grid_community130 = require("ag-grid-community");
var RowGroupColsSvc = class extends import_ag_grid_community130.BaseColsService {
constructor() {
super(...arguments);
this.beanName = "rowGroupColsSvc";
this.eventName = "columnRowGroupChanged";
this.columnProcessors = {
set: (column, added, source) => this.setActive(added, column, source),
add: (column, added, source) => this.setActive(true, column, source),
remove: (column, added, source) => this.setActive(false, column, source)
};
this.columnOrdering = {
enableProp: "rowGroup",
initialEnableProp: "initialRowGroup",
indexProp: "rowGroupIndex",
initialIndexProp: "initialRowGroupIndex"
};
this.columnExtractors = {
setFlagFunc: (col, flag, source) => this.setColRowGroupActive(col, flag, source),
getIndexFunc: (colDef) => colDef.rowGroupIndex,
getInitialIndexFunc: (colDef) => colDef.initialRowGroupIndex,
getValueFunc: (colDef) => colDef.rowGroup,
getInitialValueFunc: (colDef) => colDef.initialRowGroup
};
this.modifyColumnsNoEventsCallbacks = {
addCol: (column) => this.columns.push(column),
removeCol: (column) => (0, import_ag_grid_community130._removeFromArray)(this.columns, column)
};
}
moveColumn(fromIndex, toIndex, source) {
if (this.columns.length === 0) {
return;
}
const column = this.columns[fromIndex];
const impactedColumns = this.columns.slice(fromIndex, toIndex);
this.columns.splice(fromIndex, 1);
this.columns.splice(toIndex, 0, column);
this.updateIndexMap();
this.eventSvc.dispatchEvent({
type: this.eventName,
columns: impactedColumns,
column: impactedColumns.length === 1 ? impactedColumns[0] : null,
source
});
}
syncColumnWithState(column, source, getValue, rowIndex) {
const { value1: rowGroup, value2: rowGroupIndex } = getValue("rowGroup", "rowGroupIndex");
if (rowGroup !== void 0 || rowGroupIndex !== void 0) {
if (typeof rowGroupIndex === "number" || rowGroup) {
if (!column.isRowGroupActive()) {
this.setColRowGroupActive(column, true, source);
this.modifyColumnsNoEventsCallbacks.addCol(column);
}
if (rowIndex && typeof rowGroupIndex === "number") {
rowIndex[column.getId()] = rowGroupIndex;
}
} else {
if (column.isRowGroupActive()) {
this.setColRowGroupActive(column, false, source);
this.modifyColumnsNoEventsCallbacks.removeCol(column);
}
}
}
}
setActive(active, column, source) {
if (active === column.isRowGroupActive()) {
return;
}
this.setColRowGroupActive(column, active, source);
if ((0, import_ag_grid_community130._shouldUpdateColVisibilityAfterGroup)(this.gos, active)) {
this.colModel.setColsVisible([column], !active, source);
}
}
setColRowGroupActive(column, rowGroup, source) {
if (column.rowGroupActive !== rowGroup) {
column.rowGroupActive = rowGroup;
column.dispatchColEvent("columnRowGroupChanged", source);
}
column.dispatchStateUpdatedEvent("rowGroup");
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/autoColService.ts
var import_ag_grid_community131 = require("ag-grid-community");
var AutoColService = class extends import_ag_grid_community131.BeanStub {
constructor() {
super(...arguments);
this.beanName = "autoColSvc";
}
postConstruct() {
this.addManagedPropertyListener("autoGroupColumnDef", this.updateColumns.bind(this));
}
addColumns(cols) {
if (this.columns == null) {
return;
}
cols.list = this.columns.list.concat(cols.list);
cols.tree = this.columns.tree.concat(cols.tree);
(0, import_ag_grid_community131._updateColsMap)(cols);
}
createColumns(cols, updateOrders) {
const beans = this.beans;
const { colModel, gos, rowGroupColsSvc, colGroupSvc } = beans;
const isPivotMode2 = colModel.isPivotMode();
const groupFullWidthRow = (0, import_ag_grid_community131._isGroupUseEntireRow)(gos, isPivotMode2);
const suppressAutoColumn = isPivotMode2 ? gos.get("pivotSuppressAutoColumn") : this.isSuppressAutoCol();
const rowGroupCols = rowGroupColsSvc?.columns;
const groupingActive = rowGroupCols && rowGroupCols.length > 0 || gos.get("treeData");
const noAutoCols = !groupingActive || suppressAutoColumn || groupFullWidthRow;
const destroyPrevious = () => {
if (this.columns) {
(0, import_ag_grid_community131._destroyColumnTree)(beans, this.columns.tree);
this.columns = null;
}
};
if (noAutoCols) {
destroyPrevious();
return;
}
const list = this.generateAutoCols(rowGroupCols);
const autoColsSame = (0, import_ag_grid_community131._areColIdsEqual)(list, this.columns?.list || null);
const newTreeDepth = cols.treeDepth;
const oldTreeDepth = this.columns ? this.columns.treeDepth : -1;
const treeDepthSame = oldTreeDepth == newTreeDepth;
if (autoColsSame && treeDepthSame) {
return;
}
destroyPrevious();
const treeDepth = colGroupSvc?.findDepth(cols.tree) ?? 0;
const tree = colGroupSvc?.balanceTreeForAutoCols(list, treeDepth) ?? [];
this.columns = {
list,
tree,
treeDepth,
map: {}
};
const putAutoColsFirstInList = (cols2) => {
if (!cols2) {
return null;
}
const colsFiltered = cols2.filter((col) => !(0, import_ag_grid_community131.isColumnGroupAutoCol)(col));
return [...list, ...colsFiltered];
};
updateOrders(putAutoColsFirstInList);
}
updateColumns(event) {
const source = (0, import_ag_grid_community131._convertColumnEventSourceType)(event.source);
this.columns?.list.forEach((col, index) => this.updateOneAutoCol(col, index, source));
}
getColumn(key) {
return this.columns?.list.find((groupCol) => (0, import_ag_grid_community131._columnsMatch)(groupCol, key)) ?? null;
}
getColumns() {
return this.columns?.list ?? null;
}
generateAutoCols(rowGroupCols = []) {
const autoCols = [];
const doingTreeData = this.gos.get("treeData");
let doingMultiAutoColumn = (0, import_ag_grid_community131._isGroupMultiAutoColumn)(this.gos);
if (doingTreeData && doingMultiAutoColumn) {
(0, import_ag_grid_community131._warn)(182);
doingMultiAutoColumn = false;
}
if (doingMultiAutoColumn) {
rowGroupCols.forEach((rowGroupCol, index) => {
autoCols.push(this.createOneAutoCol(rowGroupCol, index));
});
} else {
autoCols.push(this.createOneAutoCol());
}
return autoCols;
}
isSuppressAutoCol() {
const gos = this.gos;
const groupDisplayType = gos.get("groupDisplayType");
const isCustomRowGroups = groupDisplayType === "custom";
if (isCustomRowGroups) {
return true;
}
const treeDataDisplayType = gos.get("treeDataDisplayType");
return treeDataDisplayType === "custom";
}
// rowGroupCol and index are missing if groupDisplayType != "multipleColumns"
createOneAutoCol(rowGroupCol, index) {
let colId;
if (rowGroupCol) {
colId = `${import_ag_grid_community131.GROUP_AUTO_COLUMN_ID}-${rowGroupCol.getId()}`;
} else {
colId = import_ag_grid_community131.GROUP_AUTO_COLUMN_ID;
}
const colDef = this.createAutoColDef(colId, rowGroupCol, index);
colDef.colId = colId;
const newCol = new import_ag_grid_community131.AgColumn(colDef, null, colId, true);
this.createBean(newCol);
return newCol;
}
/**
* Refreshes an auto group col to load changes from defaultColDef or autoGroupColDef
*/
updateOneAutoCol(colToUpdate, index, source) {
const oldColDef = colToUpdate.getColDef();
const underlyingColId = typeof oldColDef.showRowGroup == "string" ? oldColDef.showRowGroup : void 0;
const beans = this.beans;
const underlyingColumn = underlyingColId != null ? beans.colModel.getColDefCol(underlyingColId) : void 0;
const colId = colToUpdate.getId();
const colDef = this.createAutoColDef(colId, underlyingColumn ?? void 0, index);
colToUpdate.setColDef(colDef, null, source);
(0, import_ag_grid_community131._applyColumnState)(beans, { state: [{ colId, ...colDef }] }, source);
}
createAutoColDef(colId, underlyingColumn, index) {
let res = this.createBaseColDef(underlyingColumn);
const autoGroupColumnDef = this.gos.get("autoGroupColumnDef");
(0, import_ag_grid_community131._mergeDeep)(res, autoGroupColumnDef);
res = (0, import_ag_grid_community131._addColumnDefaultAndTypes)(this.beans, res, colId, true);
if (!this.gos.get("treeData")) {
const noFieldOrValueGetter = (0, import_ag_grid_community131._missing)(res.field) && (0, import_ag_grid_community131._missing)(res.valueGetter) && (0, import_ag_grid_community131._missing)(res.filterValueGetter) && res.filter !== "agGroupColumnFilter";
if (noFieldOrValueGetter) {
res.filter = false;
}
}
if (index && index > 0) {
res.headerCheckboxSelection = false;
}
const isSortingCoupled = (0, import_ag_grid_community131._isColumnsSortingCoupledToGroup)(this.gos);
const hasOwnData = res.valueGetter || res.field != null;
if (isSortingCoupled && !hasOwnData) {
res.sortIndex = void 0;
res.initialSort = void 0;
}
return res;
}
createBaseColDef(rowGroupCol) {
const userDef = this.gos.get("autoGroupColumnDef");
const localeTextFunc = this.getLocaleTextFunc();
const res = {
headerName: localeTextFunc("group", "Group"),
showRowGroup: rowGroupCol?.getColId() ?? true
};
const userHasProvidedGroupCellRenderer = userDef && (userDef.cellRenderer || userDef.cellRendererSelector);
if (!userHasProvidedGroupCellRenderer) {
res.cellRenderer = "agGroupCellRenderer";
}
if (rowGroupCol) {
res.headerName = this.beans.colNames.getDisplayNameForColumn(rowGroupCol, "header") ?? void 0;
res.headerValueGetter = rowGroupCol.colDef.headerValueGetter;
}
return res;
}
destroy() {
(0, import_ag_grid_community131._destroyColumnTree)(this.beans, this.columns?.tree);
super.destroy();
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/clientSideExpansionService.ts
var import_ag_grid_community133 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowHierarchy/baseExpansionService.ts
var import_ag_grid_community132 = require("ag-grid-community");
var BaseExpansionService = class extends import_ag_grid_community132.BeanStub {
addExpandedCss(classes, rowNode) {
if (rowNode.isExpandable()) {
classes.push("ag-row-group");
classes.push(rowNode.expanded ? "ag-row-group-expanded" : "ag-row-group-contracted");
}
}
getRowExpandedListeners(rowCtrl) {
const { rowNode } = rowCtrl;
const updateExpandedCss = this.updateExpandedCss.bind(this, rowCtrl, rowNode);
return {
expandedChanged: updateExpandedCss,
hasChildrenChanged: updateExpandedCss
};
}
setExpanded(rowNode, expanded, e, forceSync) {
if (rowNode.expanded === expanded) {
return;
}
rowNode.expanded = expanded;
rowNode.dispatchRowEvent("expandedChanged");
const event = { ...(0, import_ag_grid_community132._createGlobalRowEvent)(rowNode, this.gos, "rowGroupOpened"), expanded, event: e || null };
this.dispatchExpandedEvent(event, forceSync);
}
isExpandable(rowNode) {
if (rowNode.footer) {
return false;
}
if (this.beans.colModel.isPivotMode()) {
return rowNode.hasChildren() && !rowNode.leafGroup;
}
return rowNode.hasChildren() || rowNode.master;
}
updateExpandedCss(rowCtrl, rowNode) {
const expandable = rowNode.isExpandable();
const expanded = rowNode.expanded == true;
rowCtrl.forEachGui(void 0, (gui) => {
const rowComp = gui.rowComp;
rowComp.toggleCss("ag-row-group", expandable);
rowComp.toggleCss("ag-row-group-expanded", expandable && expanded);
rowComp.toggleCss("ag-row-group-contracted", expandable && !expanded);
(0, import_ag_grid_community132._setAriaExpanded)(gui.element, expandable && expanded);
});
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/clientSideExpansionService.ts
var ClientSideExpansionService = class extends BaseExpansionService {
constructor() {
super(...arguments);
this.beanName = "expansionSvc";
this.events = [];
}
wireBeans(beans) {
this.rowModel = beans.rowModel;
}
expandRows(rowIdsToExpand, rowIdsToCollapse) {
const rowIdsToExpandSet = new Set(rowIdsToExpand);
const rowIdsToCollapseSet = rowIdsToCollapse ? new Set(rowIdsToCollapse) : void 0;
this.rowModel.forEachNode((node) => {
const id = node.id;
if (!id) {
return;
}
if (rowIdsToExpandSet.has(id)) {
node.expanded = true;
} else if (rowIdsToCollapseSet?.has(id)) {
node.expanded = false;
}
});
this.onGroupExpandedOrCollapsed();
}
expandAll(expand) {
const { gos, colModel, eventSvc } = this.beans;
const rowModel = this.rowModel;
const usingTreeData = gos.get("treeData");
const usingPivotMode = colModel.isPivotActive();
const recursiveExpandOrCollapse = (rowNodes) => {
if (!rowNodes) {
return;
}
rowNodes.forEach((rowNode) => {
const actionRow = () => {
rowNode.expanded = expand;
recursiveExpandOrCollapse(rowNode.childrenAfterGroup);
};
if (usingTreeData) {
const hasChildren = (0, import_ag_grid_community133._exists)(rowNode.childrenAfterGroup);
if (hasChildren) {
actionRow();
}
return;
}
if (usingPivotMode) {
const notLeafGroup = !rowNode.leafGroup;
if (notLeafGroup) {
actionRow();
}
return;
}
const isRowGroup = rowNode.group;
if (isRowGroup) {
actionRow();
}
});
};
const rootNode = rowModel.rootNode;
if (rootNode) {
recursiveExpandOrCollapse(rootNode.childrenAfterGroup);
}
rowModel.refreshModel({ step: "map" });
eventSvc.dispatchEvent({
type: "expandOrCollapseAll",
source: expand ? "expandAll" : "collapseAll"
});
}
onGroupExpandedOrCollapsed() {
this.rowModel.refreshModel({ step: "map" });
}
// because the user can call rowNode.setExpanded() many times in one VM turn,
// we throttle the calls to ClientSideRowModel using animationFrameSvc. this means for 100
// row nodes getting expanded, we only update the CSRM once, and then we fire all events after
// CSRM has updated.
//
// if we did not do this, then the user could call setExpanded on 100+ rows, causing the grid
// to re-render 100+ times, which would be a performance lag.
//
// we use animationFrameService
// rather than debounce() so this will get done if anyone flushes the animationFrameService
// (eg user calls api.ensureRowVisible(), which in turn flushes ).
dispatchExpandedEvent(event, forceSync) {
this.events.push(event);
const func = () => {
this.rowModel.onRowGroupOpened();
this.events.forEach((e) => this.eventSvc.dispatchEvent(e));
const nodes = this.events.map((e) => e.node);
this.beans.rowRenderer.refreshCells({ rowNodes: nodes });
this.events = [];
};
if (forceSync) {
func();
} else {
if (this.dispatchExpandedDebounced == null) {
this.dispatchExpandedDebounced = this.debounce(func);
}
this.dispatchExpandedDebounced();
}
}
// the advantage over normal debounce is the client can call flushAllFrames()
// to make sure all rendering is complete. we don't wait any milliseconds,
// as this is intended to batch calls in one VM turn.
debounce(func) {
const animationFrameSvc = this.beans.animationFrameSvc;
if (!animationFrameSvc) {
return () => window.setTimeout(func, 0);
}
let pending = false;
return () => {
if (!animationFrameSvc.active) {
window.setTimeout(func, 0);
return;
}
if (pending) {
return;
}
pending = true;
animationFrameSvc.addDestroyTask(() => {
pending = false;
func();
});
};
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/flattenStage.ts
var import_ag_grid_community135 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowHierarchy/flattenUtils.ts
var import_ag_grid_community134 = require("ag-grid-community");
function _getFlattenDetails(gos) {
let groupHideParentOfSingleChild = gos.get("groupHideParentOfSingleChild");
if (!groupHideParentOfSingleChild) {
groupHideParentOfSingleChild = gos.get("groupRemoveSingleChildren");
if (!groupHideParentOfSingleChild && gos.get("groupRemoveLowestSingleChildren")) {
groupHideParentOfSingleChild = "leafGroupsOnly";
}
}
return {
groupHideParentOfSingleChild,
isGroupMultiAutoColumn: (0, import_ag_grid_community134._isGroupMultiAutoColumn)(gos),
hideOpenParents: gos.get("groupHideOpenParents"),
grandTotalRow: (0, import_ag_grid_community134._getGrandTotalRow)(gos),
groupTotalRow: (0, import_ag_grid_community134._getGroupTotalRowCallback)(gos)
};
}
function _isRemovedSingleChildrenGroup(details, rowNode, isParent) {
return details.groupHideParentOfSingleChild === true && isParent && rowNode.childrenAfterGroup.length === 1;
}
function _isRemovedLowestSingleChildrenGroup(details, rowNode, isParent) {
return details.groupHideParentOfSingleChild === "leafGroupsOnly" && isParent && rowNode.leafGroup && rowNode.childrenAfterGroup.length === 1;
}
function _shouldRowBeRendered(details, rowNode, isParent, skipLeafNodes, isRemovedSingleChildrenGroup, isRemovedLowestSingleChildrenGroup) {
const isSkippedLeafNode = skipLeafNodes && !isParent;
const neverAllowToExpand = skipLeafNodes && rowNode.leafGroup;
const isHiddenOpenParent = details.hideOpenParents && rowNode.expanded && !rowNode.master && !neverAllowToExpand;
return !isSkippedLeafNode && !isHiddenOpenParent && !isRemovedSingleChildrenGroup && !isRemovedLowestSingleChildrenGroup;
}
// packages/ag-grid-enterprise/src/rowHierarchy/flattenStage.ts
var FlattenStage = class extends import_ag_grid_community135.BeanStub {
constructor() {
super(...arguments);
this.beanName = "flattenStage";
this.refreshProps = /* @__PURE__ */ new Set([
"groupHideParentOfSingleChild",
"groupRemoveSingleChildren",
"groupRemoveLowestSingleChildren",
"groupTotalRow",
"masterDetail"
]);
this.step = "map";
}
execute(params) {
const rootNode = params.rowNode;
const result = [];
const skipLeafNodes = this.beans.colModel.isPivotMode();
const showRootNode = skipLeafNodes && rootNode.leafGroup && rootNode.aggData;
const topList = showRootNode ? [rootNode] : rootNode.childrenAfterSort;
const details = _getFlattenDetails(this.gos);
this.recursivelyAddToRowsToDisplay(details, topList, result, skipLeafNodes, 0);
const atLeastOneRowPresent = result.length > 0;
const grandTotalRow = details.grandTotalRow;
const includeGrandTotalRow = !showRootNode && // don't show total footer when showRootNode is true (i.e. in pivot mode and no groups)
atLeastOneRowPresent && grandTotalRow;
if (includeGrandTotalRow) {
_createRowNodeFooter(rootNode, this.beans);
if (grandTotalRow === "pinnedBottom" || grandTotalRow === "pinnedTop") {
this.beans.pinnedRowModel?.setGrandTotalPinned(grandTotalRow === "pinnedBottom" ? "bottom" : "top");
} else {
const addToTop = grandTotalRow === "top";
this.addRowNodeToRowsToDisplay(details, rootNode.sibling, result, 0, addToTop);
}
}
return result;
}
recursivelyAddToRowsToDisplay(details, rowsToFlatten, result, skipLeafNodes, uiLevel) {
if (!rowsToFlatten?.length) {
return;
}
const masterDetailSvc = this.beans.masterDetailSvc;
for (let i = 0; i < rowsToFlatten.length; i++) {
const rowNode = rowsToFlatten[i];
const isParent = rowNode.hasChildren();
const isRemovedSingleChildrenGroup = _isRemovedSingleChildrenGroup(details, rowNode, isParent);
const isRemovedLowestSingleChildrenGroup = _isRemovedLowestSingleChildrenGroup(details, rowNode, isParent);
const thisRowShouldBeRendered = _shouldRowBeRendered(
details,
rowNode,
isParent,
skipLeafNodes,
isRemovedSingleChildrenGroup,
isRemovedLowestSingleChildrenGroup
);
if (thisRowShouldBeRendered) {
this.addRowNodeToRowsToDisplay(details, rowNode, result, uiLevel);
}
if (skipLeafNodes && rowNode.leafGroup) {
continue;
}
if (isParent) {
const excludedParent = isRemovedSingleChildrenGroup || isRemovedLowestSingleChildrenGroup;
if (rowNode.expanded || excludedParent) {
const doesRowShowFooter = details.groupTotalRow({ node: rowNode });
if (!doesRowShowFooter) {
_destroyRowNodeFooter(rowNode);
}
const uiLevelForChildren = excludedParent ? uiLevel : uiLevel + 1;
if (doesRowShowFooter === "top") {
_createRowNodeFooter(rowNode, this.beans);
this.addRowNodeToRowsToDisplay(details, rowNode.sibling, result, uiLevelForChildren);
}
const detailNode = masterDetailSvc?.getDetail(rowNode);
if (detailNode) {
this.addRowNodeToRowsToDisplay(details, detailNode, result, uiLevel);
}
this.recursivelyAddToRowsToDisplay(
details,
rowNode.childrenAfterSort,
result,
skipLeafNodes,
uiLevelForChildren
);
if (doesRowShowFooter === "bottom") {
_createRowNodeFooter(rowNode, this.beans);
this.addRowNodeToRowsToDisplay(details, rowNode.sibling, result, uiLevelForChildren);
}
}
} else {
const detailNode = masterDetailSvc?.getDetail(rowNode);
if (detailNode) {
this.addRowNodeToRowsToDisplay(details, detailNode, result, uiLevel);
}
}
}
}
// duplicated method, it's also in floatingRowModel
addRowNodeToRowsToDisplay(details, rowNode, result, uiLevel, addToTop) {
if (addToTop) {
result.unshift(rowNode);
} else {
result.push(rowNode);
}
rowNode.setUiLevel(details.isGroupMultiAutoColumn ? 0 : uiLevel);
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/groupStage.ts
var import_ag_grid_community136 = require("ag-grid-community");
var GroupStage = class extends import_ag_grid_community136.BeanStub {
constructor() {
super(...arguments);
this.beanName = "groupStage";
this.refreshProps = /* @__PURE__ */ new Set([
"groupDefaultExpanded",
"groupAllowUnbalanced",
"initialGroupOrderComparator",
"groupHideOpenParents",
"groupDisplayType",
"treeData",
"treeDataChildrenField",
"treeDataParentIdField"
]);
this.step = "group";
this.approach = null;
this.strategyBeanName = null;
this.strategy = void 0;
}
/** Gets a filler row by id */
getNode(id) {
return this.strategy?.getNode(id);
}
destroy() {
super.destroy();
this.strategy = void 0;
}
execute(params) {
const approach = (0, import_ag_grid_community136._getGroupingApproach)(this.gos);
const approachChanged = this.approach !== approach;
const strategy = approachChanged ? this.changeApproach(params, approach) : this.strategy;
if (!strategy) {
return void 0;
}
return strategy.execute(params, approach) || approachChanged;
}
getStrategyBeanName(approach) {
switch (approach) {
case "group":
return "groupStrategy";
case "treePath":
case "treeNested":
case "treeSelfRef":
return "treeGroupStrategy";
default:
return null;
}
}
changeApproach({ rowNode }, approach) {
this.approach = approach;
const newBeanName = this.getStrategyBeanName(approach);
const oldStrategy = this.strategy;
let strategy = oldStrategy;
if (this.strategyBeanName !== newBeanName) {
this.destroyBean(strategy);
strategy = void 0;
if (newBeanName) {
strategy = this.beans.registry.createDynamicBean(newBeanName, false);
this.createOptionalManagedBean(strategy);
}
this.strategy = strategy;
this.strategyBeanName = newBeanName;
} else {
strategy?.reset?.();
}
if (oldStrategy) {
resetGrouping(rowNode, approach !== "treeNested");
}
return strategy;
}
};
var resetGrouping = (rootNode, canResetTreeNode) => {
const allLeafChildren = rootNode.allLeafChildren;
const rootSibling = rootNode.sibling;
rootNode.treeNodeFlags = 0;
rootNode.childrenAfterGroup = allLeafChildren;
rootNode.childrenMapped = null;
rootNode.groupData = null;
if (rootSibling) {
rootSibling.childrenAfterGroup = rootNode.childrenAfterGroup;
rootSibling.childrenAfterAggFilter = rootNode.childrenAfterAggFilter;
rootSibling.childrenAfterFilter = rootNode.childrenAfterFilter;
rootSibling.childrenAfterSort = rootNode.childrenAfterSort;
rootSibling.childrenMapped = null;
}
for (const row of allLeafChildren) {
const sibling = row.sibling;
resetChildRowGrouping(row);
if (sibling) {
resetChildRowGrouping(sibling);
}
row.parent = rootNode;
if (canResetTreeNode) {
row.treeParent = null;
}
if (row.group || row.hasChildren()) {
row.group = false;
row.updateHasChildren();
}
}
rootNode.updateHasChildren();
};
var resetChildRowGrouping = (row) => {
row.key = null;
row.treeNodeFlags = 0;
row.allChildrenCount = null;
row.allLeafChildren = null;
row.childrenAfterGroup = null;
row.childrenAfterAggFilter = null;
row.childrenAfterFilter = null;
row.childrenAfterSort = null;
row.childrenMapped = null;
row.level = 0;
if (row.groupData) {
row.groupData = null;
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/rendering/groupCellRenderer.ts
var import_ag_grid_community138 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowHierarchy/rendering/groupCellRendererCtrl.ts
var import_ag_grid_community137 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowHierarchy/rowHierarchyUtils.ts
function _isHiddenParent(node, ancestor, gos) {
let currentNode = node;
const levelDiff = currentNode.level - ancestor.level;
if (levelDiff <= 0) {
return false;
}
const isHideOpenParents = gos.get("groupHideOpenParents");
if (!isHideOpenParents) {
return false;
}
for (let i = 0; i < levelDiff; i++) {
const isFirstChild = currentNode.parent?.getFirstChild() === currentNode;
if (!isFirstChild) {
return false;
}
currentNode = currentNode.parent;
}
return currentNode === ancestor;
}
var _getRowDefaultExpanded = (beans, rowNode, level, group = rowNode.group) => {
const gos = beans.gos;
const isGroupOpenByDefault = group && gos.get("isGroupOpenByDefault");
if (!isGroupOpenByDefault) {
const groupDefaultExpanded = gos.get("groupDefaultExpanded");
return groupDefaultExpanded === -1 || level < groupDefaultExpanded;
}
const params = {
api: beans.gridApi,
context: beans.gridOptions.context,
rowNode,
field: rowNode.field,
key: rowNode.key,
level,
rowGroupColumn: rowNode.rowGroupColumn
};
return isGroupOpenByDefault(params) == true;
};
// packages/ag-grid-enterprise/src/rowHierarchy/rendering/groupCellRendererCtrl.ts
var GroupCellRendererCtrl = class extends import_ag_grid_community137.BeanStub {
constructor() {
super(...arguments);
// keep reference to this, so we can remove again when indent changes
this.indentClass = null;
}
init(comp, eGui, eCheckbox, eExpanded, eContracted, compClass, params) {
this.params = params;
this.eGui = eGui;
this.eCheckbox = eCheckbox;
this.eExpanded = eExpanded;
this.eContracted = eContracted;
this.comp = comp;
this.compClass = compClass;
const { node, column } = params;
this.node = node;
this.displayedNode = node;
const embeddedRowMismatch = this.isEmbeddedRowMismatch();
if (embeddedRowMismatch) {
return;
}
if (node.footer) {
this.initFooterCell();
return;
}
if (!column) {
this.initFullWidthCell();
return;
}
this.displayedNode = this.beans.showRowGroupColValueSvc?.getDisplayedNode(node, column) ?? this.node;
this.setupExpand();
this.setupCheckbox();
this.addGroupValue();
this.setupIndent();
}
initFooterCell() {
const { node } = this.params;
this.addGroupValue();
this.setupIndent();
const isGrandTotal = node.level === -1;
if (!isGrandTotal) {
this.comp.toggleCss("ag-row-group-leaf-indent", true);
}
}
initFullWidthCell() {
const setupDragger = () => {
const { rowDragSvc } = this.beans;
if (!this.params.rowDrag || !rowDragSvc) {
return;
}
const rowDragComp = rowDragSvc.createRowDragComp(() => this.params.value, this.params.node);
this.createManagedBean(rowDragComp);
this.eGui.insertAdjacentElement("afterbegin", rowDragComp.getGui());
};
this.setupExpand();
setupDragger();
this.setupCheckbox();
this.addGroupValue();
this.setupIndent();
}
/**
* Returns an aria "role" to place on full width group cells, or the parent wrapper.
* @returns the aria role to place on the parent wrapper
*/
getCellAriaRole() {
const colDefAriaRole = this.params.colDef?.cellAriaRole;
const columnColDefAriaRole = this.params.column?.getColDef().cellAriaRole;
return colDefAriaRole || columnColDefAriaRole || "gridcell";
}
/**
* Determines if this cell should be rendered, as when using embeddedFullWidthRows
* only one group cell should be rendered.
*
* if [enableRTL] all but pinned right cells should be skipped if available
* otherwise prioritise pinned left cell if available
* otherwise center viewport.
*
* @returns whether the cell should be skipped due to embedded full width rows
*/
isEmbeddedRowMismatch() {
if (!this.params.fullWidth || !this.gos.get("embedFullWidthRows")) {
return false;
}
const { visibleCols } = this.beans;
const pinnedLeftCell = this.params.pinned === "left";
const pinnedRightCell = this.params.pinned === "right";
const bodyCell = !pinnedLeftCell && !pinnedRightCell;
if (this.gos.get("enableRtl")) {
if (visibleCols.isPinningLeft()) {
return !pinnedRightCell;
}
return !bodyCell;
}
if (visibleCols.isPinningLeft()) {
return !pinnedLeftCell;
}
return !bodyCell;
}
/**
* Displays the group value for the displayed node
*/
addGroupValue() {
const {
params: { value, valueFormatted }
} = this;
const innerCompDetails = this.getInnerCompDetails();
this.comp.setInnerRenderer(innerCompDetails, valueFormatted ?? value ?? null);
}
/**
* Sets up expand/collapse:
* Chevron
* Aria-expanded
* Child count
*/
setupExpand() {
const { colModel } = this.beans;
const { eGridCell, column, suppressDoubleClickExpand } = this.params;
const addIconToDom = (iconName, element) => {
const icon = (0, import_ag_grid_community137._createIconNoSpan)(iconName, this.beans, null);
if (icon) {
element.appendChild(icon);
this.addDestroyFunc(() => element.removeChild(icon));
}
};
addIconToDom("groupExpanded", this.eExpanded);
addIconToDom("groupContracted", this.eContracted);
const comp = this.comp;
const onExpandedChanged = () => {
const expandable = this.isExpandable();
if (!expandable) {
return;
}
const expanded = this.displayedNode.expanded;
comp.setExpandedDisplayed(expanded);
comp.setContractedDisplayed(!expanded);
(0, import_ag_grid_community137._setAriaExpanded)(eGridCell, !!this.displayedNode.expanded);
};
const onExpandableChanged = () => {
const expandable = this.isExpandable();
comp.toggleCss("ag-cell-expandable", expandable);
comp.toggleCss("ag-row-group", expandable);
const pivotModeAndLeaf = !expandable && colModel.isPivotMode();
comp.toggleCss("ag-pivot-leaf-group", pivotModeAndLeaf);
const normalModeNotTotalFooter = !colModel.isPivotMode() && (!this.displayedNode.footer || this.displayedNode.level !== -1);
comp.toggleCss("ag-row-group-leaf-indent", !expandable && normalModeNotTotalFooter);
const count = this.getChildCount();
const countString = count > 0 ? `(${count})` : ``;
comp.setChildCount(countString);
if (!expandable) {
comp.setExpandedDisplayed(false);
comp.setContractedDisplayed(false);
(0, import_ag_grid_community137._removeAriaExpanded)(eGridCell);
} else {
onExpandedChanged();
}
};
const setupListeners = () => {
const isDoubleClickEdit = column?.isCellEditable(this.displayedNode) && this.gos.get("enableGroupEdit");
if (!isDoubleClickEdit && !suppressDoubleClickExpand) {
this.addManagedListeners(eGridCell, { dblclick: this.onCellDblClicked.bind(this) });
}
this.addManagedListeners(this.eExpanded, { click: this.onExpandClicked.bind(this) });
this.addManagedListeners(this.eContracted, { click: this.onExpandClicked.bind(this) });
this.addManagedListeners(eGridCell, { keydown: this.onKeyDown.bind(this) });
this.addManagedListeners(this.displayedNode, {
// Expandable state has changed
allChildrenCountChanged: onExpandableChanged,
masterChanged: onExpandableChanged,
groupChanged: onExpandableChanged,
hasChildrenChanged: onExpandableChanged,
// Node expanded changed
expandedChanged: onExpandedChanged
});
};
setupListeners();
onExpandableChanged();
}
/**
* Return the inner renderer details for the cell
*
* Prioritises:
* 1. Group row renderer for group rows
* 2. agFindCellRenderer for find results in group rows
* 3. Provided innerRenderer (i.e, cellRendererParams.innerRenderer)
* 4. Cell renderer of the grouped column
* 5. Inner renderer of the grouped column
* 6. agFindCellRenderer for find results
*/
getInnerCompDetails() {
const { userCompFactory, findSvc } = this.beans;
const params = this.params;
if (params.fullWidth) {
const groupRowRendererParams = this.gos.get("groupRowRendererParams");
const groupRowInnerCompDetails = (0, import_ag_grid_community137._getInnerCellRendererDetails)(
userCompFactory,
groupRowRendererParams,
params
);
if (groupRowInnerCompDetails) {
return groupRowInnerCompDetails;
}
if (findSvc?.isMatch(params.node, null)) {
return (0, import_ag_grid_community137._getInnerCellRendererDetails)(
userCompFactory,
{ ...groupRowRendererParams, innerRenderer: "agFindCellRenderer" },
params
);
}
return void 0;
}
const isGroupRowRenderer = (details) => details && details.componentClass == this.compClass;
const innerCompDetails = (0, import_ag_grid_community137._getInnerCellRendererDetails)(userCompFactory, params, params);
if (innerCompDetails && !isGroupRowRenderer(innerCompDetails)) {
return innerCompDetails;
}
const {
displayedNode: { rowGroupColumn }
} = this;
const relatedColDef = rowGroupColumn?.colDef;
const isShowingThisCol = rowGroupColumn && params.column?.isRowGroupDisplayed(rowGroupColumn.getId());
if (relatedColDef && isShowingThisCol) {
const relatedCompDetails = (0, import_ag_grid_community137._getCellRendererDetails)(userCompFactory, relatedColDef, params);
if (relatedCompDetails) {
if (isGroupRowRenderer(relatedCompDetails)) {
if (relatedColDef?.cellRendererParams?.innerRenderer) {
return (0, import_ag_grid_community137._getInnerCellRendererDetails)(
userCompFactory,
relatedColDef.cellRendererParams,
params
);
}
} else {
return relatedCompDetails;
}
}
}
if (findSvc?.isMatch(params.node, params.column)) {
return (0, import_ag_grid_community137._getCellRendererDetails)(
userCompFactory,
{ ...relatedColDef ?? params.colDef, cellRenderer: "agFindCellRenderer" },
params
);
}
}
/**
* Get the allChildCount of a given node
* @param node the node to return the count for
* @returns 0 if the count should not be displayed, otherwise the count
*/
getChildCount() {
const { column, suppressCount } = this.params;
if (suppressCount) {
return 0;
}
const { allChildrenCount, rowGroupColumn } = this.displayedNode;
const isDisplayingRowGroupCell = (allChildrenCount ?? 0) > 0 && (!rowGroupColumn || !column || column?.isRowGroupDisplayed(rowGroupColumn.getId()));
if (!isDisplayingRowGroupCell) {
return 0;
}
const isRepresentingOtherNode = this.gos.get("showOpenedGroup") && this.displayedNode !== this.node;
if (isRepresentingOtherNode && !_isHiddenParent(this.node, this.displayedNode, this.gos)) {
return 0;
}
return allChildrenCount ?? 0;
}
/**
* Checks whether the current cell is expandable, either due to [groupHideOpenParent] control or otherwise.
* @returns whether this cell is expandable
*/
isExpandable() {
const { node, column, colDef } = this.params;
if (!this.displayedNode.isExpandable()) {
return false;
}
if (node.rowPinned) {
return false;
}
const isFullWidth = !column;
if (isFullWidth) {
return true;
}
const hasChildren = node.hasChildren();
if (hasChildren && colDef) {
const { showRowGroup } = colDef;
if (!showRowGroup) {
return false;
}
if (showRowGroup === true) {
return true;
}
}
if (node === this.displayedNode) {
if (node.rowGroupColumn) {
const showingThisRowGroup = column?.isRowGroupDisplayed(node.rowGroupColumn.getId());
if (showingThisRowGroup) {
return true;
}
}
if (node.master) {
return colDef?.showRowGroup === true || colDef?.showRowGroup == null;
}
return false;
}
return _isHiddenParent(this.node, this.displayedNode, this.gos);
}
/**
* For full width group cells & single group column, indents child groups based on uiLevel
*/
setupIndent() {
const { suppressPadding, node, colDef } = this.params;
if (suppressPadding) {
return;
}
const setIndent = () => {
let level = 0;
if (colDef && colDef.showRowGroup !== true) {
level = 0;
} else {
level = node.uiLevel;
}
const newIndentClass = "ag-row-group-indent-" + level;
if (newIndentClass === this.indentClass) {
return;
}
if (this.indentClass) {
this.comp.toggleCss(this.indentClass, false);
}
this.indentClass = newIndentClass;
this.comp.toggleCss(newIndentClass, true);
this.eGui.style.setProperty("--ag-indentation-level", String(level));
};
this.addManagedListeners(node, { uiLevelChanged: setIndent.bind(this) });
setIndent();
}
/**
* Selection checkboxes
*/
setupCheckbox() {
const { node } = this.params;
const isRowSelectable = !node.footer && !node.rowPinned && !node.detail;
if (!isRowSelectable) {
return;
}
this.addManagedPropertyListener("rowSelection", ({ currentValue, previousValue }) => {
const curr = typeof currentValue === "object" ? currentValue : void 0;
const prev = typeof previousValue === "object" ? previousValue : void 0;
if (curr?.checkboxLocation !== prev?.checkboxLocation) {
this.destroyCheckbox();
this.addCheckbox();
}
});
this.addCheckbox();
}
addCheckbox() {
const { selectionSvc } = this.beans;
if (!selectionSvc || !(0, import_ag_grid_community137._isRowSelection)(this.gos)) {
return;
}
const { node, column } = this.params;
const rowSelection = this.gos.get("rowSelection");
const checkboxLocation = (0, import_ag_grid_community137._getCheckboxLocation)(rowSelection);
if (checkboxLocation === "selectionColumn") {
return;
}
if (checkboxLocation === "autoGroupColumn") {
const isGroupColumn = column?.getColDef().showRowGroup != null;
const isFullWidthGroupRow = !column && node.group;
const isApplicableCell = isGroupColumn || isFullWidthGroupRow;
if (!isApplicableCell) {
return;
}
}
const checkboxes = typeof rowSelection === "object" ? (0, import_ag_grid_community137._getCheckboxes)(rowSelection) : this.params.checkbox;
const userWantsCheckboxes = typeof checkboxes === "function" || checkboxes === true;
if (!userWantsCheckboxes) {
return;
}
const isMultiAutoCol = typeof column?.getColDef().showRowGroup === "string";
if (isMultiAutoCol && !this.isExpandable()) {
this.comp.setCheckboxSpacing(true);
return;
}
const cbSelectionComponent = selectionSvc.createCheckboxSelectionComponent();
this.cbComp = cbSelectionComponent;
this.createBean(cbSelectionComponent);
cbSelectionComponent.init({
rowNode: node,
// when groupHideOpenParents = true and group expanded, we want the checkbox to refer to leaf node state (not group node state)
column,
overrides: {
isVisible: checkboxes,
callbackParams: this.params,
removeHidden: true
}
});
this.eCheckbox.appendChild(cbSelectionComponent.getGui());
this.comp.setCheckboxVisible(true);
}
destroyCheckbox() {
this.comp.setCheckboxSpacing(false);
this.comp.setCheckboxVisible(false);
this.cbComp && this.eCheckbox.removeChild(this.cbComp.getGui());
this.cbComp = this.destroyBean(this.cbComp);
}
/**
* Called when the expand / contract icon is clicked.
*/
onExpandClicked(mouseEvent) {
if ((0, import_ag_grid_community137._isStopPropagationForAgGrid)(mouseEvent)) {
return;
}
(0, import_ag_grid_community137._stopPropagationForAgGrid)(mouseEvent);
this.onExpandOrContract(mouseEvent);
}
/**
* Called on cell key press - only handles 'Enter' key for expand/collapse
*/
onKeyDown(event) {
const isEnterKey = event.key === import_ag_grid_community137.KeyCode.ENTER;
if (!isEnterKey || this.params.suppressEnterExpand) {
return;
}
const cellEditable = this.params.column && this.params.column.isCellEditable(this.params.node);
if (cellEditable) {
return;
}
this.onExpandOrContract(event);
}
/**
* Called on cell double click - only expands/collapses if the event is not on the expand / contract icon
*/
onCellDblClicked(mouseEvent) {
if ((0, import_ag_grid_community137._isStopPropagationForAgGrid)(mouseEvent)) {
return;
}
const targetIsExpandIcon = (0, import_ag_grid_community137._isElementInEventPath)(this.eExpanded, mouseEvent) || (0, import_ag_grid_community137._isElementInEventPath)(this.eContracted, mouseEvent);
if (!targetIsExpandIcon) {
this.onExpandOrContract(mouseEvent);
}
}
/**
* Called when expand or contract is attempted, to scroll the row and update the node state
* @param e originating event
*/
onExpandOrContract(e) {
if (!this.isExpandable()) {
return;
}
const rowNode = this.displayedNode;
const nextExpandState = !rowNode.expanded;
if (!nextExpandState && rowNode.sticky) {
this.beans.ctrlsSvc.getScrollFeature().setVerticalScrollPosition(rowNode.rowTop - rowNode.stickyRowTop);
}
rowNode.setExpanded(nextExpandState, e);
}
destroy() {
super.destroy();
this.destroyCheckbox();
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/rendering/groupCellRenderer.ts
var GroupCellRendererElement = {
tag: "span",
cls: "ag-cell-wrapper",
children: [
{ tag: "span", ref: "eExpanded", cls: "ag-group-expanded ag-hidden" },
{ tag: "span", ref: "eContracted", cls: "ag-group-contracted ag-hidden" },
{ tag: "span", ref: "eCheckbox", cls: "ag-group-checkbox ag-invisible" },
{ tag: "span", ref: "eValue", cls: "ag-group-value" },
{ tag: "span", ref: "eChildCount", cls: "ag-group-child-count" }
]
};
var GroupCellRenderer = class extends import_ag_grid_community138.Component {
constructor() {
super(GroupCellRendererElement);
this.eExpanded = import_ag_grid_community138.RefPlaceholder;
this.eContracted = import_ag_grid_community138.RefPlaceholder;
this.eCheckbox = import_ag_grid_community138.RefPlaceholder;
this.eValue = import_ag_grid_community138.RefPlaceholder;
this.eChildCount = import_ag_grid_community138.RefPlaceholder;
}
init(params) {
const compProxy = {
setInnerRenderer: (compDetails, valueToDisplay) => this.setRenderDetails(compDetails, valueToDisplay),
setChildCount: (count) => this.eChildCount.textContent = count,
toggleCss: (cssClass, value) => this.toggleCss(cssClass, value),
setContractedDisplayed: (expanded) => (0, import_ag_grid_community138._setDisplayed)(this.eContracted, expanded),
setExpandedDisplayed: (expanded) => (0, import_ag_grid_community138._setDisplayed)(this.eExpanded, expanded),
setCheckboxVisible: (visible) => this.eCheckbox.classList.toggle("ag-invisible", !visible),
setCheckboxSpacing: (add) => this.eCheckbox.classList.toggle("ag-group-checkbox-spacing", add)
};
const ctrl = this.createManagedBean(new GroupCellRendererCtrl());
const fullWidth = !params.colDef;
const eGui = this.getGui();
ctrl.init(compProxy, eGui, this.eCheckbox, this.eExpanded, this.eContracted, this.constructor, params);
if (fullWidth) {
(0, import_ag_grid_community138._setAriaRole)(eGui, ctrl.getCellAriaRole());
}
}
setRenderDetails(compDetails, valueToDisplay) {
if (compDetails) {
compDetails.newAgStackInstance().then((comp) => {
if (!comp) {
return;
}
const destroyComp = () => this.destroyBean(comp);
if (this.isAlive()) {
this.eValue.appendChild(comp.getGui());
this.addDestroyFunc(destroyComp);
} else {
destroyComp();
}
});
} else {
this.eValue.innerText = valueToDisplay;
}
}
destroy() {
this.destroyBean(this.innerCellRenderer);
super.destroy();
}
refresh() {
return false;
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/rendering/groupCellStyles.css-GENERATED.ts
var groupCellStylesCSS = (
/*css*/
`.ag-group-checkbox-spacing{width:var(--ag-icon-size)}:where(.ag-ltr) .ag-group-checkbox-spacing{margin-right:var(--ag-cell-widget-spacing)}:where(.ag-rtl) .ag-group-checkbox-spacing{margin-left:var(--ag-cell-widget-spacing)}`
);
// packages/ag-grid-enterprise/src/rowHierarchy/showRowGroupColValueService.ts
var import_ag_grid_community139 = require("ag-grid-community");
var ShowRowGroupColValueService = class extends import_ag_grid_community139.BeanStub {
constructor() {
super(...arguments);
this.beanName = "showRowGroupColValueSvc";
}
/**
* Get the value for format in the group column, also returns the displayedNode from which the value was
* taken in cases of groupHideOpenParents and showOpenedGroup.
*/
getGroupValue(node, column) {
if (!column) {
if (!node.group) {
return null;
}
return { displayedNode: node, value: node.groupValue };
}
const valueSvc = this.beans.valueSvc;
const rowGroupColId = column.colDef.showRowGroup;
if (!rowGroupColId) {
return null;
}
if (node.level === -1 && node.footer) {
return { displayedNode: node, value: null };
}
if (typeof rowGroupColId === "string") {
const colRowGroupIndex = this.beans.rowGroupColsSvc?.getColumnIndex(rowGroupColId) ?? -1;
if (colRowGroupIndex > node.level) {
return null;
}
const hideOpenParentsNode = this.getDisplayedNode(node, column, true);
if (hideOpenParentsNode) {
return {
displayedNode: hideOpenParentsNode,
value: valueSvc.getValue(column, hideOpenParentsNode)
};
}
}
const value = valueSvc.getValue(column, node);
if (value == null) {
const displayedNode = this.getDisplayedNode(node, column);
if (displayedNode) {
return {
displayedNode,
value: valueSvc.getValue(column, displayedNode)
};
}
}
return {
displayedNode: node,
value
};
}
/**
* Formats a group col value, and prefixes it with the "Total" prefix if applicable
*/
formatAndPrefixGroupColValue(groupValue, column, exporting = false) {
const formattedValue = this.formatGroupColValue(groupValue, column, exporting);
const { value, displayedNode } = groupValue;
const footerSvc = this.beans.footerSvc;
if (footerSvc?.doesCellShowTotalPrefix(displayedNode, column)) {
const footerValue = footerSvc.applyTotalPrefix(value, formattedValue, displayedNode, column);
return footerValue;
}
if (displayedNode.footer && displayedNode.level === -1) {
return null;
}
return formattedValue;
}
/**
* Formats the group col value using the underlying column's value formatter
*/
formatGroupColValue(groupValue, column, exporting = false) {
const valueSvc = this.beans.valueSvc;
const { displayedNode, value } = groupValue;
const groupedCol = displayedNode.rowGroupColumn;
const isFullWidthGroup = displayedNode.group && !column;
const isShowingGroupCell = groupedCol && (isFullWidthGroup || column?.isRowGroupDisplayed(groupedCol.colId));
if (isShowingGroupCell) {
if (exporting && groupedCol.colDef.useValueFormatterForExport === false) {
return null;
}
const formattedValue = valueSvc.formatValue(groupedCol, displayedNode, value);
if (formattedValue == null && displayedNode.key === "") {
const localeTextFunc = this.getLocaleTextFunc();
return localeTextFunc("blanks", "(Blanks)");
}
return formattedValue;
}
if (!column || displayedNode.group) {
return null;
}
if (exporting && column.colDef.useValueFormatterForExport === false) {
return null;
}
return valueSvc.formatValue(column, displayedNode, value);
}
/**
* Checks if the node has a value to inherit from the parent node for display in the given column
*
* This is used when [groupHideOpenParents] or [showOpenedGroup] are enabled
*
* @param node node to check for preferential nodes to display
* @param column column to get the displayed node for
* @returns a parent node of node to display the value from, or undefined if no value will be inherited
*/
getDisplayedNode(node, column, onlyHideOpenParents = false) {
const gos = this.gos;
const isGroupHideOpenParents = gos.get("groupHideOpenParents");
const isShowOpenedGroupValue = gos.get("showOpenedGroup") && !onlyHideOpenParents;
if (!isGroupHideOpenParents && !isShowOpenedGroupValue) {
return void 0;
}
const showRowGroup = column.colDef.showRowGroup;
if (showRowGroup === true) {
if (node.group) {
return void 0;
}
return node.parent ?? void 0;
}
let pointer = node;
while (pointer && pointer.rowGroupColumn?.getId() != showRowGroup) {
const isFirstChild = pointer === pointer.parent?.getFirstChild();
if (!isShowOpenedGroupValue && !isFirstChild) {
return void 0;
}
pointer = pointer.parent;
}
if (pointer === node) {
return void 0;
}
return pointer ?? void 0;
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/showRowGroupColsService.ts
var import_ag_grid_community140 = require("ag-grid-community");
var ShowRowGroupColsService = class extends import_ag_grid_community140.BeanStub {
constructor() {
super(...arguments);
this.beanName = "showRowGroupCols";
}
refresh() {
this.showRowGroupCols = [];
this.showRowGroupColsMap = {};
const { colModel, rowGroupColsSvc } = this.beans;
colModel.getCols().forEach((col) => {
const colDef = col.getColDef();
const showRowGroup = colDef.showRowGroup;
const isString2 = typeof showRowGroup === "string";
const isTrue = showRowGroup === true;
if (!isString2 && !isTrue) {
return;
}
this.showRowGroupCols.push(col);
if (isString2) {
this.showRowGroupColsMap[showRowGroup] = col;
} else if (rowGroupColsSvc) {
rowGroupColsSvc.columns.forEach((rowGroupCol) => {
this.showRowGroupColsMap[rowGroupCol.getId()] = col;
});
}
});
}
getShowRowGroupCols() {
return this.showRowGroupCols;
}
getShowRowGroupCol(id) {
return this.showRowGroupColsMap[id];
}
getSourceColumnsForGroupColumn(groupCol) {
const sourceColumnId = groupCol.getColDef().showRowGroup;
if (!sourceColumnId) {
return null;
}
const { rowGroupColsSvc, colModel } = this.beans;
if (sourceColumnId === true && rowGroupColsSvc) {
return rowGroupColsSvc.columns.slice(0);
}
const column = colModel.getColDefCol(sourceColumnId);
return column ? [column] : null;
}
isRowGroupDisplayed(column, colId) {
const { colDef } = column;
if (colDef?.showRowGroup == null) {
return false;
}
const showingAllGroups = colDef.showRowGroup === true;
const showingThisGroup = colDef.showRowGroup === colId;
return showingAllGroups || showingThisGroup;
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/stickyRowService.ts
var import_ag_grid_community142 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowHierarchy/stickyRowFeature.ts
var import_ag_grid_community141 = require("ag-grid-community");
var StickyRowFeature = class extends import_ag_grid_community141.BeanStub {
constructor(createRowCon, destroyRowCtrls) {
super();
this.createRowCon = createRowCon;
this.destroyRowCtrls = destroyRowCtrls;
this.stickyTopRowCtrls = [];
this.stickyBottomRowCtrls = [];
// sticky rows pulls in extra rows from other pages which impacts row position
this.extraTopHeight = 0;
this.extraBottomHeight = 0;
}
postConstruct() {
this.isClientSide = (0, import_ag_grid_community141._isClientSideRowModel)(this.gos);
this.beans.ctrlsSvc.whenReady(this, (params) => {
this.gridBodyCtrl = params.gridBodyCtrl;
});
this.resetStickyContainers();
}
setOffsetTop(offset) {
if (this.extraTopHeight === offset) {
return;
}
this.extraTopHeight = offset;
this.eventSvc.dispatchEvent({
type: "stickyTopOffsetChanged",
offset
});
}
setOffsetBottom(offset) {
if (this.extraBottomHeight === offset) {
return;
}
this.extraBottomHeight = offset;
}
resetOffsets() {
this.setOffsetBottom(0);
this.setOffsetTop(0);
}
/**
* Get the last pixel of the group, this pixel is used to push the sticky node up out of the viewport.
*/
getLastPixelOfGroup(row) {
return this.isClientSide ? getClientSideLastPixelOfGroup(row) : getServerSideLastPixelOfGroup(row);
}
/**
* Get the first pixel of the group, this pixel is used to push the sticky node down out of the viewport
*/
getFirstPixelOfGroup(row) {
if (row.footer) {
return row.sibling.rowTop + row.sibling.rowHeight - 1;
}
if (row.hasChildren()) {
return row.rowTop - 1;
}
return 0;
}
updateStickyRows(container) {
const isTop = container === "top";
let newStickyContainerHeight = 0;
if (!this.canRowsBeSticky()) {
return this.refreshNodesAndContainerHeight(container, /* @__PURE__ */ new Set(), newStickyContainerHeight);
}
const { rowModel, rowRenderer, pinnedRowModel } = this.beans;
const pixelAtContainerBoundary = isTop ? rowRenderer.firstVisibleVPixel - this.extraTopHeight : rowRenderer.lastVisibleVPixel - this.extraTopHeight;
const newStickyRows = /* @__PURE__ */ new Set();
const addStickyRow = (stickyRow) => {
newStickyRows.add(stickyRow);
if (isTop) {
const lastChildBottom = this.getLastPixelOfGroup(stickyRow);
const stickRowBottom = pixelAtContainerBoundary + newStickyContainerHeight + stickyRow.rowHeight;
if (lastChildBottom < stickRowBottom) {
stickyRow.stickyRowTop = newStickyContainerHeight + (lastChildBottom - stickRowBottom);
} else {
stickyRow.stickyRowTop = newStickyContainerHeight;
}
} else {
const lastChildBottom = this.getFirstPixelOfGroup(stickyRow);
const stickRowTop = pixelAtContainerBoundary - (newStickyContainerHeight + stickyRow.rowHeight);
if (lastChildBottom > stickRowTop) {
stickyRow.stickyRowTop = newStickyContainerHeight - (lastChildBottom - stickRowTop);
} else {
stickyRow.stickyRowTop = newStickyContainerHeight;
}
}
newStickyContainerHeight = 0;
newStickyRows.forEach((rowNode) => {
const thisRowLastPx = rowNode.stickyRowTop + rowNode.rowHeight;
if (newStickyContainerHeight < thisRowLastPx) {
newStickyContainerHeight = thisRowLastPx;
}
});
};
const suppressFootersSticky = this.areFooterRowsStickySuppressed();
const suppressGroupsSticky = this.gos.get("suppressGroupRowsSticky");
const isRowSticky = (row) => {
if (!row.displayed) {
return false;
}
if (row.footer) {
if (suppressFootersSticky === true) {
return false;
}
if (suppressFootersSticky === "grand" && row.level === -1) {
return false;
}
if (suppressFootersSticky === "group" && row.level > -1) {
return false;
}
const isFooterFirstRowInGroup = row.sibling.rowIndex ? row.sibling.rowIndex + 1 === row.rowIndex : false;
if (container === "bottom" && isFooterFirstRowInGroup) {
return false;
}
if (row.level === -1 && pinnedRowModel?.getGrandTotalPinned()) {
return false;
}
const alreadySticking = newStickyRows.has(row);
return !alreadySticking;
}
if (row.isExpandable()) {
if (suppressGroupsSticky === true) {
return false;
}
if (container === "bottom") {
return false;
}
const alreadySticking = newStickyRows.has(row);
return !alreadySticking && row.expanded;
}
return false;
};
for (let i = 0; i < 100; i++) {
let firstPixelAfterStickyRows = pixelAtContainerBoundary + newStickyContainerHeight;
if (!isTop) {
firstPixelAfterStickyRows = pixelAtContainerBoundary - newStickyContainerHeight;
}
const firstIndex = rowModel.getRowIndexAtPixel(firstPixelAfterStickyRows);
const firstRow = rowModel.getRow(firstIndex);
if (firstRow == null) {
break;
}
const ancestors = this.getStickyAncestors(firstRow);
const firstMissingParent = ancestors.find(
(parent) => (isTop ? parent.rowIndex < firstIndex : parent.rowIndex > firstIndex) && isRowSticky(parent)
);
if (firstMissingParent) {
addStickyRow(firstMissingParent);
continue;
}
const isFirstRowOutsideViewport = isTop ? firstRow.rowTop < firstPixelAfterStickyRows : firstRow.rowTop + firstRow.rowHeight > firstPixelAfterStickyRows;
if (isFirstRowOutsideViewport && isRowSticky(firstRow)) {
addStickyRow(firstRow);
continue;
}
break;
}
if (!isTop) {
newStickyRows.forEach((rowNode) => {
rowNode.stickyRowTop = newStickyContainerHeight - (rowNode.stickyRowTop + rowNode.rowHeight);
});
}
return this.refreshNodesAndContainerHeight(container, newStickyRows, newStickyContainerHeight);
}
areFooterRowsStickySuppressed() {
const suppressFootersSticky = this.gos.get("suppressStickyTotalRow");
if (suppressFootersSticky === true) {
return true;
}
const suppressGroupRows = suppressFootersSticky === "group";
const suppressGrandRows = suppressFootersSticky === "grand";
if (suppressGroupRows && suppressGrandRows) {
return true;
}
if (suppressGrandRows) {
return "grand";
}
if (suppressGroupRows) {
return "group";
}
return false;
}
canRowsBeSticky() {
const isStickyEnabled = (0, import_ag_grid_community141._isGroupRowsSticky)(this.gos);
const suppressFootersSticky = this.areFooterRowsStickySuppressed();
const suppressGroupsSticky = this.gos.get("suppressGroupRowsSticky");
return isStickyEnabled && (!suppressFootersSticky || !suppressGroupsSticky);
}
getStickyAncestors(rowNode) {
const ancestors = [];
let p = rowNode.footer ? rowNode.sibling : rowNode.parent;
while (p) {
if (p.sibling) {
ancestors.push(p.sibling);
}
ancestors.push(p);
p = p.parent;
}
return ancestors.reverse();
}
checkStickyRows() {
const hasTopUpdated = this.updateStickyRows("top");
const hasBottomUpdated = this.updateStickyRows("bottom");
return hasTopUpdated || hasBottomUpdated;
}
destroyStickyCtrls() {
this.resetStickyContainers();
}
resetStickyContainers() {
this.refreshNodesAndContainerHeight("top", /* @__PURE__ */ new Set(), 0);
this.refreshNodesAndContainerHeight("bottom", /* @__PURE__ */ new Set(), 0);
}
refreshStickyNode(stickRowNode) {
const allStickyNodes = /* @__PURE__ */ new Set();
if (this.stickyTopRowCtrls.some((ctrl) => ctrl.rowNode === stickRowNode)) {
for (let i = 0; i < this.stickyTopRowCtrls.length; i++) {
const currentNode = this.stickyTopRowCtrls[i].rowNode;
if (currentNode !== stickRowNode) {
allStickyNodes.add(currentNode);
}
}
if (this.refreshNodesAndContainerHeight("top", allStickyNodes, this.topContainerHeight)) {
this.checkStickyRows();
}
return;
}
for (let i = 0; i < this.stickyBottomRowCtrls.length; i++) {
const currentNode = this.stickyBottomRowCtrls[i].rowNode;
if (currentNode !== stickRowNode) {
allStickyNodes.add(currentNode);
}
}
if (this.refreshNodesAndContainerHeight("bottom", allStickyNodes, this.bottomContainerHeight)) {
this.checkStickyRows();
}
}
/**
* Destroy old ctrls and create new ctrls where necessary.
*/
refreshNodesAndContainerHeight(container, newStickyNodes, height) {
const isTop = container === "top";
const previousCtrls = isTop ? this.stickyTopRowCtrls : this.stickyBottomRowCtrls;
const removedCtrlsMap = {};
const remainingCtrls = [];
for (let i = 0; i < previousCtrls.length; i++) {
const node = previousCtrls[i].rowNode;
const hasBeenRemoved = !newStickyNodes.has(node);
if (hasBeenRemoved) {
removedCtrlsMap[node.id] = previousCtrls[i];
node.sticky = false;
continue;
}
remainingCtrls.push(previousCtrls[i]);
}
const existingNodes = /* @__PURE__ */ new Set();
for (let i = 0; i < remainingCtrls.length; i++) {
existingNodes.add(remainingCtrls[i].rowNode);
}
const newCtrls = [];
newStickyNodes.forEach((node) => {
if (existingNodes.has(node)) {
return;
}
node.sticky = true;
newCtrls.push(this.createRowCon(node, false, false));
});
let hasSomethingChanged = !!newCtrls.length || remainingCtrls.length !== previousCtrls.length;
if (isTop) {
if (this.topContainerHeight !== height) {
this.topContainerHeight = height;
this.gridBodyCtrl.setStickyTopHeight(height);
hasSomethingChanged = true;
}
} else {
if (this.bottomContainerHeight !== height) {
this.bottomContainerHeight = height;
this.gridBodyCtrl.setStickyBottomHeight(height);
hasSomethingChanged = true;
}
}
this.destroyRowCtrls(removedCtrlsMap, false);
const newCtrlsList = [...remainingCtrls, ...newCtrls];
newCtrlsList.sort((a, b) => b.rowNode.rowIndex - a.rowNode.rowIndex);
if (!isTop) {
newCtrlsList.reverse();
}
newCtrlsList.forEach((ctrl) => ctrl.setRowTop(ctrl.rowNode.stickyRowTop));
const pageBounds = this.beans.pageBounds;
let extraHeight = 0;
if (isTop) {
newStickyNodes.forEach((node) => {
if (node.rowIndex < pageBounds.getFirstRow()) {
extraHeight += node.rowHeight;
}
});
if (extraHeight > this.topContainerHeight) {
extraHeight = this.topContainerHeight;
}
this.setOffsetTop(extraHeight);
} else {
newStickyNodes.forEach((node) => {
if (node.rowIndex > pageBounds.getLastRow()) {
extraHeight += node.rowHeight;
}
});
if (extraHeight > this.bottomContainerHeight) {
extraHeight = this.bottomContainerHeight;
}
this.setOffsetBottom(extraHeight);
}
if (!hasSomethingChanged) {
return false;
}
if (isTop) {
this.stickyTopRowCtrls = newCtrlsList;
} else {
this.stickyBottomRowCtrls = newCtrlsList;
}
return true;
}
ensureRowHeightsValid() {
let anyChange = false;
const updateRowHeight = (ctrl) => {
const rowNode = ctrl.rowNode;
if (rowNode.rowHeightEstimated) {
const rowHeight = (0, import_ag_grid_community141._getRowHeightForNode)(this.beans, rowNode);
rowNode.setRowHeight(rowHeight.height);
anyChange = true;
}
};
this.stickyTopRowCtrls.forEach(updateRowHeight);
this.stickyBottomRowCtrls.forEach(updateRowHeight);
return anyChange;
}
};
function getServerSideLastPixelOfGroup(row) {
if (row.isExpandable() || row.footer) {
if (row.master && row.detailNode) {
return row.detailNode.rowTop + row.detailNode.rowHeight;
}
const noOrContiguousSiblings = !row.sibling || Math.abs(row.sibling.rowIndex - row.rowIndex) === 1;
if (noOrContiguousSiblings) {
let storeBounds = row.childStore?.getStoreBounds();
if (row.footer) {
storeBounds = row.sibling.childStore?.getStoreBounds();
}
return (storeBounds?.heightPx ?? 0) + (storeBounds?.topPx ?? 0);
}
if (row.footer) {
return row.rowTop + row.rowHeight;
}
return row.sibling.rowTop + row.sibling.rowHeight;
}
return Number.MAX_SAFE_INTEGER;
}
function getClientSideLastPixelOfGroup(row) {
if (row.isExpandable() || row.footer) {
const grandTotalAtTop = row.footer && row.rowIndex === 0;
if (grandTotalAtTop) {
return Number.MAX_SAFE_INTEGER;
}
const noOrContiguousSiblings = !row.sibling || Math.abs(row.sibling.rowIndex - row.rowIndex) === 1;
if (noOrContiguousSiblings) {
let lastAncestor = row.footer ? row.sibling : row;
while (lastAncestor.isExpandable() && lastAncestor.expanded) {
if (lastAncestor.master && lastAncestor.detailNode) {
lastAncestor = lastAncestor.detailNode;
} else if (lastAncestor.childrenAfterSort) {
if (lastAncestor.childrenAfterSort.length === 0) {
break;
}
lastAncestor = (0, import_ag_grid_community141._last)(lastAncestor.childrenAfterSort);
}
}
return lastAncestor.rowTop + lastAncestor.rowHeight;
}
if (row.footer) {
return row.rowTop + row.rowHeight;
}
return row.sibling.rowTop + row.sibling.rowHeight;
}
return Number.MAX_SAFE_INTEGER;
}
// packages/ag-grid-enterprise/src/rowHierarchy/stickyRowService.ts
var StickyRowService = class extends import_ag_grid_community142.BeanStub {
constructor() {
super(...arguments);
this.beanName = "stickyRowSvc";
}
createStickyRowFeature(ctrl, createRowCon, destroyRowCtrls) {
const gos = this.gos;
if ((0, import_ag_grid_community142._isGroupRowsSticky)(gos) && (0, import_ag_grid_community142._isClientSideRowModel)(gos) || (0, import_ag_grid_community142._isServerSideRowModel)(gos)) {
return ctrl.createManagedBean(new StickyRowFeature(createRowCon, destroyRowCtrls));
}
return void 0;
}
};
// packages/ag-grid-enterprise/src/rowHierarchy/rowHierarchyModule.ts
var GroupCellRendererModule = {
moduleName: "GroupCellRenderer",
version: VERSION,
userComponents: {
agGroupRowRenderer: GroupCellRenderer,
agGroupCellRenderer: GroupCellRenderer
},
dynamicBeans: { groupCellRendererCtrl: GroupCellRendererCtrl },
icons: {
// shown on row group when contracted (click to expand)
groupContracted: "tree-closed",
// shown on row group when expanded (click to contract)
groupExpanded: "tree-open"
},
css: [groupCellStylesCSS],
dependsOn: [EnterpriseCoreModule]
};
var GroupColumnModule = {
moduleName: "GroupColumn",
version: VERSION,
beans: [
AutoColService,
ShowRowGroupColsService,
ShowRowGroupColValueService,
RowGroupColsSvc,
PivotColsSvc,
ValueColsSvc
],
dependsOn: [EnterpriseCoreModule, GroupCellRendererModule]
};
var ClientSideRowModelHierarchyModule = {
moduleName: "ClientSideRowModelHierarchy",
version: VERSION,
rowModels: ["clientSide"],
beans: [GroupStage, FlattenStage, ClientSideExpansionService],
dependsOn: [EnterpriseCoreModule]
};
var StickyRowModule = {
moduleName: "StickyRow",
version: VERSION,
beans: [StickyRowService]
};
// packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/agGridHeaderDropZones.ts
var import_ag_grid_community143 = require("ag-grid-community");
var AgGridHeaderDropZones = class extends import_ag_grid_community143.Component {
constructor() {
super();
}
postConstruct() {
this.setGui(this.createNorthPanel());
const onRowGroupChanged = this.onRowGroupChanged.bind(this);
this.addManagedEventListeners({
columnRowGroupChanged: onRowGroupChanged,
newColumnsLoaded: onRowGroupChanged
});
this.addManagedPropertyListener("rowGroupPanelShow", onRowGroupChanged);
this.addManagedPropertyListener("pivotPanelShow", () => this.onPivotPanelShow());
this.onRowGroupChanged();
}
createNorthPanel() {
const topPanelGui = (0, import_ag_grid_community143._createElement)({ tag: "div", cls: "ag-column-drop-wrapper", role: "presentation" });
const rowGroupComp = new RowGroupDropZonePanel(true);
this.rowGroupComp = this.createManagedBean(rowGroupComp);
const pivotComp = new PivotDropZonePanel(true);
this.pivotComp = this.createManagedBean(pivotComp);
topPanelGui.appendChild(rowGroupComp.getGui());
topPanelGui.appendChild(pivotComp.getGui());
const listener = this.onDropPanelVisible.bind(this);
this.addManagedListeners(rowGroupComp, {
displayChanged: listener
});
this.addManagedListeners(pivotComp, {
displayChanged: listener
});
this.onDropPanelVisible();
return topPanelGui;
}
onDropPanelVisible() {
const { rowGroupComp, pivotComp } = this;
const bothDisplayed = rowGroupComp.isDisplayed() && pivotComp.isDisplayed();
const classStr = "ag-column-drop-horizontal-half-width";
rowGroupComp.toggleCss(classStr, bothDisplayed);
pivotComp.toggleCss(classStr, bothDisplayed);
}
onRowGroupChanged() {
const rowGroupComp = this.rowGroupComp;
if (!rowGroupComp) {
return;
}
const rowGroupPanelShow = this.gos.get("rowGroupPanelShow");
if (rowGroupPanelShow === "always") {
rowGroupComp.setDisplayed(true);
} else if (rowGroupPanelShow === "onlyWhenGrouping") {
const grouping = this.beans.rowGroupColsSvc?.columns?.length !== 0;
rowGroupComp.setDisplayed(grouping);
} else {
rowGroupComp.setDisplayed(false);
}
}
onPivotPanelShow() {
const pivotComp = this.pivotComp;
if (!pivotComp) {
return;
}
const pivotPanelShow = this.gos.get("pivotPanelShow");
if (pivotPanelShow === "always") {
pivotComp.setDisplayed(true);
} else if (pivotPanelShow === "onlyWhenPivoting") {
const pivoting = this.beans.colModel.isPivotActive();
pivotComp.setDisplayed(pivoting);
} else {
pivotComp.setDisplayed(false);
}
}
};
var AgGridHeaderDropZonesSelector = {
selector: "AG-GRID-HEADER-DROP-ZONES",
component: AgGridHeaderDropZones
};
// packages/ag-grid-enterprise/src/rowGrouping/groupFilter/groupFilter.ts
var import_ag_grid_community144 = require("ag-grid-community");
var GroupFilterElement = {
tag: "div",
cls: "ag-group-filter",
children: [
{ tag: "div", ref: "eGroupField" },
{ tag: "div", ref: "eUnderlyingFilter" }
]
};
var GroupFilter = class extends import_ag_grid_community144.TabGuardComp {
constructor() {
super(GroupFilterElement);
this.filterType = "group";
this.eGroupField = import_ag_grid_community144.RefPlaceholder;
this.eUnderlyingFilter = import_ag_grid_community144.RefPlaceholder;
}
wireBeans(beans) {
this.groupFilterSvc = beans.groupFilter;
}
postConstruct() {
this.initialiseTabGuard({});
}
init(legacyParams) {
this.params = legacyParams;
return this.updateParams().then(() => {
this.addHandlerListeners(this.updateGroups.bind(this));
});
}
refresh(legacyParams) {
const params = legacyParams;
this.params = params;
if (params.source === "colDef") {
this.updateParams();
}
return true;
}
updateParams() {
this.validateParams();
return this.updateGroups();
}
validateParams() {
const { colDef } = this.params;
if (colDef.field) {
(0, import_ag_grid_community144._warn)(234);
}
if (colDef.filterValueGetter) {
(0, import_ag_grid_community144._warn)(235);
}
if (colDef.filterParams) {
(0, import_ag_grid_community144._warn)(236);
}
}
addHandlerListeners(listener) {
const destroyFunctions = this.addManagedListeners(this.getHandler(), {
sourceColumnsChanged: () => {
this.updateGroups();
},
destroyed: () => {
destroyFunctions.forEach((func) => func());
this.addHandlerListeners(listener);
}
});
}
updateGroups() {
const { sourceColumns, selectedColumn } = this.updateGroupField();
this.dispatchLocalEvent({
type: "columnsChanged"
});
return this.getUnderlyingFilters(sourceColumns, selectedColumn);
}
updateGroupField() {
this.groupColumn = this.params.column;
const handler = this.getHandler();
if (!handler) {
return { sourceColumns: null };
}
const { sourceColumns, hasMultipleColumns, selectedColumn } = handler;
const eGroupField = this.eGroupField;
(0, import_ag_grid_community144._clearElement)(eGroupField);
if (this.eGroupFieldSelect) {
this.destroyBean(this.eGroupFieldSelect);
}
if (hasMultipleColumns && sourceColumns) {
this.createGroupFieldSelectElement(sourceColumns, selectedColumn);
eGroupField.appendChild(this.eGroupFieldSelect.getGui());
eGroupField.appendChild((0, import_ag_grid_community144._createElement)({ tag: "div", cls: "ag-filter-separator" }));
}
(0, import_ag_grid_community144._setDisplayed)(eGroupField, hasMultipleColumns);
return { sourceColumns, selectedColumn };
}
createGroupFieldSelectElement(sourceColumns, selectedColumn) {
const eGroupFieldSelect = this.createManagedBean(new import_ag_grid_community144.AgSelect());
this.eGroupFieldSelect = eGroupFieldSelect;
const localeTextFunc = this.getLocaleTextFunc();
eGroupFieldSelect.setLabel(localeTextFunc("groupFilterSelect", "Select field:"));
eGroupFieldSelect.setLabelAlignment("top");
eGroupFieldSelect.addOptions(
sourceColumns.map((sourceColumn) => ({
value: sourceColumn.getColId(),
text: this.beans.colNames.getDisplayNameForColumn(sourceColumn, "groupFilter", false) ?? void 0
}))
);
eGroupFieldSelect.setValue(selectedColumn.getColId());
eGroupFieldSelect.onValueChange((newValue) => this.updateSelectedColumn(newValue));
eGroupFieldSelect.addCss("ag-group-filter-field-select-wrapper");
if (sourceColumns.length === 1) {
eGroupFieldSelect.setDisabled(true);
}
}
getUnderlyingFilters(sourceColumns, selectedColumn) {
if (!sourceColumns) {
this.filterColumnPairs = void 0;
this.selectedFilter = void 0;
return import_ag_grid_community144.AgPromise.resolve();
}
const filterPromises = [];
const filterColumnPairs = [];
const colFilter = this.beans.colFilter;
sourceColumns.forEach((column) => {
const filterPromise = colFilter.getOrCreateFilterUi(column);
if (filterPromise) {
filterPromises.push(
filterPromise.then((filter) => {
if (filter) {
filterColumnPairs.push({
filter,
column
});
}
if (column.getColId() === selectedColumn.getColId()) {
this.selectedFilter = filter ?? void 0;
}
})
);
}
});
return import_ag_grid_community144.AgPromise.all(filterPromises).then(() => {
this.filterColumnPairs = filterColumnPairs;
});
}
addUnderlyingFilterElement(selectedColumn) {
(0, import_ag_grid_community144._clearElement)(this.eUnderlyingFilter);
if (!selectedColumn) {
return import_ag_grid_community144.AgPromise.resolve();
}
const comp = this.createManagedBean(new import_ag_grid_community144.FilterComp(selectedColumn, "COLUMN_MENU"));
this.filterComp = comp;
if (!comp.hasFilter()) {
return import_ag_grid_community144.AgPromise.resolve();
}
this.eUnderlyingFilter.appendChild(comp.getGui());
return comp.getFilter()?.then(() => {
comp.afterGuiAttached?.(this.afterGuiAttachedParams);
if (!this.afterGuiAttachedParams?.suppressFocus && this.eGroupFieldSelect && !this.eGroupFieldSelect.isDisabled()) {
this.eGroupFieldSelect.getFocusableElement().focus();
}
}) ?? import_ag_grid_community144.AgPromise.resolve();
}
updateSelectedColumn(columnId) {
if (!columnId) {
return;
}
this.filterComp?.afterGuiDetached();
this.destroyBean(this.filterComp);
const selectedFilterColumnPair = this.getFilterColumnPair(columnId);
const selectedColumn = selectedFilterColumnPair?.column;
this.selectedFilter = selectedFilterColumnPair?.filter;
this.getHandler().setSelectedColumn(selectedColumn);
this.dispatchLocalEvent({
type: "columnsChanged"
});
this.addUnderlyingFilterElement(selectedColumn);
}
isFilterActive() {
return this.groupFilterSvc.isFilterActive(this.groupColumn);
}
doesFilterPass() {
return true;
}
getModel() {
return null;
}
setModel() {
}
afterGuiAttached(params) {
this.afterGuiAttachedParams = params;
this.addUnderlyingFilterElement(this.getHandler().selectedColumn);
}
afterGuiDetached() {
(0, import_ag_grid_community144._clearElement)(this.eUnderlyingFilter);
this.selectedFilter?.afterGuiDetached?.();
}
getSelectedColumn() {
return this.getHandler().selectedColumn;
}
getHandler() {
return this.params.getHandler();
}
getFilterColumnPair(columnId) {
if (!columnId) {
return void 0;
}
return this.filterColumnPairs?.find(({ column }) => column.getColId() === columnId);
}
};
// packages/ag-grid-enterprise/src/rowGrouping/groupFilter/groupFilterHandler.ts
var import_ag_grid_community145 = require("ag-grid-community");
var GroupFilterHandler = class extends import_ag_grid_community145.BeanStub {
init(params) {
this.params = params;
this.validateModel(params);
this.updateColumns();
this.addManagedEventListeners({
columnRowGroupChanged: this.updateColumns.bind(this),
filterDestroyed: (event) => this.onFilterDestroyed(event)
});
}
refresh(params) {
this.params = params;
this.validateModel(params);
if (params.source === "colDef") {
this.updateColumns();
}
}
doesFilterPass() {
return true;
}
setSelectedColumn(selectedColumn) {
this.selectedColumn = selectedColumn;
this.dispatchLocalEvent({ type: "selectedColumnChanged" });
}
validateModel(params) {
if (params.model != null) {
params.onModelChange(null);
}
}
getSourceColumns() {
const groupColumn = this.params.column;
if (this.gos.get("treeData")) {
(0, import_ag_grid_community145._warn)(237);
return [];
}
const sourceColumns = this.beans.groupFilter.getSourceColumns(groupColumn);
if (!sourceColumns) {
(0, import_ag_grid_community145._warn)(183);
return [];
}
return sourceColumns;
}
updateColumns() {
const allSourceColumns = this.getSourceColumns();
const sourceColumns = allSourceColumns.filter((sourceColumn) => sourceColumn.isFilterAllowed());
this.sourceColumns = sourceColumns;
let selectedColumn;
let hasMultipleColumns;
if (!sourceColumns.length) {
selectedColumn = void 0;
hasMultipleColumns = false;
} else {
if (allSourceColumns.length === 1) {
selectedColumn = sourceColumns[0];
hasMultipleColumns = false;
} else {
selectedColumn = this.selectedColumn;
if (!selectedColumn || !sourceColumns.some((column) => column.getId() === selectedColumn.getId())) {
selectedColumn = sourceColumns[0];
}
hasMultipleColumns = true;
}
}
this.selectedColumn = selectedColumn;
this.hasMultipleColumns = hasMultipleColumns;
this.dispatchLocalEvent({ type: "sourceColumnsChanged" });
}
onFilterDestroyed({ column: eventColumn, source }) {
if (source === "gridDestroyed") {
return;
}
const colId = eventColumn.getColId();
if (this.sourceColumns?.some((column) => column.getColId() === colId)) {
setTimeout(() => {
if (this.isAlive()) {
this.updateColumns();
}
});
}
}
};
// packages/ag-grid-enterprise/src/rowGrouping/groupFilter/groupFilterService.ts
var import_ag_grid_community146 = require("ag-grid-community");
var GroupFilterService = class extends import_ag_grid_community146.BeanStub {
constructor() {
super(...arguments);
this.beanName = "groupFilter";
}
postConstruct() {
this.addManagedEventListeners({
columnRowGroupChanged: () => this.updateFilterFlags("columnRowGroupChanged")
});
}
isGroupFilter(column) {
return column.getColDef().filter === "agGroupColumnFilter";
}
isFilterAllowed(column) {
const colFilter = this.beans.colFilter;
return !!this.getSourceColumns(column)?.some((column2) => colFilter?.isFilterAllowed(column2));
}
isFilterActive(column) {
const colFilter = this.beans.colFilter;
return !!this.getSourceColumns(column)?.some((column2) => colFilter?.isFilterActive(column2));
}
getSourceColumns(column) {
return this.beans.showRowGroupCols?.getSourceColumnsForGroupColumn(column);
}
updateFilterFlags(source, additionalEventAttributes) {
const { autoColSvc, colFilter } = this.beans;
autoColSvc?.getColumns()?.forEach((groupColumn) => {
if (this.isGroupFilter(groupColumn)) {
colFilter?.setColFilterActive(
groupColumn,
this.isFilterActive(groupColumn),
source,
additionalEventAttributes
);
}
});
}
};
// packages/ag-grid-enterprise/src/rowGrouping/groupFilter/groupFloatingFilter.ts
var import_ag_grid_community147 = require("ag-grid-community");
var GroupFloatingFilterElement = {
tag: "div",
ref: "eFloatingFilter",
cls: "ag-group-floating-filter ag-floating-filter-input",
role: "presentation"
};
var GroupFloatingFilterComp = class extends import_ag_grid_community147.Component {
constructor() {
super(GroupFloatingFilterElement);
this.eFloatingFilter = import_ag_grid_community147.RefPlaceholder;
this.haveAddedColumnListeners = false;
}
init(params) {
this.params = params;
const canShowUnderlyingFloatingFilter = (0, import_ag_grid_community147._isGroupMultiAutoColumn)(this.gos);
const onColChange = this.onColChange.bind(this);
const setupFilterElement = (resolve) => {
if (canShowUnderlyingFloatingFilter) {
this.setupUnderlyingFloatingFilterElement().then(() => resolve());
} else {
this.setupReadOnlyFloatingFilterElement();
resolve();
}
};
if (this.gos.get("enableFilterHandlers")) {
return new import_ag_grid_community147.AgPromise((resolve) => setupFilterElement(resolve)).then(() => {
this.addHandlerListeners(params, onColChange);
});
} else {
return new import_ag_grid_community147.AgPromise((resolve) => {
this.params.parentFilterInstance((parentFilterInstance) => {
this.parentFilterInstance = parentFilterInstance;
setupFilterElement(resolve);
});
}).then(() => {
this.addManagedListeners(this.parentFilterInstance, {
columnsChanged: onColChange
});
});
}
}
refresh(params) {
this.params = params;
this.setParams();
if (this.gos.get("enableFilterHandlers")) {
if (this.showingUnderlyingFloatingFilter) {
const column = this.getSelectedColumn();
const compDetails = this.beans.colFilter.getFloatingFilterCompDetails(
column,
this.params.showParentFilter
);
this.underlyingFloatingFilter?.refresh?.(compDetails?.params);
} else {
this.updateDisplayedValue();
}
}
}
setParams() {
const displayName = this.beans.colNames.getDisplayNameForColumn(this.params.column, "header", true);
const translate = this.getLocaleTextFunc();
this.eFloatingFilterText?.setInputAriaLabel(`${displayName} ${translate("ariaFilterInput", "Filter Input")}`);
}
addHandlerListeners(params, listener) {
const destroyFunctions = this.addManagedListeners(params.getHandler(), {
selectedColumnChanged: listener,
sourceColumnsChanged: listener,
destroyed: () => {
destroyFunctions.forEach((func) => func());
this.addHandlerListeners(this.params, listener);
}
});
}
setupReadOnlyFloatingFilterElement() {
if (!this.eFloatingFilterText) {
this.eFloatingFilterText = this.createManagedBean(new import_ag_grid_community147.AgInputTextField());
this.eFloatingFilterText.setDisabled(true).addGuiEventListener("click", () => this.params.showParentFilter());
this.setParams();
}
this.updateDisplayedValue();
this.eFloatingFilter.appendChild(this.eFloatingFilterText.getGui());
}
setupUnderlyingFloatingFilterElement() {
this.showingUnderlyingFloatingFilter = false;
this.underlyingFloatingFilter = void 0;
(0, import_ag_grid_community147._clearElement)(this.eFloatingFilter);
const column = this.getSelectedColumn();
if (column && !column.isVisible()) {
const colFilter = this.beans.colFilter;
const compDetails = colFilter.getFloatingFilterCompDetails(column, this.params.showParentFilter);
if (compDetails) {
if (!this.haveAddedColumnListeners) {
this.haveAddedColumnListeners = true;
this.addManagedListeners(column, {
visibleChanged: this.onColumnVisibleChanged.bind(this),
colDefChanged: this.onColDefChanged.bind(this)
});
}
return compDetails.newAgStackInstance().then((floatingFilter) => {
this.underlyingFloatingFilter = floatingFilter;
this.underlyingFloatingFilter?.onParentModelChanged(colFilter.getModelForColumn(column));
this.appendChild(floatingFilter.getGui());
this.showingUnderlyingFloatingFilter = true;
});
}
}
this.setupReadOnlyFloatingFilterElement();
return import_ag_grid_community147.AgPromise.resolve();
}
getSelectedColumn() {
if (this.gos.get("enableFilterHandlers")) {
const reactiveParams = this.params;
return reactiveParams.getHandler().selectedColumn;
} else {
return this.parentFilterInstance.getSelectedColumn();
}
}
onColumnVisibleChanged() {
this.setupUnderlyingFloatingFilterElement();
}
onColDefChanged(event) {
if (!event.column) {
return;
}
const compDetails = this.beans.colFilter.getFloatingFilterCompDetails(
event.column,
this.params.showParentFilter
);
if (compDetails) {
this.underlyingFloatingFilter?.refresh?.(compDetails.params);
}
}
onParentModelChanged(_model, event) {
if (this.showingUnderlyingFloatingFilter) {
this.underlyingFloatingFilter?.onParentModelChanged(
this.beans.colFilter.getModelForColumn(this.getSelectedColumn()),
event
);
} else {
this.updateDisplayedValue();
}
}
updateDisplayedValue() {
const eFloatingFilterText = this.eFloatingFilterText;
if (!eFloatingFilterText) {
return;
}
const colFilter = this.beans.colFilter;
const column = this.getSelectedColumn();
const updateText = (filterOrHandler) => {
if (!filterOrHandler) {
eFloatingFilterText.setValue("");
eFloatingFilterText.setDisplayed(false);
} else {
const model = column ? colFilter.getModelForColumn(column) : null;
eFloatingFilterText.setValue(model == null ? "" : filterOrHandler.getModelAsString?.(model) ?? "");
eFloatingFilterText.setDisplayed(true);
}
};
if (this.gos.get("enableFilterHandlers")) {
updateText(colFilter.getHandler(column));
} else {
colFilter.getOrCreateFilterUi(column)?.then((filter) => {
updateText(filter);
});
}
}
onColChange() {
if (!this.showingUnderlyingFloatingFilter) {
this.updateDisplayedValue();
}
}
};
// packages/ag-grid-enterprise/src/rowGrouping/groupStrategy/groupStrategy.ts
var import_ag_grid_community148 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowGrouping/groupStrategy/batchRemover.ts
var BatchRemover = class {
constructor() {
this.allSets = /* @__PURE__ */ new Map();
}
removeFromChildrenAfterGroup(parent, child) {
const set2 = this.getSet(parent);
(set2.fromChildrenAfterGroup ?? (set2.fromChildrenAfterGroup = /* @__PURE__ */ new Set())).add(child);
}
isRemoveFromAllLeafChildren(parent, child) {
return !!this.allSets.get(parent)?.fromAllLeafChildren?.has(child);
}
preventRemoveFromAllLeafChildren(parent, child) {
this.allSets.get(parent)?.fromAllLeafChildren?.delete(child);
}
removeFromAllLeafChildren(parent, child) {
const set2 = this.getSet(parent);
(set2.fromAllLeafChildren ?? (set2.fromAllLeafChildren = /* @__PURE__ */ new Set())).add(child);
}
getSet(parent) {
let set2 = this.allSets.get(parent);
if (!set2) {
set2 = {
fromChildrenAfterGroup: null,
fromAllLeafChildren: null
};
this.allSets.set(parent, set2);
}
return set2;
}
getAllParents() {
return Array.from(this.allSets.keys());
}
flush() {
const allSets = this.allSets;
for (const parent of allSets.keys()) {
const nodeDetails = allSets.get(parent);
if (nodeDetails) {
const { fromChildrenAfterGroup, fromAllLeafChildren } = nodeDetails;
const { childrenAfterGroup, allLeafChildren } = parent;
if (childrenAfterGroup && fromChildrenAfterGroup) {
filterRowNodesInPlace(childrenAfterGroup, fromChildrenAfterGroup);
parent.updateHasChildren();
}
if (allLeafChildren && fromAllLeafChildren) {
filterRowNodesInPlace(allLeafChildren, fromAllLeafChildren);
}
}
}
allSets.clear();
}
};
function filterRowNodesInPlace(array, removals) {
let writeIdx = 0;
for (let i = 0, len = array.length; i < len; ++i) {
const item = array[i];
if (!removals.has(item)) {
array[writeIdx++] = item;
}
}
array.length = writeIdx;
}
// packages/ag-grid-enterprise/src/rowGrouping/groupStrategy/groupColumns.ts
var makeGroupColumns = (columns) => {
if (!columns) {
return [];
}
const len = columns.length;
const result = new Array(len);
for (let i = 0; i < len; i++) {
const col = columns[i];
const colDef = col.getColDef();
result[i] = {
col,
field: colDef.field,
type: colDef.type,
keyCreator: colDef.keyCreator,
valueGetter: colDef.valueGetter
};
}
return result;
};
var groupColumnsChanged = (groupColumns, columns) => {
const len = groupColumns.length;
if (len !== columns?.length) {
return true;
}
for (let i = 0; i < len; i++) {
const a = groupColumns[i];
const b = columns[i];
if (a.col !== b) {
return true;
}
const bColDef = b.getColDef();
if (a.field !== bColDef.field || a.type !== bColDef.type || a.valueGetter !== bColDef.valueGetter || a.keyCreator !== bColDef.keyCreator) {
return true;
}
}
return false;
};
// packages/ag-grid-enterprise/src/rowGrouping/groupStrategy/sortGroupChildren.ts
function sortGroupChildren(rowNodes) {
if (!rowNodes) {
return false;
}
const length = rowNodes.length;
if (length < 2) {
return false;
}
let atLeastOneOutOfOrder = false;
for (let i = 1; i < length; i++) {
if (compareGroupChildren(rowNodes[i - 1], rowNodes[i]) > 0) {
atLeastOneOutOfOrder = true;
break;
}
}
if (!atLeastOneOutOfOrder) {
return false;
}
rowNodes.sort(compareGroupChildren);
return true;
}
function compareGroupChildren(nodeA, nodeB) {
const positionA = nodeA.sourceRowIndex;
const positionB = nodeB.sourceRowIndex;
const aHasIndex = positionA >= 0;
const bHasIndex = positionB >= 0;
const bothNodesAreUserNodes = aHasIndex && bHasIndex;
const bothNodesAreFillerNodes = !aHasIndex && !bHasIndex;
if (bothNodesAreUserNodes) {
return positionA - positionB;
}
if (bothNodesAreFillerNodes) {
return nodeA.__objectId - nodeB.__objectId;
}
if (aHasIndex) {
return 1;
}
return -1;
}
// packages/ag-grid-enterprise/src/rowGrouping/groupStrategy/groupStrategy.ts
var GroupStrategy = class extends import_ag_grid_community148.BeanStub {
constructor() {
super(...arguments);
// when grouping, these items are of note:
// rowNode.parent: RowNode: set to the parent
// rowNode.childrenAfterGroup: RowNode[] = the direct children of this group
// rowNode.childrenMapped: string=>RowNode = children mapped by group key (when groups) or an empty map if leaf group (this is then used by pivot)
// for leaf groups, rowNode.childrenAfterGroup = rowNode.allLeafChildren;
this.prevGroupCols = null;
this.prevShowGroupCols = null;
}
wireBeans(beans) {
this.colModel = beans.colModel;
this.valueSvc = beans.valueSvc;
this.selectionSvc = beans.selectionSvc;
this.showRowGroupCols = beans.showRowGroupCols;
}
getNode(id) {
let res = void 0;
this.beans.rowModel.forEachNode((node) => {
if (node.id === id) {
res = node;
}
});
return res;
}
execute(params) {
const details = this.createGroupingDetails(params);
const changedRowNodes = params.changedRowNodes;
if (changedRowNodes) {
this.handleDeltaUpdate(details, changedRowNodes);
} else {
this.shotgunResetEverything(details, !!params.afterColumnsChanged);
}
const changedPath = params.changedPath;
this.positionLeafsAndGroups(changedPath);
this.orderGroups(details);
this.selectionSvc?.updateSelectableAfterGrouping(changedPath);
}
positionLeafsAndGroups(changedPath) {
changedPath.forEachChangedNodeDepthFirst((group) => {
if (group.childrenAfterGroup) {
const leafNodes = [];
const groupNodes = [];
let unbalancedNode;
group.childrenAfterGroup.forEach((row) => {
if (!row.childrenAfterGroup?.length) {
leafNodes.push(row);
} else {
if (row.key === "" && !unbalancedNode) {
unbalancedNode = row;
} else {
groupNodes.push(row);
}
}
});
if (unbalancedNode) {
groupNodes.push(unbalancedNode);
}
group.childrenAfterGroup = [...leafNodes, ...groupNodes];
}
}, false);
}
createGroupingDetails(params) {
const { rowNode, changedPath, rowNodesOrderChanged } = params;
let groupColsChanged = false;
const cols = this.beans.rowGroupColsSvc?.columns;
let groupCols = this.prevGroupCols;
if (!groupCols || groupColumnsChanged(groupCols, cols)) {
groupColsChanged = !!groupCols;
this.prevGroupCols = groupCols = makeGroupColumns(cols);
}
const details = {
groupCols,
rootNode: rowNode,
pivotMode: this.colModel.isPivotMode(),
rowNodesOrderChanged: !!rowNodesOrderChanged,
groupColsChanged,
// if no transaction and not immutable row data set, then it's shotgun, changed path would be 'not active' at this point anyway
changedPath,
groupAllowUnbalanced: this.gos.get("groupAllowUnbalanced"),
isGroupOpenByDefault: this.gos.getCallback("isGroupOpenByDefault"),
initialGroupOrderComparator: this.gos.getCallback("initialGroupOrderComparator")
};
return details;
}
handleDeltaUpdate(details, { removals, updates, adds }) {
const batchRemover = new BatchRemover();
if (removals.size) {
this.removeNodes(removals, details, batchRemover);
}
for (const rowNode of updates) {
this.moveNodeInWrongPath(rowNode, details, batchRemover);
}
const changedPath = details.changedPath;
for (const rowNode of adds) {
this.insertOneNode(rowNode, details);
if (changedPath.active) {
changedPath.addParentNode(rowNode.parent);
}
}
const parentsWithChildrenRemoved = batchRemover.getAllParents();
batchRemover.flush();
this.removeEmptyGroups(parentsWithChildrenRemoved, details);
if (details.rowNodesOrderChanged) {
this.sortChildren(details);
}
}
// this is used when doing delta updates, eg Redux, keeps nodes in right order
sortChildren(details) {
details.changedPath.forEachChangedNodeDepthFirst(
(node) => {
const didSort = sortGroupChildren(node.childrenAfterGroup);
if (didSort) {
details.changedPath.addParentNode(node);
}
},
false,
true
);
}
orderGroups(details) {
const comparator = details.initialGroupOrderComparator;
if ((0, import_ag_grid_community148._exists)(comparator)) {
recursiveSort(details.rootNode);
}
function recursiveSort(rowNode) {
const doSort = (0, import_ag_grid_community148._exists)(rowNode.childrenAfterGroup) && // we only want to sort groups, so we do not sort leafs (a leaf group has leafs as children)
!rowNode.leafGroup;
if (doSort) {
rowNode.childrenAfterGroup.sort((nodeA, nodeB) => comparator({ nodeA, nodeB }));
rowNode.childrenAfterGroup.forEach((childNode) => recursiveSort(childNode));
}
}
}
getExistingPathForNode(node, details) {
const res = [];
let pointer = node.parent;
while (pointer && pointer !== details.rootNode) {
res.push({
key: pointer.key,
rowGroupColumn: pointer.rowGroupColumn,
field: pointer.field
});
pointer = pointer.parent;
}
res.reverse();
return res;
}
moveNodeInWrongPath(childNode, details, batchRemover) {
if (details.changedPath.active) {
details.changedPath.addParentNode(childNode.parent);
}
const infoToKeyMapper = (item) => item.key;
const oldPath = this.getExistingPathForNode(childNode, details).map(infoToKeyMapper);
const newPath = this.getGroupInfo(childNode, details).map(infoToKeyMapper);
const nodeInCorrectPath = (0, import_ag_grid_community148._areEqual)(oldPath, newPath);
if (!nodeInCorrectPath) {
this.moveNode(childNode, details, batchRemover);
}
}
moveNode(childNode, details, batchRemover) {
this.removeNodesFromParents([childNode], details, batchRemover);
this.insertOneNode(childNode, details, batchRemover);
childNode.setData(childNode.data);
if (details.changedPath.active) {
const newParent = childNode.parent;
details.changedPath.addParentNode(newParent);
}
}
removeNodes(leafRowNodes, details, batchRemover) {
this.removeNodesFromParents(leafRowNodes, details, batchRemover);
if (details.changedPath.active) {
for (const rowNode of leafRowNodes) {
details.changedPath.addParentNode(rowNode.parent);
}
}
}
forEachParentGroup(details, group, callback) {
let pointer = group;
while (pointer && pointer !== details.rootNode) {
callback(pointer);
pointer = pointer.parent;
}
}
removeNodesFromParents(nodesToRemove, details, provided) {
const batchRemoverIsLocal = provided == null;
const batchRemoverToUse = provided ? provided : new BatchRemover();
for (const nodeToRemove of nodesToRemove) {
this.removeFromParent(nodeToRemove, batchRemoverToUse);
this.forEachParentGroup(details, nodeToRemove.parent, (parentNode) => {
batchRemoverToUse.removeFromAllLeafChildren(parentNode, nodeToRemove);
});
}
if (batchRemoverIsLocal) {
batchRemoverToUse.flush();
}
}
removeEmptyGroups(possibleEmptyGroups, details) {
let checkAgain = true;
const groupShouldBeRemoved = (rowNode) => {
const mapKey = this.getChildrenMappedKey(rowNode.key, rowNode.rowGroupColumn);
const parentChildrenMapped = rowNode.parent?.childrenMapped;
const groupAlreadyRemoved = parentChildrenMapped ? !parentChildrenMapped[mapKey] : true;
if (groupAlreadyRemoved) {
return false;
}
return !!rowNode.group && (rowNode.childrenAfterGroup?.length ?? 0) === 0;
};
while (checkAgain) {
checkAgain = false;
const batchRemover = new BatchRemover();
possibleEmptyGroups.forEach((possibleEmptyGroup) => {
this.forEachParentGroup(details, possibleEmptyGroup, (rowNode) => {
if (groupShouldBeRemoved(rowNode)) {
checkAgain = true;
this.removeFromParent(rowNode, batchRemover);
this.selectionSvc?.setNodesSelected({
nodes: [rowNode],
newValue: false,
source: "rowGroupChanged"
});
}
});
});
batchRemover.flush();
}
}
// removes the node from the parent by:
// a) removing from childrenAfterGroup (using batchRemover if present, otherwise immediately)
// b) removing from childrenMapped (immediately)
// c) setRowTop(null) - as the rowRenderer uses this to know the RowNode is no longer needed
// d) setRowIndex(null) - as the rowNode will no longer be displayed.
removeFromParent(child, batchRemover) {
if (child.parent) {
if (batchRemover) {
batchRemover.removeFromChildrenAfterGroup(child.parent, child);
} else {
(0, import_ag_grid_community148._removeFromArray)(child.parent.childrenAfterGroup, child);
child.parent.updateHasChildren();
}
}
const mapKey = this.getChildrenMappedKey(child.key, child.rowGroupColumn);
const childParentChildrenMapped = child.parent?.childrenMapped;
if (childParentChildrenMapped) {
delete childParentChildrenMapped[mapKey];
}
child.setRowTop(null);
child.setRowIndex(null);
}
/**
* This is idempotent, but relies on the `key` field being the same throughout a RowNode's lifetime
*/
addToParent(child, parent) {
const childrenMapped = parent.childrenMapped ?? (parent.childrenMapped = {});
const mapKey = this.getChildrenMappedKey(child.key, child.rowGroupColumn);
if (childrenMapped[mapKey] !== child) {
childrenMapped[mapKey] = child;
(parent.childrenAfterGroup ?? (parent.childrenAfterGroup = [])).push(child);
setRowNodeGroup(parent, this.beans, true);
}
}
checkAllGroupDataAfterColsChanged(details) {
const recurse = (rowNodes) => {
if (!rowNodes) {
return;
}
rowNodes.forEach((rowNode) => {
const isLeafNode = !rowNode.group;
if (isLeafNode) {
return;
}
const groupInfo = {
field: rowNode.field,
key: rowNode.key,
rowGroupColumn: rowNode.rowGroupColumn,
leafNode: rowNode.allLeafChildren?.[0]
};
this.setGroupData(rowNode, groupInfo);
recurse(rowNode.childrenAfterGroup);
});
};
recurse(details.rootNode.childrenAfterGroup);
}
shotgunResetEverything(details, afterColumnsChanged) {
if (this.noChangeInGroupingColumns(details, afterColumnsChanged)) {
return;
}
this.selectionSvc?.filterFromSelection?.((node) => !node.group);
const rootNode = details.rootNode;
rootNode.leafGroup = details.groupCols.length === 0;
rootNode.childrenAfterGroup = [];
rootNode.childrenMapped = {};
rootNode.updateHasChildren();
const sibling = rootNode.sibling;
if (sibling) {
sibling.childrenAfterGroup = rootNode.childrenAfterGroup;
sibling.childrenMapped = rootNode.childrenMapped;
}
this.insertNodes(rootNode.allLeafChildren, details);
}
noChangeInGroupingColumns(details, afterColumnsChanged) {
let showGroupColsChanged = false;
const showGroupCols = this.prevShowGroupCols;
const showCols = this.showRowGroupCols.getShowRowGroupCols();
if (!showGroupCols || groupColumnsChanged(showGroupCols, showCols)) {
showGroupColsChanged = !!showGroupCols;
this.prevShowGroupCols = makeGroupColumns(showCols);
}
if (!afterColumnsChanged || details.groupColsChanged) {
return false;
}
if (showGroupColsChanged) {
this.checkAllGroupDataAfterColsChanged(details);
}
return true;
}
insertNodes(newRowNodes, details) {
newRowNodes.forEach((rowNode) => {
this.insertOneNode(rowNode, details);
if (details.changedPath.active) {
details.changedPath.addParentNode(rowNode.parent);
}
});
}
insertOneNode(childNode, details, batchRemover) {
const path = this.getGroupInfo(childNode, details);
const parentGroup = this.findParentForNode(childNode, path, details, batchRemover);
if (!parentGroup.group) {
(0, import_ag_grid_community148._warn)(184, { parentGroupData: parentGroup.data, childNodeData: childNode.data });
}
childNode.parent = parentGroup;
childNode.level = path.length;
parentGroup.childrenAfterGroup.push(childNode);
parentGroup.updateHasChildren();
}
findParentForNode(childNode, path, details, batchRemover) {
let nextNode = details.rootNode;
path.forEach((groupInfo, level) => {
nextNode = this.getOrCreateNextNode(nextNode, groupInfo, level, details);
if (!batchRemover?.isRemoveFromAllLeafChildren(nextNode, childNode)) {
nextNode.allLeafChildren.push(childNode);
} else {
batchRemover?.preventRemoveFromAllLeafChildren(nextNode, childNode);
}
});
return nextNode;
}
getOrCreateNextNode(parentGroup, groupInfo, level, details) {
const key = this.getChildrenMappedKey(groupInfo.key, groupInfo.rowGroupColumn);
const parentChildrenMapped = parentGroup?.childrenMapped;
let nextNode = parentChildrenMapped?.[key];
if (!nextNode) {
nextNode = this.createGroup(groupInfo, parentGroup, level, details);
this.addToParent(nextNode, parentGroup);
}
return nextNode;
}
createGroup(groupInfo, parent, level, details) {
const groupNode = new import_ag_grid_community148.RowNode(this.beans);
groupNode.group = true;
groupNode.field = groupInfo.field;
groupNode.rowGroupColumn = groupInfo.rowGroupColumn;
this.setGroupData(groupNode, groupInfo);
groupNode.key = groupInfo.key;
groupNode.id = this.createGroupId(groupNode, parent, level);
groupNode.level = level;
groupNode.leafGroup = level === details.groupCols.length - 1;
groupNode.allLeafChildren = [];
groupNode.setAllChildrenCount(0);
groupNode.rowGroupIndex = level;
groupNode.childrenAfterGroup = [];
groupNode.childrenMapped = {};
groupNode.updateHasChildren();
groupNode.parent = parent;
this.setExpandedInitialValue(details, groupNode);
return groupNode;
}
createGroupId(node, parent, level) {
const createGroupId = (node2, parent2) => {
if (!node2.rowGroupColumn) {
return null;
}
const parentId = parent2 ? createGroupId(parent2, parent2.parent, 0) : null;
return `${parentId == null ? "" : parentId + "-"}${node2.rowGroupColumn.getColId()}-${node2.key}`;
};
return import_ag_grid_community148._ROW_ID_PREFIX_ROW_GROUP + createGroupId(node, parent, level);
}
setGroupData(groupNode, groupInfo) {
const rowGroupCol = groupInfo.rowGroupColumn;
if (rowGroupCol && groupInfo.leafNode) {
groupNode.groupValue = this.valueSvc.getValue(rowGroupCol, groupInfo.leafNode);
}
groupNode.groupData = {};
const groupDisplayCols = this.showRowGroupCols.getShowRowGroupCols();
groupDisplayCols.forEach((col) => {
const groupColumn = groupNode.rowGroupColumn;
const isRowGroupDisplayed = groupColumn !== null && col.isRowGroupDisplayed(groupColumn.getId());
if (isRowGroupDisplayed) {
groupNode.groupData[col.getColId()] = this.valueSvc.getValue(groupColumn, groupInfo.leafNode);
}
});
}
getChildrenMappedKey(key, rowGroupColumn) {
return rowGroupColumn ? rowGroupColumn.getId() + "-" + key : key;
}
setExpandedInitialValue(details, groupNode) {
if (details.pivotMode && groupNode.leafGroup) {
groupNode.expanded = false;
return;
}
groupNode.expanded = _getRowDefaultExpanded(this.beans, groupNode, groupNode.level);
}
getGroupInfo(rowNode, details) {
const res = [];
for (const { col, field } of details.groupCols) {
let key = this.valueSvc.getKeyForNode(col, rowNode);
let keyExists = key !== null && key !== void 0 && key !== "";
const createGroupForEmpty = details.pivotMode || !details.groupAllowUnbalanced;
if (createGroupForEmpty && !keyExists) {
key = "";
keyExists = true;
}
if (keyExists) {
const item = {
key,
field,
rowGroupColumn: col,
leafNode: rowNode
};
res.push(item);
}
}
return res;
}
};
// packages/ag-grid-enterprise/src/rowGrouping/rowGroupingApi.ts
function setRowGroupColumns(beans, colKeys) {
beans.rowGroupColsSvc?.setColumns(colKeys, "api");
}
function removeRowGroupColumns(beans, colKeys) {
beans.rowGroupColsSvc?.removeColumns(colKeys, "api");
}
function addRowGroupColumns(beans, colKeys) {
beans.rowGroupColsSvc?.addColumns(colKeys, "api");
}
function moveRowGroupColumn(beans, fromIndex, toIndex) {
beans.rowGroupColsSvc?.moveColumn?.(fromIndex, toIndex, "api");
}
function getRowGroupColumns(beans) {
return beans.rowGroupColsSvc?.columns ?? [];
}
// packages/ag-grid-enterprise/src/rowGrouping/rowGroupingModule.ts
var SharedRowGroupingModule = {
moduleName: "SharedRowGrouping",
version: VERSION,
apiFunctions: {
setRowGroupColumns,
removeRowGroupColumns,
addRowGroupColumns,
getRowGroupColumns,
moveRowGroupColumn
},
dependsOn: [EnterpriseCoreModule, SharedAggregationModule, GroupColumnModule, StickyRowModule]
};
var RowGroupingModule = {
moduleName: "RowGrouping",
version: VERSION,
dynamicBeans: { groupStrategy: GroupStrategy },
rowModels: ["clientSide"],
dependsOn: [SharedRowGroupingModule, AggregationModule, ClientSideRowModelHierarchyModule]
};
var RowGroupingPanelModule = {
moduleName: "RowGroupingPanel",
version: VERSION,
selectors: [AgGridHeaderDropZonesSelector],
icons: {
// identifies the pivot drop zone
pivotPanel: "pivot",
// "Row groups" drop zone in column tool panel
rowGroupPanel: "group",
// separator between column 'pills' when you add multiple columns to the header drop zone
panelDelimiter: "small-right",
// version of panelDelimiter used in RTL mode
panelDelimiterRtl: "small-left"
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community149._PopupModule]
};
var GroupFilterModule = {
moduleName: "GroupFilter",
version: VERSION,
userComponents: { agGroupColumnFilter: GroupFilter, agGroupColumnFloatingFilter: GroupFloatingFilterComp },
beans: [GroupFilterService],
dynamicBeans: {
agGroupColumnFilterHandler: GroupFilterHandler
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community149._ColumnFilterModule]
};
// packages/ag-grid-enterprise/src/viewportRowModel/viewportRowModel.ts
var import_ag_grid_community150 = require("ag-grid-community");
var ViewportRowModel = class extends import_ag_grid_community150.BeanStub {
constructor() {
super(...arguments);
this.beanName = "rowModel";
// rowRenderer tells us these
this.firstRow = -1;
this.lastRow = -1;
// datasource tells us this
this.rowCount = -1;
this.rowNodesByIndex = {};
/**
* Used to see if setRowData has been called inside of the viewportChanged event context,
* if so the new rows are already being calculated, and the model does not need updated
* otherwise, a new model event needs to fire as rows have changed externally.
*/
this.viewportChangedContext = false;
}
// we don't implement as lazy row heights is not supported in this row model
ensureRowHeightsValid(_startPixel, _endPixel, _startLimitIndex, _endLimitIndex) {
return false;
}
postConstruct() {
const beans = this.beans;
this.rowHeight = (0, import_ag_grid_community150._getRowHeightAsNumber)(beans);
this.addManagedEventListeners({ viewportChanged: this.onViewportChanged.bind(this) });
this.addManagedPropertyListener("viewportDatasource", () => this.updateDatasource());
this.addManagedPropertyListener("rowHeight", () => {
this.rowHeight = (0, import_ag_grid_community150._getRowHeightAsNumber)(beans);
this.updateRowHeights();
});
}
start() {
this.updateDatasource();
}
isLastRowIndexKnown() {
return true;
}
destroy() {
this.destroyDatasource();
super.destroy();
}
destroyDatasource() {
const datasource = this.datasource;
if (!datasource) {
return;
}
datasource.destroy?.();
this.beans.rowRenderer.datasourceChanged();
this.firstRow = -1;
this.lastRow = -1;
}
updateDatasource() {
const datasource = this.gos.get("viewportDatasource");
if (datasource) {
this.setViewportDatasource(datasource);
}
}
getPageSize() {
return this.gos.get("viewportRowModelPageSize");
}
getBufferSize() {
return this.gos.get("viewportRowModelBufferSize");
}
calculateFirstRow(firstRenderedRow) {
const bufferSize = this.getBufferSize();
const pageSize = this.getPageSize();
const afterBuffer = firstRenderedRow - bufferSize;
if (afterBuffer < 0) {
return 0;
}
return Math.floor(afterBuffer / pageSize) * pageSize;
}
calculateLastRow(lastRenderedRow) {
if (lastRenderedRow === -1) {
return lastRenderedRow;
}
const bufferSize = this.getBufferSize();
const pageSize = this.getPageSize();
const afterBuffer = lastRenderedRow + bufferSize;
const result = Math.ceil(afterBuffer / pageSize) * pageSize;
const lastRowIndex = this.rowCount - 1;
return Math.min(result, lastRowIndex);
}
onViewportChanged(event) {
const newFirst = this.calculateFirstRow(event.firstRow);
const newLast = this.calculateLastRow(event.lastRow);
if (this.firstRow !== newFirst || this.lastRow !== newLast) {
this.firstRow = newFirst;
this.lastRow = newLast;
this.purgeRowsNotInViewport();
this.viewportChangedContext = true;
this.datasource?.setViewportRange(this.firstRow, this.lastRow);
this.viewportChangedContext = false;
}
}
purgeRowsNotInViewport() {
const rowNodesByIndex = this.rowNodesByIndex;
Object.keys(rowNodesByIndex).forEach((indexStr) => {
const index = parseInt(indexStr, 10);
if (index < this.firstRow || index > this.lastRow) {
if (this.isRowFocused(index) || this.beans.editSvc?.isRowEditing(rowNodesByIndex[index])) {
return;
}
delete rowNodesByIndex[index];
}
});
}
isRowFocused(rowIndex) {
const focusedCell = this.beans.focusSvc.getFocusCellToUseAfterRefresh();
if (!focusedCell) {
return false;
}
if (focusedCell.rowPinned != null) {
return false;
}
const hasFocus = focusedCell.rowIndex === rowIndex;
return hasFocus;
}
setViewportDatasource(viewportDatasource) {
this.destroyDatasource();
this.datasource = viewportDatasource;
this.rowCount = -1;
if (!viewportDatasource.init) {
(0, import_ag_grid_community150._warn)(226);
} else {
viewportDatasource.init({
setRowCount: this.setRowCount.bind(this),
setRowData: this.setRowData.bind(this),
getRow: this.getRow.bind(this)
});
}
}
getType() {
return "viewport";
}
getRow(rowIndex) {
if (!this.rowNodesByIndex[rowIndex]) {
this.rowNodesByIndex[rowIndex] = this.createBlankRowNode(rowIndex);
}
return this.rowNodesByIndex[rowIndex];
}
getRowNode(id) {
let result;
this.forEachNode((rowNode) => {
if (rowNode.id === id) {
result = rowNode;
}
});
return result;
}
getRowCount() {
return this.rowCount === -1 ? 0 : this.rowCount;
}
getRowIndexAtPixel(pixel) {
if (this.rowHeight !== 0) {
return Math.floor(pixel / this.rowHeight);
}
return 0;
}
getRowBounds(index) {
const rowHeight = this.rowHeight;
return {
rowHeight,
rowTop: rowHeight * index
};
}
updateRowHeights() {
const rowHeight = this.rowHeight;
this.forEachNode((node) => {
node.setRowHeight(rowHeight);
node.setRowTop(rowHeight * node.rowIndex);
});
this.eventSvc.dispatchEvent({
type: "modelUpdated",
newData: false,
newPage: false,
keepRenderedRows: true,
animate: false
});
}
getTopLevelRowCount() {
return this.getRowCount();
}
getTopLevelRowDisplayedIndex(topLevelIndex) {
return topLevelIndex;
}
isEmpty() {
return this.rowCount > 0;
}
isRowsToRender() {
return this.rowCount > 0;
}
getNodesInRangeForSelection(firstInRange, lastInRange) {
const firstIndex = firstInRange.rowIndex;
const lastIndex = lastInRange.rowIndex;
const firstNodeOutOfRange = firstIndex < this.firstRow || firstIndex > this.lastRow;
const lastNodeOutOfRange = lastIndex < this.firstRow || lastIndex > this.lastRow;
if (firstNodeOutOfRange || lastNodeOutOfRange) {
return [];
}
const result = [];
const startIndex = firstIndex <= lastIndex ? firstIndex : lastIndex;
const endIndex = firstIndex <= lastIndex ? lastIndex : firstIndex;
for (let i = startIndex; i <= endIndex; i++) {
result.push(this.rowNodesByIndex[i]);
}
return result;
}
forEachNode(callback) {
let callbackCount = 0;
Object.keys(this.rowNodesByIndex).forEach((indexStr) => {
const index = parseInt(indexStr, 10);
const rowNode = this.rowNodesByIndex[index];
callback(rowNode, callbackCount);
callbackCount++;
});
}
setRowData(rowData) {
const getRowIdFunc = (0, import_ag_grid_community150._getRowIdCallback)(this.beans.gos);
const existingNodesById = /* @__PURE__ */ new Map();
if (getRowIdFunc) {
for (const row of Object.values(this.rowNodesByIndex)) {
existingNodesById.set(row.id, row);
}
}
for (let i = this.firstRow; i <= this.lastRow; i++) {
const data = rowData[i];
if (!data) {
continue;
}
let rowId;
let row;
if (getRowIdFunc) {
rowId = getRowIdFunc({ data, rowPinned: void 0, level: 0, parentKeys: void 0 });
row = existingNodesById.get(rowId);
} else {
row = this.rowNodesByIndex[i];
}
if (row) {
row.updateData(data);
row.setRowIndex(i);
row.setRowTop(this.rowHeight * i);
} else {
row = this.createBlankRowNode(i);
row.setDataAndId(data, rowId ?? i.toString());
}
this.rowNodesByIndex[i] = row;
}
if (!this.viewportChangedContext) {
this.eventSvc.dispatchEvent({
type: "modelUpdated",
newData: false,
newPage: false,
keepRenderedRows: true,
animate: false
});
}
}
createBlankRowNode(rowIndex) {
const rowNode = new import_ag_grid_community150.RowNode(this.beans);
const rowHeight = this.rowHeight;
rowNode.setRowHeight(rowHeight);
rowNode.setRowTop(rowHeight * rowIndex);
rowNode.setRowIndex(rowIndex);
return rowNode;
}
setRowCount(rowCount, keepRenderedRows = false) {
if (rowCount === this.rowCount) {
return;
}
this.rowCount = rowCount;
const eventSvc = this.eventSvc;
eventSvc.dispatchEventOnce({
type: "rowCountReady"
});
eventSvc.dispatchEvent({
type: "modelUpdated",
newData: false,
newPage: false,
keepRenderedRows,
animate: false
});
}
isRowPresent(rowNode) {
const foundRowNode = this.getRowNode(rowNode.id);
return !!foundRowNode;
}
};
// packages/ag-grid-enterprise/src/viewportRowModel/viewportRowModelModule.ts
var ViewportRowModelModule = {
moduleName: "ViewportRowModel",
version: VERSION,
rowModels: ["viewport"],
beans: [ViewportRowModel],
dependsOn: [EnterpriseCoreModule]
};
// packages/ag-grid-enterprise/src/clipboard/clipboardModule.ts
var import_ag_grid_community152 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/clipboard/clipboardApi.ts
function copyToClipboard(beans, params) {
beans.clipboardSvc?.copyToClipboard(params);
}
function cutToClipboard(beans, params) {
beans.clipboardSvc?.cutToClipboard(params);
}
function copySelectedRowsToClipboard(beans, params) {
beans.clipboardSvc?.copySelectedRowsToClipboard(params);
}
function copySelectedRangeToClipboard(beans, params) {
beans.clipboardSvc?.copySelectedRangeToClipboard(params);
}
function copySelectedRangeDown(beans) {
beans.clipboardSvc?.copyRangeDown();
}
function pasteFromClipboard(beans) {
beans.clipboardSvc?.pasteFromClipboard();
}
// packages/ag-grid-enterprise/src/clipboard/clipboardService.ts
var import_ag_grid_community151 = require("ag-grid-community");
var SOURCE_PASTE = "paste";
var EXPORT_TYPE_DRAG_COPY = "dragCopy";
var EXPORT_TYPE_CLIPBOARD = "clipboard";
function stringToArray(strData, delimiter = ",") {
const data = [];
const isNewline = (char) => char === "\r" || char === "\n";
let insideQuotedField = false;
if (strData === "") {
return [[""]];
}
for (let row = 0, column = 0, position = 0; position < strData.length; position++) {
const previousChar = strData[position - 1];
const currentChar = strData[position];
const nextChar = strData[position + 1];
const ensureDataExists = () => {
if (!data[row]) {
data[row] = [];
}
if (!data[row][column]) {
data[row][column] = "";
}
};
ensureDataExists();
if (currentChar === '"') {
if (insideQuotedField) {
if (nextChar === '"') {
data[row][column] += '"';
position++;
} else {
insideQuotedField = false;
}
} else if (previousChar === void 0 || previousChar === delimiter || isNewline(previousChar)) {
insideQuotedField = true;
}
}
if (!insideQuotedField && currentChar !== '"') {
if (currentChar === delimiter) {
column++;
ensureDataExists();
continue;
} else if (isNewline(currentChar)) {
column = 0;
row++;
ensureDataExists();
if (currentChar === "\r" && nextChar === "\n") {
position++;
}
continue;
}
}
data[row][column] += currentChar;
}
return data;
}
var ClipboardService = class extends import_ag_grid_community151.BeanStub {
constructor() {
super(...arguments);
this.beanName = "clipboardSvc";
this.clientSideRowModel = null;
this.gridCtrl = null;
this.lastPasteOperationTime = 0;
this.navigatorApiFailed = false;
}
postConstruct() {
const { gos, rowModel, ctrlsSvc } = this.beans;
if ((0, import_ag_grid_community151._isClientSideRowModel)(gos, rowModel)) {
this.clientSideRowModel = rowModel;
}
ctrlsSvc.whenReady(this, (p) => {
this.gridCtrl = p.gridCtrl;
});
}
destroy() {
super.destroy();
this.clientSideRowModel = null;
this.gridCtrl = null;
}
pasteFromClipboard() {
const allowNavigator = !this.gos.get("suppressClipboardApi");
if (allowNavigator && !this.navigatorApiFailed && navigator.clipboard && navigator.clipboard.readText) {
navigator.clipboard.readText().then(this.processClipboardData.bind(this)).catch((e) => {
(0, import_ag_grid_community151._warn)(40, { e, method: "readText" });
this.navigatorApiFailed = true;
this.pasteFromClipboardLegacy();
});
} else {
this.pasteFromClipboardLegacy();
}
}
pasteFromClipboardLegacy() {
let defaultPrevented = false;
const handlePasteEvent = (e) => {
const currentPastOperationTime = Date.now();
if (currentPastOperationTime - this.lastPasteOperationTime < 50) {
defaultPrevented = true;
e.preventDefault();
}
this.lastPasteOperationTime = currentPastOperationTime;
};
this.executeOnTempElement(
(textArea) => {
textArea.addEventListener("paste", handlePasteEvent);
textArea.focus({ preventScroll: true });
},
(element) => {
const data = element.value;
if (!defaultPrevented) {
this.processClipboardData(data);
} else {
this.refocusLastFocusedCell();
}
element.removeEventListener("paste", handlePasteEvent);
}
);
}
refocusLastFocusedCell() {
const { focusSvc } = this.beans;
const focusedCell = focusSvc.getFocusedCell();
if (focusedCell) {
focusSvc.setFocusedCell({
rowIndex: focusedCell.rowIndex,
column: focusedCell.column,
rowPinned: focusedCell.rowPinned,
forceBrowserFocus: true
});
}
}
getClipboardDelimiter() {
const delimiter = this.gos.get("clipboardDelimiter");
return (0, import_ag_grid_community151._exists)(delimiter) ? delimiter : " ";
}
processClipboardData(data) {
if (data == null) {
return;
}
let parsedData = stringToArray(data, this.getClipboardDelimiter());
const userFunc = this.gos.getCallback("processDataFromClipboard");
if (userFunc) {
parsedData = userFunc({ data: parsedData });
}
if (parsedData == null) {
return;
}
if (this.gos.get("suppressLastEmptyLineOnPaste")) {
this.removeLastLineIfBlank(parsedData);
}
const { rangeSvc } = this.beans;
const pasteOperation = (cellsToFlash, updatedRowNodes, focusedCell, changedPath) => {
const rangeActive = rangeSvc?.isMoreThanOneCell();
const pasteIntoRange = rangeActive && !this.hasOnlyOneValueToPaste(parsedData);
if (pasteIntoRange) {
this.pasteIntoActiveRange(rangeSvc, parsedData, cellsToFlash, updatedRowNodes, changedPath);
} else {
this.pasteStartingFromFocusedCell(parsedData, cellsToFlash, updatedRowNodes, focusedCell, changedPath);
}
this.beans.editSvc?.stopEditing(void 0, { source: SOURCE_PASTE });
};
this.doPasteOperation(pasteOperation);
}
// common code to paste operations, e.g. paste to cell, paste to range, and copy range down
doPasteOperation(pasteOperationFunc) {
const source = "clipboard";
const { eventSvc, focusSvc, rowRenderer, gos } = this.beans;
eventSvc.dispatchEvent({
type: "pasteStart",
source
});
const { clientSideRowModel } = this;
const rootNode = clientSideRowModel?.rootNode;
const changedPath = rootNode && new import_ag_grid_community151.ChangedPath(gos.get("aggregateOnlyChangedColumns"), rootNode);
const cellsToFlash = {};
const updatedRowNodes = [];
const focusedCell = focusSvc.getFocusedCell();
pasteOperationFunc(cellsToFlash, updatedRowNodes, focusedCell, changedPath);
const nodesToRefresh = [...updatedRowNodes];
if (changedPath) {
clientSideRowModel.doAggregate(changedPath);
changedPath.forEachChangedNodeDepthFirst((rowNode) => {
nodesToRefresh.push(rowNode);
});
}
rowRenderer.refreshCells({ rowNodes: nodesToRefresh });
this.dispatchFlashCells(cellsToFlash);
this.fireRowChanged(updatedRowNodes);
this.refocusLastFocusedCell();
eventSvc.dispatchEvent({
type: "pasteEnd",
source
});
}
pasteIntoActiveRange(rangeSvc, clipboardData, cellsToFlash, updatedRowNodes, changedPath) {
const abortRepeatingPasteIntoRows = this.getRangeSize(rangeSvc) % clipboardData.length != 0;
let indexOffset = 0;
let dataRowIndex = 0;
const rowCallback = (currentRow, rowNode, columns, index) => {
const selectionColIdx = columns.findIndex(import_ag_grid_community151.isColumnSelectionCol);
if (selectionColIdx !== -1) {
columns.splice(selectionColIdx, 1);
}
const atEndOfClipboardData = index - indexOffset >= clipboardData.length;
if (atEndOfClipboardData) {
if (abortRepeatingPasteIntoRows) {
return;
}
indexOffset += dataRowIndex;
dataRowIndex = 0;
}
const currentRowData = clipboardData[index - indexOffset];
updatedRowNodes.push(rowNode);
const processCellFromClipboardFunc = this.gos.getCallback("processCellFromClipboard");
for (let idx = 0; idx < columns.length; idx++) {
const column = columns[idx];
if (!column.isCellEditable(rowNode) || column.isSuppressPaste(rowNode)) {
continue;
}
let calculatedIdx = idx;
if (idx >= currentRowData.length) {
calculatedIdx = idx % currentRowData.length;
}
const newValue = this.processCell(
rowNode,
column,
currentRowData[calculatedIdx],
EXPORT_TYPE_DRAG_COPY,
processCellFromClipboardFunc,
true
);
this.beans.editSvc?.commitNextEdit();
rowNode.setDataValue(column, newValue, SOURCE_PASTE);
changedPath?.addParentNode(rowNode.parent, [column]);
const { rowIndex, rowPinned } = currentRow;
const cellId = (0, import_ag_grid_community151._createCellId)({ rowIndex, column, rowPinned });
cellsToFlash[cellId] = true;
}
dataRowIndex++;
};
this.iterateActiveRanges(false, rowCallback);
}
getDisplayedColumnsStartingAt(column) {
let currentColumn = column;
const columns = [];
const { visibleCols } = this.beans;
while (currentColumn && (0, import_ag_grid_community151.isSpecialCol)(currentColumn)) {
currentColumn = visibleCols.getColAfter(currentColumn);
}
while (currentColumn != null) {
columns.push(currentColumn);
currentColumn = visibleCols.getColAfter(currentColumn);
}
return columns;
}
pasteStartingFromFocusedCell(parsedData, cellsToFlash, updatedRowNodes, focusedCell, changedPath) {
if (!focusedCell) {
return;
}
const currentRow = { rowIndex: focusedCell.rowIndex, rowPinned: focusedCell.rowPinned };
const columnsToPasteInto = this.getDisplayedColumnsStartingAt(focusedCell.column);
if (this.isPasteSingleValueIntoRange(parsedData)) {
this.pasteSingleValueIntoRange(parsedData, updatedRowNodes, cellsToFlash, changedPath);
} else {
this.pasteMultipleValues(
parsedData,
currentRow,
updatedRowNodes,
columnsToPasteInto,
cellsToFlash,
EXPORT_TYPE_CLIPBOARD,
changedPath
);
}
}
// if range is active, and only one cell, then we paste this cell into all cells in the active range.
isPasteSingleValueIntoRange(parsedData) {
const rangeSvc = this.beans.rangeSvc;
return this.hasOnlyOneValueToPaste(parsedData) && !!rangeSvc && !rangeSvc.isEmpty();
}
pasteSingleValueIntoRange(parsedData, updatedRowNodes, cellsToFlash, changedPath) {
const value = parsedData[0][0];
const rowCallback = (currentRow, rowNode, columns) => {
updatedRowNodes.push(rowNode);
columns.forEach(
(column) => this.updateCellValue(rowNode, column, value, cellsToFlash, EXPORT_TYPE_CLIPBOARD, changedPath)
);
};
this.iterateActiveRanges(false, rowCallback);
}
hasOnlyOneValueToPaste(parsedData) {
return parsedData.length === 1 && parsedData[0].length === 1;
}
copyRangeDown() {
const { rangeSvc, gos, valueSvc } = this.beans;
if (!rangeSvc || rangeSvc.isEmpty()) {
return;
}
const firstRowValues = [];
const pasteOperation = (cellsToFlash, updatedRowNodes, focusedCell, changedPath) => {
const processCellForClipboardFunc = gos.getCallback("processCellForClipboard");
const processCellFromClipboardFunc = gos.getCallback("processCellFromClipboard");
const rowCallback = (currentRow, rowNode, columns) => {
if (!firstRowValues.length) {
columns.forEach((column) => {
const value = this.processCell(
rowNode,
column,
valueSvc.getValue(column, rowNode),
EXPORT_TYPE_DRAG_COPY,
processCellForClipboardFunc,
false,
true
);
firstRowValues.push(value);
});
} else {
updatedRowNodes.push(rowNode);
columns.forEach((column, index) => {
if (!column.isCellEditable(rowNode) || column.isSuppressPaste(rowNode)) {
return;
}
const firstRowValue = this.processCell(
rowNode,
column,
firstRowValues[index],
EXPORT_TYPE_DRAG_COPY,
processCellFromClipboardFunc,
true
);
this.beans.editSvc?.commitNextEdit();
rowNode.setDataValue(column, firstRowValue, SOURCE_PASTE);
if (changedPath) {
changedPath.addParentNode(rowNode.parent, [column]);
}
const { rowIndex, rowPinned } = currentRow;
const cellId = (0, import_ag_grid_community151._createCellId)({ rowIndex, column, rowPinned });
cellsToFlash[cellId] = true;
});
}
};
this.iterateActiveRanges(true, rowCallback);
};
this.doPasteOperation(pasteOperation);
}
removeLastLineIfBlank(parsedData) {
const lastLine = (0, import_ag_grid_community151._last)(parsedData);
const lastLineIsBlank = lastLine && lastLine.length === 1 && lastLine[0] === "";
if (lastLineIsBlank) {
if (parsedData.length === 1) {
return;
}
(0, import_ag_grid_community151._removeFromArray)(parsedData, lastLine);
}
}
fireRowChanged(rowNodes) {
if (this.gos.get("editType") !== "fullRow") {
return;
}
rowNodes.forEach((rowNode) => {
this.eventSvc.dispatchEvent({
type: "rowValueChanged",
node: rowNode,
data: rowNode.data,
rowIndex: rowNode.rowIndex,
rowPinned: rowNode.rowPinned
});
});
}
pasteMultipleValues(clipboardGridData, currentRow, updatedRowNodes, columnsToPasteInto, cellsToFlash, type, changedPath) {
let rowPointer = currentRow;
const beans = this.beans;
const { gos } = beans;
const skipGroupRows = this.clientSideRowModel != null && !gos.get("enableGroupEdit") && !gos.get("treeData");
const getNextGoodRowNode = () => {
while (true) {
if (!rowPointer) {
return null;
}
const res = (0, import_ag_grid_community151._getRowNode)(beans, rowPointer);
rowPointer = (0, import_ag_grid_community151._getRowBelow)(beans, {
rowPinned: rowPointer.rowPinned,
rowIndex: rowPointer.rowIndex
});
if (res == null) {
return null;
}
const skipRow = res.detail || res.footer || skipGroupRows && res.group;
if (!skipRow) {
return res;
}
}
};
clipboardGridData.forEach((clipboardRowData) => {
const rowNode = getNextGoodRowNode();
if (!rowNode) {
return;
}
clipboardRowData.forEach(
(value, index) => this.updateCellValue(rowNode, columnsToPasteInto[index], value, cellsToFlash, type, changedPath)
);
updatedRowNodes.push(rowNode);
});
}
updateCellValue(rowNode, column, value, cellsToFlash, type, changedPath) {
if (!rowNode || !column || !column.isCellEditable(rowNode) || column.isSuppressPaste(rowNode)) {
return;
}
const processedValue = this.processCell(
rowNode,
column,
value,
type,
this.gos.getCallback("processCellFromClipboard"),
true
);
this.beans.editSvc?.commitNextEdit();
rowNode.setDataValue(column, processedValue, SOURCE_PASTE);
const { rowIndex, rowPinned } = rowNode;
const cellId = (0, import_ag_grid_community151._createCellId)({ rowIndex, column, rowPinned });
cellsToFlash[cellId] = true;
if (changedPath) {
changedPath.addParentNode(rowNode.parent, [column]);
}
}
copyToClipboard(params = {}) {
this.copyOrCutToClipboard(params);
}
cutToClipboard(params = {}, source = "api") {
if (this.gos.get("suppressCutToClipboard")) {
return;
}
this.eventSvc.dispatchEvent({
type: "cutStart",
source
});
this.copyOrCutToClipboard(params, true);
this.eventSvc.dispatchEvent({
type: "cutEnd",
source
});
}
copyOrCutToClipboard(params, cut) {
let { includeHeaders, includeGroupHeaders } = params;
const { gos, focusSvc } = this.beans;
if (includeHeaders == null) {
includeHeaders = gos.get("copyHeadersToClipboard");
}
if (includeGroupHeaders == null) {
includeGroupHeaders = gos.get("copyGroupHeadersToClipboard");
}
const copyParams = { includeHeaders, includeGroupHeaders };
const rowSelection = gos.get("rowSelection");
const cellSelection = gos.get("cellSelection");
let cellClearType = null;
if (this.shouldCopyCells(cellSelection, rowSelection)) {
this.copySelectedRangeToClipboard(copyParams);
cellClearType = 0 /* CellRange */;
} else if (this.shouldCopyRows(rowSelection)) {
this.copySelectedRowsToClipboard(copyParams);
cellClearType = 1 /* SelectedRows */;
} else if (focusSvc.isAnyCellFocused()) {
this.copyFocusedCellToClipboard(copyParams);
cellClearType = 2 /* FocusedCell */;
}
if (cut && cellClearType !== null) {
this.clearCellsAfterCopy(cellClearType);
}
}
shouldCopyCells(cellSelection, rowSelection) {
const { rangeSvc, selectionSvc, gos } = this.beans;
if (!rangeSvc || rangeSvc.isEmpty()) {
return false;
}
if (cellSelection) {
const shouldCopyRowsInstead = typeof rowSelection === "object" && rowSelection.copySelectedRows && !selectionSvc?.isEmpty();
return !shouldCopyRowsInstead;
} else {
const suppressCopySingleCellRanges = gos.get("suppressCopySingleCellRanges");
const shouldSkip = !rangeSvc.isMoreThanOneCell() && suppressCopySingleCellRanges;
return !shouldSkip;
}
}
shouldCopyRows(rowSelection) {
const { selectionSvc, gos } = this.beans;
if (selectionSvc?.isEmpty() ?? true) {
return false;
}
if (rowSelection && typeof rowSelection !== "string") {
return rowSelection.copySelectedRows ?? false;
} else {
return !gos.get("suppressCopyRowsToClipboard");
}
}
clearCellsAfterCopy(type) {
const beans = this.beans;
const { rangeSvc, focusSvc, eventSvc } = beans;
eventSvc.dispatchEvent({ type: "keyShortcutChangedCellStart" });
if (type === 0 /* CellRange */) {
rangeSvc.clearCellRangeCellValues({ cellEventSource: "clipboardSvc" });
} else if (type === 1 /* SelectedRows */) {
this.clearSelectedRows();
} else {
const focusedCell = focusSvc.getFocusedCell();
if (focusedCell == null) {
return;
}
const rowNode = (0, import_ag_grid_community151._getRowNode)(beans, focusedCell);
if (rowNode) {
this.clearCellValue(rowNode, focusedCell.column);
}
}
eventSvc.dispatchEvent({ type: "keyShortcutChangedCellEnd" });
}
clearSelectedRows() {
const { selectionSvc, visibleCols } = this.beans;
const selected = selectionSvc?.getSelectedNodes() ?? [];
const columns = visibleCols.allCols;
for (const row of selected) {
for (const col of columns) {
this.clearCellValue(row, col);
}
}
}
clearCellValue(rowNode, column) {
if (!column.isCellEditable(rowNode)) {
return;
}
const emptyValue = this.beans.valueSvc.getDeleteValue(column, rowNode);
rowNode.setDataValue(column, emptyValue, "clipboardSvc");
}
iterateActiveRanges(onlyFirst, rowCallback, columnCallback) {
const rangeSvc = this.beans.rangeSvc;
if (!rangeSvc || rangeSvc.isEmpty()) {
return;
}
const cellRanges = rangeSvc.getCellRanges();
if (onlyFirst) {
this.iterateActiveRange(cellRanges[0], rowCallback, columnCallback, true);
} else {
cellRanges.forEach(
(range, idx) => this.iterateActiveRange(range, rowCallback, columnCallback, idx === cellRanges.length - 1)
);
}
}
iterateActiveRange(range, rowCallback, columnCallback, isLastRange) {
const { beans } = this;
const { rangeSvc } = beans;
if (!rangeSvc) {
return;
}
let currentRow = rangeSvc.getRangeStartRow(range);
const lastRow = rangeSvc.getRangeEndRow(range);
if (columnCallback && range.columns) {
columnCallback(range.columns);
}
let rangeIndex = 0;
let isLastRow = false;
while (!isLastRow && currentRow != null) {
const rowNode = (0, import_ag_grid_community151._getRowNode)(beans, currentRow);
isLastRow = (0, import_ag_grid_community151._isSameRow)(currentRow, lastRow);
rowCallback(currentRow, rowNode, range.columns, rangeIndex++, isLastRow && isLastRange);
currentRow = (0, import_ag_grid_community151._getRowBelow)(beans, currentRow);
}
}
copySelectedRangeToClipboard(params = {}) {
const rangeSvc = this.beans.rangeSvc;
if (!rangeSvc || rangeSvc.isEmpty()) {
return;
}
const allRangesMerge = rangeSvc.areAllRangesAbleToMerge();
const { data, cellsToFlash } = allRangesMerge ? this.buildDataFromMergedRanges(rangeSvc, params) : this.buildDataFromRanges(rangeSvc, params);
this.copyDataToClipboard(data);
this.dispatchFlashCells(cellsToFlash);
}
buildDataFromMergedRanges(rangeSvc, params) {
const columnsSet = /* @__PURE__ */ new Set();
const ranges = rangeSvc.getCellRanges();
const rowPositionsMap = /* @__PURE__ */ new Map();
const allRowPositions = [];
const allCellsToFlash = {};
ranges.forEach((range) => {
range.columns.forEach((col) => columnsSet.add(col));
const { rowPositions, cellsToFlash } = this.getRangeRowPositionsAndCellsToFlash(rangeSvc, range);
rowPositions.forEach((rowPosition) => {
const rowPositionAsString = `${rowPosition.rowIndex}-${rowPosition.rowPinned || "null"}`;
if (!rowPositionsMap.get(rowPositionAsString)) {
rowPositionsMap.set(rowPositionAsString, true);
allRowPositions.push(rowPosition);
}
});
Object.assign(allCellsToFlash, cellsToFlash);
});
const allColumns = this.beans.visibleCols.allCols;
const exportedColumns = Array.from(columnsSet);
exportedColumns.sort((a, b) => {
const posA = allColumns.indexOf(a);
const posB = allColumns.indexOf(b);
return posA - posB;
});
const data = this.buildExportParams({
columns: exportedColumns,
rowPositions: allRowPositions,
includeHeaders: params.includeHeaders,
includeGroupHeaders: params.includeGroupHeaders
});
return { data, cellsToFlash: allCellsToFlash };
}
buildDataFromRanges(rangeSvc, params) {
const ranges = rangeSvc.getCellRanges();
const data = [];
const allCellsToFlash = {};
ranges.forEach((range) => {
const { rowPositions, cellsToFlash } = this.getRangeRowPositionsAndCellsToFlash(rangeSvc, range);
Object.assign(allCellsToFlash, cellsToFlash);
data.push(
this.buildExportParams({
columns: range.columns,
rowPositions,
includeHeaders: params.includeHeaders,
includeGroupHeaders: params.includeGroupHeaders
})
);
});
return { data: data.join("\n"), cellsToFlash: allCellsToFlash };
}
getRangeRowPositionsAndCellsToFlash(rangeSvc, range) {
const rowPositions = [];
const cellsToFlash = {};
const startRow = rangeSvc.getRangeStartRow(range);
const lastRow = rangeSvc.getRangeEndRow(range);
let node = startRow;
while (node) {
rowPositions.push(node);
range.columns.forEach((column) => {
const { rowIndex, rowPinned } = node;
const cellId = (0, import_ag_grid_community151._createCellId)({ rowIndex, column, rowPinned });
cellsToFlash[cellId] = true;
});
if ((0, import_ag_grid_community151._isSameRow)(node, lastRow)) {
break;
}
node = (0, import_ag_grid_community151._getRowBelow)(this.beans, node);
}
return { rowPositions, cellsToFlash };
}
getCellsToFlashFromRowNodes(rowNodes) {
const allDisplayedColumns = this.beans.visibleCols.allCols;
const cellsToFlash = {};
for (let i = 0; i < rowNodes.length; i++) {
const { level, rowIndex: index, rowPinned, sibling } = rowNodes[i];
const rowIndex = level === -1 ? sibling.rowIndex : index;
if (rowIndex == null) {
continue;
}
for (let j = 0; j < allDisplayedColumns.length; j++) {
const column = allDisplayedColumns[j];
const cellId = (0, import_ag_grid_community151._createCellId)({ rowIndex, column, rowPinned });
cellsToFlash[cellId] = true;
}
}
return cellsToFlash;
}
copyFocusedCellToClipboard(params = {}) {
let focusedCell = this.beans.focusSvc.getFocusedCell();
if (focusedCell == null) {
return;
}
focusedCell = this.beans.rowSpanSvc?.getCellStart(focusedCell) ?? focusedCell;
const cellId = (0, import_ag_grid_community151._createCellId)(focusedCell);
const currentRow = { rowPinned: focusedCell.rowPinned, rowIndex: focusedCell.rowIndex };
const column = focusedCell.column;
const data = this.buildExportParams({
columns: [column],
rowPositions: [currentRow],
includeHeaders: params.includeHeaders,
includeGroupHeaders: params.includeGroupHeaders
});
this.copyDataToClipboard(data);
this.dispatchFlashCells({ [cellId]: true });
}
copySelectedRowsToClipboard(params = {}) {
const { columnKeys, includeHeaders, includeGroupHeaders } = params;
const data = this.buildExportParams({
columns: columnKeys,
includeHeaders,
includeGroupHeaders
});
this.copyDataToClipboard(data);
const rowNodes = this.beans.selectionSvc?.getSelectedNodes() || [];
this.dispatchFlashCells(this.getCellsToFlashFromRowNodes(rowNodes));
}
buildExportParams(params) {
const { columns, rowPositions, includeHeaders = false, includeGroupHeaders = false } = params;
const { gos, csvCreator } = this.beans;
const processRowGroupCallback = ({ node, column }) => {
const { value, valueFormatted } = this.beans.valueSvc.getValueForDisplay(column, node, true);
const val = valueFormatted ?? value ?? "";
const cb = gos.getCallback("processCellForClipboard");
if (!cb) {
return val;
}
return cb({
column,
node,
value: val,
type: EXPORT_TYPE_CLIPBOARD,
formatValue: (valueToFormat) => this.beans.valueSvc.formatValue(column, node, valueToFormat) ?? valueToFormat,
parseValue: (valueToParse) => this.beans.valueSvc.parseValue(column, node, valueToParse, value) ?? valueToParse
});
};
const exportParams = {
columnKeys: columns,
rowPositions,
skipColumnHeaders: !includeHeaders,
skipColumnGroupHeaders: !includeGroupHeaders,
suppressQuotes: true,
columnSeparator: this.getClipboardDelimiter(),
onlySelected: !rowPositions,
processCellCallback: gos.getCallback("processCellForClipboard"),
processRowGroupCallback,
processHeaderCallback: gos.getCallback("processHeaderForClipboard"),
processGroupHeaderCallback: gos.getCallback("processGroupHeaderForClipboard")
};
return csvCreator.getDataAsCsv(exportParams, true);
}
// eslint-disable-next-line @typescript-eslint/ban-types
dispatchFlashCells(cellsToFlash) {
window.setTimeout(() => {
this.eventSvc.dispatchEvent({
type: "flashCells",
cells: cellsToFlash
});
}, 0);
}
processCell(rowNode, column, value, type, func, canParse, canFormat) {
const valueSvc = this.beans.valueSvc;
if (func) {
const params = {
column,
node: rowNode,
value,
type,
formatValue: (valueToFormat) => valueSvc.formatValue(column, rowNode ?? null, valueToFormat) ?? valueToFormat,
parseValue: (valueToParse) => valueSvc.parseValue(column, rowNode ?? null, valueToParse, valueSvc.getValue(column, rowNode))
};
return func(params);
}
if (canParse && column.getColDef().useValueParserForImport !== false) {
return valueSvc.parseValue(column, rowNode ?? null, value, valueSvc.getValue(column, rowNode));
}
if (canFormat && column.getColDef().useValueFormatterForExport !== false) {
return valueSvc.formatValue(column, rowNode ?? null, value) ?? value;
}
return value;
}
copyDataToClipboard(data) {
const userProvidedFunc = this.gos.getCallback("sendToClipboard");
if (userProvidedFunc) {
userProvidedFunc({ data });
return;
}
const allowNavigator = !this.gos.get("suppressClipboardApi");
if (allowNavigator && navigator.clipboard) {
navigator.clipboard.writeText(data).catch((e) => {
(0, import_ag_grid_community151._warn)(40, { e, method: "writeText" });
this.copyDataToClipboardLegacy(data);
});
return;
}
this.copyDataToClipboardLegacy(data);
}
copyDataToClipboardLegacy(data) {
this.executeOnTempElement((element) => {
const eDocument = (0, import_ag_grid_community151._getDocument)(this.beans);
const focusedElementBefore = (0, import_ag_grid_community151._getActiveDomElement)(this.beans);
element.value = data || " ";
element.select();
element.focus({ preventScroll: true });
const result = eDocument.execCommand("copy");
if (!result) {
(0, import_ag_grid_community151._warn)(41);
}
if (focusedElementBefore != null && focusedElementBefore.focus != null) {
focusedElementBefore.focus({ preventScroll: true });
}
});
}
executeOnTempElement(callbackNow, callbackAfter) {
if (!this.gridCtrl) {
return;
}
const eDoc = (0, import_ag_grid_community151._getDocument)(this.beans);
const eTempInput = eDoc.createElement("textarea");
const style = eTempInput.style;
style.width = "1px";
style.height = "1px";
const documentElement = eDoc.documentElement;
style.top = documentElement.scrollTop + "px";
style.left = documentElement.scrollLeft + "px";
style.position = "absolute";
style.opacity = "0";
const guiRoot = this.gridCtrl.getGui();
guiRoot.appendChild(eTempInput);
try {
callbackNow(eTempInput);
} catch (err) {
(0, import_ag_grid_community151._warn)(42);
}
if (callbackAfter) {
window.setTimeout(() => {
callbackAfter(eTempInput);
guiRoot.removeChild(eTempInput);
}, 100);
} else {
guiRoot.removeChild(eTempInput);
}
}
getRangeSize(rangeSvc) {
const ranges = rangeSvc.getCellRanges();
let startRangeIndex = 0;
let endRangeIndex = 0;
if (ranges.length > 0) {
startRangeIndex = rangeSvc.getRangeStartRow(ranges[0]).rowIndex;
endRangeIndex = rangeSvc.getRangeEndRow(ranges[0]).rowIndex;
}
return startRangeIndex - endRangeIndex + 1;
}
};
// packages/ag-grid-enterprise/src/clipboard/clipboardModule.ts
var ClipboardModule = {
moduleName: "Clipboard",
version: VERSION,
beans: [ClipboardService],
apiFunctions: {
copyToClipboard,
cutToClipboard,
copySelectedRowsToClipboard,
copySelectedRangeToClipboard,
copySelectedRangeDown,
pasteFromClipboard
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community152.CsvExportModule, import_ag_grid_community152._KeyboardNavigationModule, import_ag_grid_community152.HighlightChangesModule]
};
// packages/ag-grid-enterprise/src/rowNumbers/rowNumbersModule.ts
var import_ag_grid_community156 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowNumbers/rowNumbers.css-GENERATED.ts
var rowNumbersCSS = (
/*css*/
`.ag-row-number-cell{background-color:var(--ag-header-background-color);border:none;color:var(--ag-header-text-color);font-family:var(--ag-header-font-family);font-size:var(--ag-header-font-size);font-weight:var(--ag-header-font-weight);overflow:hidden;-webkit-user-select:none;-moz-user-select:none;user-select:none;white-space:nowrap;width:100%}:where(.ag-ltr) .ag-row-number-cell{text-align:right}:where(.ag-rtl) .ag-row-number-cell{text-align:left}.ag-row-numbers-resizer{bottom:-2px;cursor:ns-resize;height:4px;position:absolute;width:100%}:where(.ag-ltr) .ag-row-numbers-resizer{left:0}:where(.ag-rtl) .ag-row-numbers-resizer{right:0}.ag-floating-bottom .ag-row-numbers-resizer{bottom:unset;top:-2px}:where(.ag-row-number-header.ag-row-number-selection-enabled){cursor:cell}.ag-row-number-range-highlight{background-color:var(--ag-range-header-highlight-color)}.ag-row-number-range-selected{background-color:var(--ag-row-numbers-selected-color)}:where(.ag-ltr){.ag-row-number-header,:where(.ag-cell.ag-row-number-cell):not(.ag-cell-last-left-pinned){border-right:var(--ag-pinned-column-border)}:where(.ag-cell.ag-row-number-cell.ag-row-number-selection-enabled){cursor:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbDpzcGFjZT0icHJlc2VydmUiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgc3R5bGU9ImZpbGwtcnVsZTpldmVub2RkO2NsaXAtcnVsZTpldmVub2RkO3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZDtzdHJva2UtbWl0ZXJsaW1pdDoxLjUiPjxwYXRoIGQ9Ik0zLjQ0NSA4LjkxMVY3LjQwOUg5Ljc1VjYuMDE0bDIuNTM1IDIuMTQ2LTIuNTM1IDIuMTQ2VjguOTExeiIgc3R5bGU9InN0cm9rZTojZmZmO3N0cm9rZS13aWR0aDouNDFweCIgdHJhbnNmb3JtPSJtYXRyaXgoMS41Nzg0IDAgMCAxLjg2NDI5IC00LjQxMyAtNy4yMTIpIi8+PC9zdmc+"),auto}}:where(.ag-rtl){.ag-row-number-header,:where(.ag-cell.ag-row-number-cell):not(.ag-cell-first-right-pinned){border-left:var(--ag-pinned-column-border)}:where(.ag-cell.ag-row-number-cell.ag-row-number-selection-enabled){cursor:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbDpzcGFjZT0icHJlc2VydmUiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgc3R5bGU9ImZpbGwtcnVsZTpldmVub2RkO2NsaXAtcnVsZTpldmVub2RkO3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZDtzdHJva2UtbWl0ZXJsaW1pdDoxLjUiPjxwYXRoIGQ9Ik01Ljk3OSA4LjkxMXYxLjM5NUwzLjQ0NSA4LjE2bDIuNTM0LTIuMTQ2djEuMzk1aDYuMzA2djEuNTAyeiIgc3R5bGU9InN0cm9rZTojZmZmO3N0cm9rZS13aWR0aDouNDFweCIgdHJhbnNmb3JtPSJtYXRyaXgoMS41Nzg0IDAgMCAxLjg2NDI5IC00LjQxMyAtNy4yMTIpIi8+PC9zdmc+"),auto}}`
);
// packages/ag-grid-enterprise/src/rowNumbers/rowNumbersRowResizer.ts
var import_ag_grid_community153 = require("ag-grid-community");
var RowNumbersRowResizerElement = {
tag: "div",
cls: "ag-row-numbers-resizer"
};
var AgRowNumbersRowResizer = class extends import_ag_grid_community153.Component {
constructor(cellCtrl) {
super(RowNumbersRowResizerElement);
this.cellCtrl = cellCtrl;
this.initialYPosition = -1;
this.dragging = false;
}
postConstruct() {
const { beans, cellCtrl } = this;
const { dragSvc, environment } = beans;
this.defaultRowHeight = environment.getDefaultRowHeight();
dragSvc.addDragSource({
dragStartPixels: 0,
eElement: this.getGui(),
onDragStart: this.onDragStart.bind(this),
onDragging: this.onDragging.bind(this),
onDragStop: this.onDragStop.bind(this),
onDragCancel: this.onDragCancel.bind(this),
includeTouch: true,
stopPropagationForTouch: true
});
const rowPosition = cellCtrl.getRowPosition();
this.node = (0, import_ag_grid_community153._getRowNode)(this.beans, rowPosition);
}
onDragStart(mouseEvent) {
if (!this.node) {
return;
}
const {
beans: { ctrlsSvc, eventSvc }
} = this;
const ctrl = ctrlsSvc.get("gridCtrl");
ctrl.setResizeCursor(import_ag_grid_community153.Direction.Vertical);
this.dragging = true;
this.initialHeight = this.node.rowHeight;
eventSvc.dispatchEvent({
type: "rowResizeStarted",
node: this.node,
event: mouseEvent,
rowHeight: this.initialHeight
});
}
onDragging(mouseEvent) {
let { clientY } = mouseEvent;
if (this.cellCtrl.rowNode.rowPinned === "bottom") {
clientY *= -1;
}
if (this.initialYPosition === -1 || !this.dragging) {
this.initialYPosition = clientY;
return;
}
const { beans, initialHeight, initialYPosition, defaultRowHeight, node } = this;
if (initialHeight == null) {
return;
}
const currentSize = node?.rowHeight;
const newSize = Math.max(initialHeight - (initialYPosition - clientY), defaultRowHeight);
if (currentSize === newSize) {
return;
}
node?.setRowHeight(newSize);
const { rowRenderer, rowModel, pinnedRowModel } = beans;
const pinned = !!node?.rowPinned;
if (pinned) {
rowRenderer.redraw({ afterScroll: true });
}
if (!pinned || pinnedRowModel?.isManual()) {
rowModel.onRowHeightChanged({ animate: false });
}
}
onDragStop(mouseEvent) {
this.beans.eventSvc.dispatchEvent({
type: "rowResizeEnded",
node: this.node,
event: mouseEvent,
rowHeight: this.node?.rowHeight
});
this.clearDragDetails(true);
}
onDragCancel() {
this.clearDragDetails(true);
}
clearDragDetails(fromDragEvent) {
this.initialYPosition = -1;
this.initialHeight = null;
this.dragging = false;
if (fromDragEvent) {
const ctrl = this.beans.ctrlsSvc.get("gridCtrl");
ctrl.setResizeCursor(false);
}
}
destroy() {
this.clearDragDetails(false);
this.node = void 0;
super.destroy();
}
};
// packages/ag-grid-enterprise/src/rowNumbers/rowNumbersService.ts
var import_ag_grid_community155 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rowNumbers/rowNumbersRowResizeFeature.ts
var import_ag_grid_community154 = require("ag-grid-community");
function _isRowNumbersResizerEnabled(gos) {
const rowNumbers = gos.get("rowNumbers");
if (!rowNumbers || typeof rowNumbers !== "object" || !rowNumbers.enableRowResizer) {
return false;
}
return true;
}
var RowNumbersRowResizeFeature = class {
constructor(beans, cellCtrl) {
this.beans = beans;
this.cellCtrl = cellCtrl;
}
refreshRowResizer() {
if (!_isRowNumbersResizerEnabled(this.beans.gos) || !this.isRowResizeSupported(this.cellCtrl.rowNode)) {
this.removeRowResizerFromCellComp();
} else {
this.addResizerToCellComp();
}
}
isRowResizeSupported(node) {
const { pinnedRowModel, rowModel, visibleCols } = this.beans;
const rowModelModelHasOnRowHeightChanged = !!rowModel.onRowHeightChanged;
if (visibleCols.autoHeightCols.length) {
(0, import_ag_grid_community154._warn)(276);
return false;
}
if (node.rowPinned != null) {
return pinnedRowModel?.isManual() ? rowModelModelHasOnRowHeightChanged : true;
}
return rowModelModelHasOnRowHeightChanged;
}
addResizerToCellComp() {
const { beans, cellCtrl } = this;
const { eGui } = cellCtrl;
let { rowResizer } = this;
if (!rowResizer) {
rowResizer = beans.registry.createDynamicBean(
"rowNumberRowResizer",
false,
cellCtrl
);
if (!rowResizer) {
return;
}
this.rowResizer = beans.context.createBean(rowResizer);
}
eGui.appendChild(rowResizer.getGui());
}
removeRowResizerFromCellComp() {
if (!this.rowResizer) {
return;
}
const { eGui } = this.cellCtrl;
eGui.removeChild(this.rowResizer.getGui());
this.rowResizer = this.beans.context.destroyBean(this.rowResizer);
}
destroy() {
this.removeRowResizerFromCellComp();
}
};
// packages/ag-grid-enterprise/src/rowNumbers/rowNumbersService.ts
var RowNumbersService = class extends import_ag_grid_community155.BeanStub {
constructor() {
super(...arguments);
this.beanName = "rowNumbersSvc";
this.isIntegratedWithSelection = false;
this.lastColumnResized = 0;
}
postConstruct() {
const refreshCells_debounced = (0, import_ag_grid_community155._debounce)(this, this.refreshCells.bind(this), 10);
this.addManagedEventListeners({
columnResized: () => {
this.lastColumnResized = Date.now();
},
modelUpdated: (params) => {
refreshCells_debounced(false, !params.keepRenderedRows);
},
rangeSelectionChanged: () => this.refreshCells(true),
pinnedRowsChanged: () => refreshCells_debounced(false, true)
});
this.addManagedPropertyListeners(["rowNumbers", "cellSelection"], (e) => {
this.refreshSelectionIntegration();
this.updateColumns(e);
});
this.refreshSelectionIntegration();
}
addColumns(cols) {
if (this.columns == null) {
return;
}
cols.list = this.columns.list.concat(cols.list);
cols.tree = this.columns.tree.concat(cols.tree);
(0, import_ag_grid_community155._updateColsMap)(cols);
}
createColumns(cols, updateOrders) {
const destroyCollection = () => {
(0, import_ag_grid_community155._destroyColumnTree)(this.beans, this.columns?.tree);
this.columns = null;
};
if (!this.gos.get("rowNumbers")) {
destroyCollection();
return;
}
const newTreeDepth = cols.treeDepth;
const oldTreeDepth = this.columns?.treeDepth ?? -1;
const treeDepthSame = oldTreeDepth == newTreeDepth;
const list = this.generateRowNumberCols();
const areSame = (0, import_ag_grid_community155._areColIdsEqual)(list, this.columns?.list ?? []);
if (areSame && treeDepthSame) {
return;
}
destroyCollection();
const { colGroupSvc } = this.beans;
const treeDepth = colGroupSvc?.findDepth(cols.tree) ?? 0;
const tree = colGroupSvc?.balanceTreeForAutoCols(list, treeDepth) ?? [];
this.columns = {
list,
tree,
treeDepth,
map: {}
};
const putRowNumbersColsFirstInList = (cols2) => {
if (!cols2) {
return null;
}
const colsFiltered = cols2.filter((col) => !(0, import_ag_grid_community155.isRowNumberCol)(col));
return [...list, ...colsFiltered];
};
updateOrders(putRowNumbersColsFirstInList);
}
handleMouseDownOnCell(cellPosition, mouseEvent) {
if (!this.isIntegratedWithSelection || mouseEvent.target.classList.contains("ag-row-numbers-resizer")) {
return false;
}
if (!mouseEvent.shiftKey && !(0, import_ag_grid_community155._interpretAsRightClick)(this.beans, mouseEvent)) {
setTimeout(() => {
this.focusFirstRenderedCellAtRowPosition(cellPosition);
});
}
return true;
}
updateColumns(event) {
const source = (0, import_ag_grid_community155._convertColumnEventSourceType)(event.source);
this.refreshSelectionIntegration();
this.columns?.list.forEach((col) => {
const newColDef = this.createRowNumbersColDef();
col.setColDef(newColDef, null, source);
(0, import_ag_grid_community155._applyColumnState)(this.beans, { state: [{ colId: col.getColId(), ...newColDef }] }, source);
});
}
getColumn() {
return this.columns?.list.find(import_ag_grid_community155.isRowNumberCol) ?? null;
}
getColumns() {
return this.columns?.list ?? null;
}
setupForHeader(comp) {
const { column, eGridHeader } = comp.params;
if (!(0, import_ag_grid_community155.isRowNumberCol)(column)) {
return;
}
(0, import_ag_grid_community155._setAriaLabel)(eGridHeader, "Row Number");
this.addManagedElementListeners(eGridHeader, {
click: this.onHeaderClick.bind(this),
keydown: this.onHeaderKeyDown.bind(this),
focus: this.onHeaderFocus.bind(this)
});
}
createRowNumbersRowResizerFeature(beans, ctrl) {
if (!_isRowNumbersResizerEnabled(this.gos)) {
return void 0;
}
return new RowNumbersRowResizeFeature(beans, ctrl);
}
refreshSelectionIntegration() {
const { beans } = this;
const { gos, rangeSvc } = beans;
const cellSelection = gos.get("cellSelection");
this.refreshRowNumberOverrides();
this.isIntegratedWithSelection = !!rangeSvc && !!cellSelection && !this.isSuppressCellSelectionIntegration;
}
refreshRowNumberOverrides() {
const rowNumbers = this.gos.get("rowNumbers");
this.rowNumberOverrides = {};
if (!rowNumbers || typeof rowNumbers !== "object") {
return;
}
if (rowNumbers.suppressCellSelectionIntegration) {
this.isSuppressCellSelectionIntegration = true;
}
const colDefValidProps = [
"contextMenuItems",
"context",
"onCellClicked",
"onCellContextMenu",
"onCellDoubleClicked",
"headerTooltip",
"headerStyle",
"headerComponent",
"headerComponentParams",
"suppressHeaderKeyboardEvent",
"tooltipField",
"tooltipValueGetter",
"tooltipComponent",
"tooltipComponentParams",
"valueGetter",
"valueFormatter",
"width",
"maxWidth",
"minWidth",
"resizable"
];
for (const prop of colDefValidProps) {
if (rowNumbers[prop] != null) {
this.rowNumberOverrides[prop] = rowNumbers[prop];
}
}
}
onHeaderFocus() {
this.beans.ariaAnnounce?.announceValue("Press Space to select all cells", "ariaSelectAllCells");
}
onHeaderKeyDown(e) {
if (!this.isIntegratedWithSelection || e.key !== import_ag_grid_community155.KeyCode.SPACE) {
return;
}
(0, import_ag_grid_community155._selectAllCells)(this.beans);
}
onHeaderClick(_e) {
if (Date.now() - this.lastColumnResized < 100 || !this.isIntegratedWithSelection || this.getColumn()?.resizing) {
return;
}
(0, import_ag_grid_community155._selectAllCells)(this.beans);
}
refreshCells(force, runAutoSize) {
const column = this.getColumn();
if (!column) {
return;
}
if (runAutoSize) {
const width = this.beans.autoWidthCalc?.getPreferredWidthForElements([this.createDummyElement(column)], 2);
if (width != null) {
this.beans.colResize?.setColumnWidths(
[{ key: column, newWidth: width }],
false,
true,
"rowNumbersService"
);
}
}
this.beans.rowRenderer.refreshCells({
columns: [column],
force
});
}
createDummyElement(column) {
const div = (0, import_ag_grid_community155._createElement)({ tag: "div", cls: "ag-cell-value ag-cell" });
let value = String(this.beans.rowModel.getRowCount() + 1);
if (typeof this.rowNumberOverrides.valueFormatter === "function") {
const valueFormatterParams = (0, import_ag_grid_community155._addGridCommonParams)(this.beans.gos, {
data: void 0,
value,
node: null,
column,
colDef: column.colDef
});
value = this.rowNumberOverrides.valueFormatter(valueFormatterParams);
}
div.textContent = value;
return div;
}
createRowNumbersColDef() {
const { gos, contextMenuSvc } = this.beans;
const enableRTL = gos.get("enableRtl");
return {
// overridable properties
minWidth: 60,
width: 60,
resizable: false,
valueGetter: this.valueGetter,
contextMenuItems: this.isIntegratedWithSelection || !contextMenuSvc ? void 0 : () => [],
// overrides
...this.rowNumberOverrides,
// non-overridable properties
colId: import_ag_grid_community155.ROW_NUMBERS_COLUMN_ID,
chartDataType: "excluded",
suppressHeaderMenuButton: true,
sortable: false,
suppressMovable: true,
lockPinned: true,
pinned: enableRTL ? "right" : "left",
lockPosition: enableRTL ? "right" : "left",
editable: false,
suppressFillHandle: true,
suppressAutoSize: true,
suppressSizeToFit: true,
suppressHeaderContextMenu: true,
suppressNavigable: true,
headerClass: this.getHeaderClass(),
cellClass: this.getCellClass.bind(this),
cellAriaRole: "rowheader"
};
}
valueGetter(params) {
const node = params.node;
if (node?.rowPinned && node.pinnedSibling) {
const { rowIndex } = node.pinnedSibling;
return `${rowIndex == null ? "-" : rowIndex + 1}`;
}
return String((node?.rowIndex || 0) + 1);
}
getHeaderClass() {
const cssClass = ["ag-row-number-header"];
if (this.isIntegratedWithSelection) {
cssClass.push("ag-row-number-selection-enabled");
}
return cssClass;
}
getCellClass(params) {
const { beans } = this;
const { rangeSvc, gos } = beans;
const { node } = params;
const cssClasses = ["ag-row-number-cell"];
const cellSelection = gos.get("cellSelection");
if (!rangeSvc || !cellSelection) {
return cssClasses;
}
if (this.isIntegratedWithSelection) {
cssClasses.push("ag-row-number-selection-enabled");
}
const ranges = rangeSvc.getCellRanges();
if (!ranges.length) {
return cssClasses;
}
const allColsLen = this.beans.visibleCols.allCols.length - 1;
const shouldHighlight = typeof cellSelection === "object" && cellSelection.enableHeaderHighlight;
for (const range of ranges) {
if (rangeSvc.isRowInRange(node.rowIndex, node.rowPinned, range)) {
if (shouldHighlight) {
cssClasses.push("ag-row-number-range-highlight");
}
if (range.columns.length === allColsLen) {
cssClasses.push("ag-row-number-range-selected");
}
}
}
return cssClasses;
}
generateRowNumberCols() {
const { gos } = this;
if (!gos.get("rowNumbers")) {
return [];
}
const colDef = this.createRowNumbersColDef();
const colId = colDef.colId;
gos.validateColDef(colDef, colId, true);
const col = new import_ag_grid_community155.AgColumn(colDef, null, colId, false);
this.createBean(col);
return [col];
}
// focus is disabled on the Row Numbers cells, when a click happens on it,
// it should focus the first cell of that row.
focusFirstRenderedCellAtRowPosition(rowPosition) {
const { beans, gos } = this;
const { visibleCols, colViewport } = beans;
const pinnedCols = gos.get("enableRtl") ? visibleCols.rightCols : visibleCols.leftCols;
let columns;
if (pinnedCols.length == 1) {
const rowNode = (0, import_ag_grid_community155._getRowNode)(beans, rowPosition);
if (!rowNode) {
return;
}
columns = colViewport.getColsWithinViewport(rowNode);
} else {
columns = pinnedCols;
}
const column = columns.find((col) => !(0, import_ag_grid_community155.isRowNumberCol)(col));
if (!column) {
return;
}
const { rowPinned, rowIndex } = rowPosition;
beans.focusSvc.setFocusedCell({
rowIndex,
rowPinned,
column,
forceBrowserFocus: true,
preventScrollOnBrowserFocus: true
});
}
destroy() {
(0, import_ag_grid_community155._destroyColumnTree)(this.beans, this.columns?.tree);
this.rowNumberOverrides = null;
super.destroy();
}
};
// packages/ag-grid-enterprise/src/rowNumbers/rowNumbersModule.ts
var RowNumbersModule = {
moduleName: "RowNumbers",
version: VERSION,
beans: [RowNumbersService],
dynamicBeans: { rowNumberRowResizer: AgRowNumbersRowResizer },
dependsOn: [EnterpriseCoreModule, import_ag_grid_community156.CellStyleModule, import_ag_grid_community156._SharedDragAndDropModule],
css: [rowNumbersCSS]
};
// packages/ag-grid-enterprise/src/filterToolPanel/filtersToolPanelModule.ts
var import_ag_grid_community172 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/filterToolPanel/filtersToolPanel.ts
var import_ag_grid_community161 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/filterToolPanel/agFiltersToolPanelHeader.ts
var import_ag_grid_community157 = require("ag-grid-community");
var AgFiltersToolPanelHeaderElement = {
tag: "div",
cls: "ag-filter-toolpanel-search",
role: "presentation",
children: [
{
tag: "div",
ref: "eExpand",
cls: "ag-filter-toolpanel-expand"
},
{
tag: "ag-input-text-field",
ref: "eFilterTextField",
cls: "ag-filter-toolpanel-search-input"
}
]
};
var AgFiltersToolPanelHeader = class extends import_ag_grid_community157.Component {
constructor() {
super(...arguments);
this.eExpand = import_ag_grid_community157.RefPlaceholder;
this.eFilterTextField = import_ag_grid_community157.RefPlaceholder;
}
postConstruct() {
this.setTemplate(AgFiltersToolPanelHeaderElement, [import_ag_grid_community157.AgInputTextFieldSelector]);
const translate = this.getLocaleTextFunc();
this.eFilterTextField.setAutoComplete(false).setInputAriaLabel(translate("ariaFilterColumnsInput", "Filter Columns Input")).onValueChange(this.onSearchTextChanged.bind(this));
this.createExpandIcons();
this.setExpandState(0 /* EXPANDED */);
this.addManagedElementListeners(this.eExpand, { click: this.onExpandClicked.bind(this) });
this.addManagedEventListeners({ newColumnsLoaded: this.showOrHideOptions.bind(this) });
}
init(params) {
this.params = params;
if (this.beans.colModel.ready) {
this.showOrHideOptions();
}
}
createExpandIcons() {
const { eExpand, beans } = this;
eExpand.appendChild(this.eExpandChecked = (0, import_ag_grid_community157._createIconNoSpan)("accordionOpen", beans));
eExpand.appendChild(this.eExpandUnchecked = (0, import_ag_grid_community157._createIconNoSpan)("accordionClosed", beans));
eExpand.appendChild(this.eExpandIndeterminate = (0, import_ag_grid_community157._createIconNoSpan)("accordionIndeterminate", beans));
}
// we only show expand / collapse if we are showing filters
showOrHideOptions() {
const { params, eFilterTextField } = this;
const showFilterSearch = !params.suppressFilterSearch;
const showExpand = !params.suppressExpandAll;
const translate = this.getLocaleTextFunc();
eFilterTextField.setInputPlaceholder(translate("searchOoo", "Search..."));
const isFilterGroupPresent = (col) => col.getOriginalParent() && col.isFilterAllowed();
const filterGroupsPresent = this.beans.colModel.getCols().some(isFilterGroupPresent);
(0, import_ag_grid_community157._setDisplayed)(eFilterTextField.getGui(), showFilterSearch);
(0, import_ag_grid_community157._setDisplayed)(this.eExpand, showExpand && filterGroupsPresent);
}
onSearchTextChanged() {
if (!this.onSearchTextChangedDebounced) {
this.onSearchTextChangedDebounced = (0, import_ag_grid_community157._debounce)(
this,
() => this.dispatchLocalEvent({ type: "searchChanged", searchText: this.eFilterTextField.getValue() }),
300
);
}
this.onSearchTextChangedDebounced();
}
onExpandClicked() {
const event = this.currentExpandState === 0 /* EXPANDED */ ? { type: "collapseAll" } : { type: "expandAll" };
this.dispatchLocalEvent(event);
}
setExpandState(state) {
this.currentExpandState = state;
(0, import_ag_grid_community157._setDisplayed)(this.eExpandChecked, state === 0 /* EXPANDED */);
(0, import_ag_grid_community157._setDisplayed)(this.eExpandUnchecked, state === 1 /* COLLAPSED */);
(0, import_ag_grid_community157._setDisplayed)(this.eExpandIndeterminate, state === 2 /* INDETERMINATE */);
}
};
var AgFiltersToolPanelHeaderSelector = {
selector: "AG-FILTERS-TOOL-PANEL-HEADER",
component: AgFiltersToolPanelHeader
};
// packages/ag-grid-enterprise/src/filterToolPanel/agFiltersToolPanelList.ts
var import_ag_grid_community160 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/filterToolPanel/toolPanelFilterComp.ts
var import_ag_grid_community158 = require("ag-grid-community");
var ToolPanelFilterElement = {
tag: "div",
cls: "ag-filter-toolpanel-instance",
children: [
{
tag: "div",
ref: "eFilterToolPanelHeader",
cls: "ag-filter-toolpanel-header ag-filter-toolpanel-instance-header",
role: "button",
attrs: { "aria-expanded": "false" },
children: [
{ tag: "div", ref: "eExpand", cls: "ag-filter-toolpanel-expand" },
{ tag: "span", ref: "eFilterName", cls: "ag-header-cell-text" },
{
tag: "span",
ref: "eFilterIcon",
cls: "ag-header-icon ag-filter-icon ag-filter-toolpanel-instance-header-icon",
attrs: { "aria-hidden": "true" }
}
]
},
{ tag: "div", ref: "agFilterToolPanelBody", cls: "ag-filter-toolpanel-instance-body ag-filter" }
]
};
var ToolPanelFilterComp = class extends import_ag_grid_community158.Component {
constructor(hideHeader, expandedCallback) {
super(ToolPanelFilterElement);
this.hideHeader = hideHeader;
this.expandedCallback = expandedCallback;
this.eFilterToolPanelHeader = import_ag_grid_community158.RefPlaceholder;
this.eFilterName = import_ag_grid_community158.RefPlaceholder;
this.agFilterToolPanelBody = import_ag_grid_community158.RefPlaceholder;
this.eFilterIcon = import_ag_grid_community158.RefPlaceholder;
this.eExpand = import_ag_grid_community158.RefPlaceholder;
this.expanded = false;
}
postConstruct() {
const { beans, eExpand } = this;
const eExpandChecked = (0, import_ag_grid_community158._createIconNoSpan)("accordionOpen", beans);
this.eExpandChecked = eExpandChecked;
const eExpandUnchecked = (0, import_ag_grid_community158._createIconNoSpan)("accordionClosed", beans);
this.eExpandUnchecked = eExpandUnchecked;
eExpand.appendChild(eExpandChecked);
eExpand.appendChild(eExpandUnchecked);
}
setColumn(column) {
this.column = column;
const { beans, eFilterToolPanelHeader, eFilterIcon, eExpandChecked, hideHeader } = this;
this.eFilterName.innerText = beans.colNames.getDisplayNameForColumn(column, "filterToolPanel", false) || "";
this.addManagedListeners(eFilterToolPanelHeader, {
click: this.toggleExpanded.bind(this),
keydown: this.onKeyDown.bind(this)
});
this.addManagedEventListeners({ filterOpened: this.onFilterOpened.bind(this) });
this.addInIcon("filterActive", eFilterIcon, column);
(0, import_ag_grid_community158._setDisplayed)(eFilterIcon, this.isFilterActive(), { skipAriaHidden: true });
(0, import_ag_grid_community158._setDisplayed)(eExpandChecked, false);
if (hideHeader) {
(0, import_ag_grid_community158._setDisplayed)(eFilterToolPanelHeader, false);
eFilterToolPanelHeader.removeAttribute("tabindex");
} else {
eFilterToolPanelHeader.setAttribute("tabindex", "0");
}
this.addManagedListeners(column, { filterChanged: this.onFilterChanged.bind(this) });
}
onKeyDown(e) {
const { key } = e;
const { ENTER, SPACE, LEFT, RIGHT } = import_ag_grid_community158.KeyCode;
if (key !== ENTER && key !== SPACE && key !== LEFT && key !== RIGHT) {
return;
}
e.preventDefault();
if (key === ENTER || key === SPACE) {
this.toggleExpanded();
} else if (key === import_ag_grid_community158.KeyCode.LEFT) {
this.collapse();
} else {
this.expand();
}
}
getColumn() {
return this.column;
}
getColumnFilterName() {
return this.beans.colNames.getDisplayNameForColumn(this.column, "filterToolPanel", false);
}
addCssClassToTitleBar(cssClass) {
this.eFilterToolPanelHeader.classList.add(cssClass);
}
addInIcon(iconName, eParent, column) {
if (eParent == null) {
return;
}
const eIcon = (0, import_ag_grid_community158._createIconNoSpan)(iconName, this.beans, column);
eParent.appendChild(eIcon);
}
isFilterActive() {
return !!this.beans.colFilter?.isFilterActive(this.column);
}
onFilterChanged() {
(0, import_ag_grid_community158._setDisplayed)(this.eFilterIcon, this.isFilterActive(), { skipAriaHidden: true });
this.dispatchLocalEvent({ type: "filterChanged" });
}
toggleExpanded() {
this.expanded ? this.collapse() : this.expand();
}
expand() {
if (this.expanded) {
return;
}
this.expanded = true;
(0, import_ag_grid_community158._setAriaExpanded)(this.eFilterToolPanelHeader, true);
(0, import_ag_grid_community158._setDisplayed)(this.eExpandChecked, true);
(0, import_ag_grid_community158._setDisplayed)(this.eExpandUnchecked, false);
this.addFilterElement();
this.expandedCallback();
}
addFilterElement(suppressFocus) {
const filterPanelWrapper = (0, import_ag_grid_community158._createElement)({ tag: "div", cls: "ag-filter-toolpanel-instance-filter" });
const comp = this.createManagedBean(new import_ag_grid_community158.FilterComp(this.column, "TOOLBAR"));
this.filterComp = comp;
if (!comp.hasFilter()) {
return;
}
comp.getFilter()?.then((filter) => {
this.underlyingFilter = filter;
if (!filter) {
return;
}
filterPanelWrapper.appendChild(comp.getGui());
this.agFilterToolPanelBody.appendChild(filterPanelWrapper);
comp.afterGuiAttached({ container: "toolPanel", suppressFocus });
});
}
collapse() {
if (!this.expanded) {
return;
}
this.expanded = false;
(0, import_ag_grid_community158._setAriaExpanded)(this.eFilterToolPanelHeader, false);
this.removeFilterElement();
(0, import_ag_grid_community158._setDisplayed)(this.eExpandChecked, false);
(0, import_ag_grid_community158._setDisplayed)(this.eExpandUnchecked, true);
const filterComp = this.filterComp;
filterComp?.afterGuiDetached();
this.destroyBean(filterComp);
this.expandedCallback();
}
removeFilterElement() {
(0, import_ag_grid_community158._clearElement)(this.agFilterToolPanelBody);
}
isExpanded() {
return this.expanded;
}
onPanelHidden() {
if (!this.expanded) {
return;
}
const filter = this.underlyingFilter;
if (!filter) {
return;
}
filter.afterGuiDetached?.();
}
onFilterOpened(event) {
if (event.source !== "COLUMN_MENU") {
return;
}
if (event.column !== this.column) {
return;
}
if (!this.expanded) {
return;
}
this.collapse();
}
};
// packages/ag-grid-enterprise/src/filterToolPanel/toolPanelFilterGroupComp.ts
var import_ag_grid_community159 = require("ag-grid-community");
var ToolPanelFilterGroupComp = class extends import_ag_grid_community159.Component {
constructor(columnGroup, childFilterComps, expandedCallback, depth, showingColumn) {
super();
this.columnGroup = columnGroup;
this.childFilterComps = childFilterComps;
this.expandedCallback = expandedCallback;
this.depth = depth;
this.showingColumn = showingColumn;
this.filterGroupComp = import_ag_grid_community159.RefPlaceholder;
}
postConstruct() {
const groupParams = {
cssIdentifier: "filter-toolpanel",
direction: "vertical"
};
this.setTemplate(
{
tag: "div",
cls: "ag-filter-toolpanel-group-wrapper",
children: [{ tag: "ag-group-component", ref: "filterGroupComp" }]
},
[AgGroupComponentSelector],
{ filterGroupComp: groupParams }
);
this.setGroupTitle();
const { filterGroupComp, depth, childFilterComps, gos } = this;
filterGroupComp.setAlignItems("stretch");
filterGroupComp.addCss(`ag-filter-toolpanel-group-level-${depth}`);
filterGroupComp.getGui().style.setProperty("--ag-indentation-level", String(depth));
filterGroupComp.addCssClassToTitleBar(`ag-filter-toolpanel-group-level-${depth}-header`);
childFilterComps.forEach((filterComp) => {
filterGroupComp.addItem(filterComp);
filterComp.addCssClassToTitleBar(`ag-filter-toolpanel-group-level-${depth + 1}-header`);
filterComp.getGui().style.setProperty("--ag-indentation-level", String(depth + 1));
});
const column = this.showingColumn ? this.columnGroup : void 0;
this.tooltipFeature = this.createOptionalManagedBean(
this.beans.registry.createDynamicBean("tooltipFeature", false, {
getGui: () => this.getGui(),
getLocation: () => "filterToolPanelColumnGroup",
shouldDisplayTooltip: (0, import_ag_grid_community159._getShouldDisplayTooltip)(
gos,
() => filterGroupComp.getGui().querySelector(".ag-group-title")
),
getColDef: column ? () => column.getColDef() : void 0,
getColumn: column ? () => column : void 0
})
);
this.refreshFilterClass();
this.addExpandCollapseListeners();
this.addFilterChangedListeners();
this.setupTooltip();
this.addInIcon("filterActive");
}
setupTooltip() {
if (!this.showingColumn) {
return;
}
const refresh = () => {
this.tooltipFeature?.setTooltipAndRefresh(this.columnGroup.getColDef().headerTooltip);
};
refresh();
this.addManagedEventListeners({ newColumnsLoaded: refresh });
}
addCssClassToTitleBar(cssClass) {
this.filterGroupComp.addCssClassToTitleBar(cssClass);
}
onPanelHidden() {
this.childFilterComps.forEach((filterComp) => filterComp.onPanelHidden());
}
isColumnGroup() {
return (0, import_ag_grid_community159.isProvidedColumnGroup)(this.columnGroup);
}
isExpanded() {
return this.filterGroupComp.isExpanded();
}
getChildren() {
return this.childFilterComps;
}
getFilterGroupName() {
return this.filterGroupName ?? "";
}
getFilterGroupId() {
return this.columnGroup.getId();
}
hideGroupItem(hide, index) {
this.filterGroupComp.hideItem(hide, index);
}
hideGroup(hide) {
this.setDisplayed(!hide);
}
addInIcon(iconName) {
const eIcon = (0, import_ag_grid_community159._createIconNoSpan)(iconName, this.beans);
if (eIcon) {
eIcon.classList.add("ag-filter-toolpanel-group-instance-header-icon");
}
this.filterGroupComp.addTitleBarWidget(eIcon);
}
forEachToolPanelFilterChild(action) {
this.childFilterComps.forEach((filterComp) => {
if (filterComp instanceof ToolPanelFilterComp) {
action(filterComp);
}
});
}
addExpandCollapseListeners() {
const expandListener = this.isColumnGroup() ? () => this.expandedCallback() : () => this.forEachToolPanelFilterChild((filterComp) => filterComp.expand());
const collapseListener = this.isColumnGroup() ? () => this.expandedCallback() : () => this.forEachToolPanelFilterChild((filterComp) => filterComp.collapse());
this.addManagedListeners(this.filterGroupComp, {
expanded: expandListener,
collapsed: collapseListener
});
}
getColumns() {
if ((0, import_ag_grid_community159.isProvidedColumnGroup)(this.columnGroup)) {
return this.columnGroup.getLeafColumns();
}
return [this.columnGroup];
}
addFilterChangedListeners() {
this.getColumns().forEach((column) => {
this.addManagedListeners(column, { filterChanged: () => this.refreshFilterClass() });
});
if (!(0, import_ag_grid_community159.isProvidedColumnGroup)(this.columnGroup)) {
this.addManagedEventListeners({ filterOpened: this.onFilterOpened.bind(this) });
}
}
refreshFilterClass() {
const columns = this.getColumns();
const anyChildFiltersActive = () => columns.some((col) => col.isFilterActive());
this.filterGroupComp.toggleCss("ag-has-filter", anyChildFiltersActive());
}
onFilterOpened(event) {
if (event.source !== "COLUMN_MENU") {
return;
}
if (event.column !== this.columnGroup) {
return;
}
if (!this.isExpanded()) {
return;
}
this.collapse();
}
expand() {
this.filterGroupComp.toggleGroupExpand(true);
}
collapse() {
this.filterGroupComp.toggleGroupExpand(false);
}
setGroupTitle() {
const columnGroup = this.columnGroup;
const filterGroupName = (0, import_ag_grid_community159.isProvidedColumnGroup)(columnGroup) ? this.getColumnGroupName(columnGroup) : this.getColumnName(columnGroup);
this.filterGroupName = filterGroupName;
this.filterGroupComp.setTitle(filterGroupName || "");
}
getColumnGroupName(columnGroup) {
return this.beans.colNames.getDisplayNameForProvidedColumnGroup(null, columnGroup, "filterToolPanel");
}
getColumnName(column) {
return this.beans.colNames.getDisplayNameForColumn(column, "filterToolPanel", false);
}
destroyFilters() {
this.childFilterComps = this.destroyBeans(this.childFilterComps);
(0, import_ag_grid_community159._clearElement)(this.getGui());
}
destroy() {
this.destroyFilters();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/filterToolPanel/agFiltersToolPanelList.ts
var AgFiltersToolPanelList = class extends import_ag_grid_community160.Component {
constructor() {
super({ tag: "div", cls: "ag-filter-list-panel" });
this.initialised = false;
this.hasLoadedInitialState = false;
this.isInitialState = false;
this.filterGroupComps = [];
// If a column drag is happening, we suppress handling the event until it has completed
this.suppressOnColumnsChanged = false;
this.onColumnsChangedPending = false;
}
wireBeans(beans) {
this.colModel = beans.colModel;
}
init(params) {
this.initialised = true;
const defaultParams = (0, import_ag_grid_community160._addGridCommonParams)(this.gos, {
suppressExpandAll: false,
suppressFilterSearch: false,
suppressSyncLayoutWithGrid: false
});
(0, import_ag_grid_community160._mergeDeep)(defaultParams, params);
this.params = defaultParams;
if (!defaultParams.suppressSyncLayoutWithGrid) {
this.addManagedEventListeners({ columnMoved: () => this.onColumnsChanged() });
}
this.addManagedEventListeners({
newColumnsLoaded: () => this.onColumnsChanged(),
toolPanelVisibleChanged: (event) => {
if (event.key === "filters" && !event.visible) {
this.onPanelHidden();
}
},
dragStarted: () => {
this.suppressOnColumnsChanged = true;
},
dragStopped: () => {
this.suppressOnColumnsChanged = false;
if (this.onColumnsChangedPending) {
this.onColumnsChangedPending = false;
this.onColumnsChanged();
}
}
});
if (this.colModel.ready) {
this.onColumnsChanged();
}
}
onColumnsChanged() {
if (this.suppressOnColumnsChanged) {
this.onColumnsChangedPending = true;
return;
}
const pivotModeActive = this.colModel.isPivotMode();
const shouldSyncColumnLayoutWithGrid = !this.params.suppressSyncLayoutWithGrid && !pivotModeActive;
shouldSyncColumnLayoutWithGrid ? this.syncFilterLayout() : this.buildTreeFromProvidedColumnDefs();
this.refreshAriaLabel();
}
syncFilterLayout() {
syncLayoutWithGrid(this.colModel, this.setFiltersLayout.bind(this));
this.refreshAriaLabel();
}
buildTreeFromProvidedColumnDefs() {
const columnTree = this.colModel.getColDefColTree();
this.recreateFilters(columnTree);
}
setFiltersLayout(colDefs) {
const columnTree = toolPanelCreateColumnTree(this.colModel, colDefs);
this.recreateFilters(columnTree);
}
recreateFilters(columnTree) {
const activeElement = (0, import_ag_grid_community160._getActiveDomElement)(this.beans);
if (!this.hasLoadedInitialState) {
this.hasLoadedInitialState = true;
this.isInitialState = !!this.params.initialState;
}
const expansionState = this.getExpansionState();
this.destroyFilters();
const filterGroupComps = this.recursivelyAddComps(columnTree, 0, expansionState);
this.filterGroupComps = filterGroupComps;
const len = filterGroupComps.length;
if (len) {
filterGroupComps.forEach((comp) => this.appendChild(comp));
this.setFirstAndLastVisible(0, len - 1);
}
const searchFilterText = this.searchFilterText;
if ((0, import_ag_grid_community160._exists)(searchFilterText)) {
this.searchFilters(searchFilterText);
}
this.fireExpandedEvent();
if (this.getGui().contains(activeElement)) {
activeElement.focus();
}
this.isInitialState = false;
this.refreshAriaLabel();
}
recursivelyAddComps(tree, depth, expansionState) {
return tree.map((child) => {
if ((0, import_ag_grid_community160.isProvidedColumnGroup)(child)) {
return this.recursivelyAddFilterGroupComps(child, depth, expansionState)?.flatMap((a) => a) ?? [];
}
const column = child;
if (!this.shouldDisplayFilter(column)) {
return [];
}
const hideFilterCompHeader = depth === 0;
const filterComp = new ToolPanelFilterComp(hideFilterCompHeader, () => this.onFilterExpanded());
this.createBean(filterComp);
filterComp.setColumn(column);
if (expansionState.get(column.getId())) {
filterComp.expand();
}
if (depth > 0) {
return filterComp;
}
const filterGroupComp = this.createBean(
new ToolPanelFilterGroupComp(column, [filterComp], this.onGroupExpanded.bind(this), depth, true)
);
filterGroupComp.addCssClassToTitleBar("ag-filter-toolpanel-header");
if (!expansionState.get(filterGroupComp.getFilterGroupId())) {
filterGroupComp.collapse();
}
return filterGroupComp;
}).flatMap((a) => a);
}
refreshAriaLabel() {
const translate = this.getLocaleTextFunc();
const filterListName = translate("ariaFilterPanelList", "Filter List");
const localeFilters = translate("filters", "Filters");
const eGui = this.getGui();
const groupSelector = ".ag-filter-toolpanel-group-wrapper";
const itemSelector = ".ag-filter-toolpanel-group-item";
const hiddenSelector = ".ag-hidden";
const visibleItems = eGui.querySelectorAll(`${itemSelector}:not(${groupSelector}, ${hiddenSelector})`);
const totalVisibleItems = visibleItems.length;
(0, import_ag_grid_community160._setAriaLabel)(this.getAriaElement(), `${filterListName} ${totalVisibleItems} ${localeFilters}`);
}
recursivelyAddFilterGroupComps(columnGroup, depth, expansionState) {
if (!this.filtersExistInChildren(columnGroup.getChildren())) {
return;
}
const colGroupDef = columnGroup.getColGroupDef();
if (colGroupDef && colGroupDef.suppressFiltersToolPanel) {
return [];
}
const newDepth = columnGroup.isPadding() ? depth : depth + 1;
const childFilterComps = this.recursivelyAddComps(columnGroup.getChildren(), newDepth, expansionState).flatMap(
(a) => a
);
if (columnGroup.isPadding()) {
return childFilterComps;
}
const filterGroupComp = new ToolPanelFilterGroupComp(
columnGroup,
childFilterComps,
this.onGroupExpanded.bind(this),
depth,
false
);
this.createBean(filterGroupComp);
filterGroupComp.addCssClassToTitleBar("ag-filter-toolpanel-header");
const expansionStateValue = expansionState.get(filterGroupComp.getFilterGroupId());
if (this.isInitialState && !expansionStateValue || expansionStateValue === false) {
filterGroupComp.collapse();
}
return [filterGroupComp];
}
filtersExistInChildren(tree) {
return tree.some((child) => {
if ((0, import_ag_grid_community160.isProvidedColumnGroup)(child)) {
return this.filtersExistInChildren(child.getChildren());
}
return this.shouldDisplayFilter(child);
});
}
shouldDisplayFilter(column) {
const suppressFiltersToolPanel = column.getColDef() && column.getColDef().suppressFiltersToolPanel;
return column.isFilterAllowed() && !suppressFiltersToolPanel;
}
getExpansionState() {
const expansionState = /* @__PURE__ */ new Map();
if (this.isInitialState) {
const { expandedColIds, expandedGroupIds } = this.params.initialState;
expandedColIds.forEach((id) => expansionState.set(id, true));
expandedGroupIds.forEach((id) => expansionState.set(id, true));
return expansionState;
}
const recursiveGetExpansionState = (filterGroupComp) => {
expansionState.set(filterGroupComp.getFilterGroupId(), filterGroupComp.isExpanded());
filterGroupComp.getChildren().forEach((child) => {
if (child instanceof ToolPanelFilterGroupComp) {
recursiveGetExpansionState(child);
} else {
expansionState.set(child.getColumn().getId(), child.isExpanded());
}
});
};
this.filterGroupComps.forEach(recursiveGetExpansionState);
return expansionState;
}
// we don't support refreshing, but must implement because it's on the tool panel interface
refresh() {
}
// lazy initialise the panel
setVisible(visible) {
super.setDisplayed(visible);
if (visible && !this.initialised) {
this.init(this.params);
}
}
expandFilterGroups(expand, groupIds) {
const updatedGroupIds = [];
const updateGroupExpandState = (filterGroup) => {
const groupId = filterGroup.getFilterGroupId();
const shouldExpandOrCollapse = !groupIds || groupIds.includes(groupId);
if (shouldExpandOrCollapse) {
if (expand && filterGroup.isColumnGroup()) {
filterGroup.expand();
} else {
filterGroup.collapse();
}
updatedGroupIds.push(groupId);
}
filterGroup.getChildren().forEach((child) => {
if (child instanceof ToolPanelFilterGroupComp) {
updateGroupExpandState(child);
}
});
};
this.filterGroupComps.forEach(updateGroupExpandState);
this.onGroupExpanded();
if (groupIds) {
const unrecognisedGroupIds = groupIds.filter((groupId) => updatedGroupIds.indexOf(groupId) < 0);
if (unrecognisedGroupIds.length > 0) {
(0, import_ag_grid_community160._warn)(166, { unrecognisedGroupIds });
}
}
}
expandFilters(expand, colIds) {
const updatedColIds = [];
const updateGroupExpandState = (filterComp) => {
if (filterComp instanceof ToolPanelFilterGroupComp) {
let anyChildrenChanged = false;
filterComp.getChildren().forEach((child) => {
const childUpdated = updateGroupExpandState(child);
if (childUpdated) {
if (expand) {
filterComp.expand();
anyChildrenChanged = true;
} else if (!filterComp.isColumnGroup()) {
filterComp.collapse();
}
}
});
return anyChildrenChanged;
}
const colId = filterComp.getColumn().getColId();
const updateFilterExpandState = !colIds || colIds.includes(colId);
if (updateFilterExpandState) {
expand ? filterComp.expand() : filterComp.collapse();
updatedColIds.push(colId);
}
return updateFilterExpandState;
};
this.filterGroupComps.forEach(updateGroupExpandState);
this.onGroupExpanded();
if (colIds) {
const unrecognisedColIds = colIds.filter((colId) => updatedColIds.indexOf(colId) < 0);
if (unrecognisedColIds.length > 0) {
(0, import_ag_grid_community160._warn)(167, { unrecognisedColIds });
}
}
}
onGroupExpanded() {
this.fireExpandedEvent();
}
onFilterExpanded() {
this.dispatchLocalEvent({ type: "filterExpanded" });
}
fireExpandedEvent() {
let expandedCount = 0;
let notExpandedCount = 0;
const updateExpandCounts = (filterGroup) => {
if (!filterGroup.isColumnGroup()) {
return;
}
filterGroup.isExpanded() ? expandedCount++ : notExpandedCount++;
filterGroup.getChildren().forEach((child) => {
if (child instanceof ToolPanelFilterGroupComp) {
updateExpandCounts(child);
}
});
};
this.filterGroupComps.forEach(updateExpandCounts);
let state;
if (expandedCount > 0 && notExpandedCount > 0) {
state = 2 /* INDETERMINATE */;
} else if (notExpandedCount > 0) {
state = 1 /* COLLAPSED */;
} else {
state = 0 /* EXPANDED */;
}
this.dispatchLocalEvent({ type: "groupExpanded", state });
}
performFilterSearch(searchText) {
this.searchFilterText = (0, import_ag_grid_community160._exists)(searchText) ? searchText.toLowerCase() : null;
this.searchFilters(this.searchFilterText);
}
searchFilters(searchFilter) {
const passesFilter = (groupName) => {
return !(0, import_ag_grid_community160._exists)(searchFilter) || groupName.toLowerCase().indexOf(searchFilter) !== -1;
};
const recursivelySearch = (filterItem, parentPasses) => {
if (!(filterItem instanceof ToolPanelFilterGroupComp)) {
return passesFilter(filterItem.getColumnFilterName() || "");
}
const children = filterItem.getChildren();
const groupNamePasses = passesFilter(filterItem.getFilterGroupName());
const alreadyPassed = parentPasses || groupNamePasses;
if (alreadyPassed) {
filterItem.hideGroup(false);
for (let i = 0; i < children.length; i++) {
recursivelySearch(children[i], alreadyPassed);
filterItem.hideGroupItem(false, i);
}
return true;
}
let anyChildPasses = false;
children.forEach((child, index) => {
const childPasses = recursivelySearch(child, parentPasses);
filterItem.hideGroupItem(!childPasses, index);
if (childPasses) {
anyChildPasses = true;
}
});
filterItem.hideGroup(!anyChildPasses);
return anyChildPasses;
};
let firstVisible;
let lastVisible;
this.filterGroupComps.forEach((filterGroup, idx) => {
recursivelySearch(filterGroup, false);
const isHidden = filterGroup.getGui()?.classList.contains("ag-hidden");
if (firstVisible === void 0) {
if (!isHidden) {
firstVisible = idx;
lastVisible = idx;
}
} else if (!isHidden && lastVisible !== idx) {
lastVisible = idx;
}
});
this.setFirstAndLastVisible(firstVisible, lastVisible);
this.refreshAriaLabel();
}
setFirstAndLastVisible(firstIdx, lastIdx) {
this.filterGroupComps.forEach((filterGroup, idx) => {
filterGroup.removeCss("ag-first-group-visible");
filterGroup.removeCss("ag-last-group-visible");
if (idx === firstIdx) {
filterGroup.addCss("ag-first-group-visible");
}
if (idx === lastIdx) {
filterGroup.addCss("ag-last-group-visible");
}
});
}
onPanelHidden() {
this.filterGroupComps.forEach((filterGroupComp) => filterGroupComp.onPanelHidden());
}
getExpandedFiltersAndGroups() {
const expandedGroupIds = [];
const expandedColIds = /* @__PURE__ */ new Set();
const getExpandedFiltersAndGroups = (filterComp) => {
if (filterComp instanceof ToolPanelFilterGroupComp) {
filterComp.getChildren().forEach((child) => getExpandedFiltersAndGroups(child));
const groupId = filterComp.getFilterGroupId();
if (filterComp.isExpanded() && !expandedColIds.has(groupId)) {
expandedGroupIds.push(groupId);
}
} else {
if (filterComp.isExpanded()) {
expandedColIds.add(filterComp.getColumn().getColId());
}
}
};
this.filterGroupComps.forEach(getExpandedFiltersAndGroups);
return { expandedGroupIds, expandedColIds: Array.from(expandedColIds) };
}
destroyFilters() {
this.filterGroupComps = this.destroyBeans(this.filterGroupComps);
(0, import_ag_grid_community160._clearElement)(this.getGui());
}
destroy() {
this.destroyFilters();
super.destroy();
}
};
var AgFiltersToolPanelListSelector = {
selector: "AG-FILTERS-TOOL-PANEL-LIST",
component: AgFiltersToolPanelList
};
// packages/ag-grid-enterprise/src/filterToolPanel/filtersToolPanel.css-GENERATED.ts
var filtersToolPanelCSS = (
/*css*/
`.ag-filter-toolpanel{flex:1 1 0px;min-width:0}.ag-filter-toolpanel-header,.ag-filter-toolpanel-search{align-items:center;color:var(--ag-header-text-color);display:flex;font-weight:var(--ag-header-font-weight);padding:0 var(--ag-spacing);>*{align-items:center;display:flex}}.ag-filter-toolpanel-header{padding-bottom:var(--ag-spacing);padding-top:var(--ag-spacing);position:relative;&:focus-visible{border-radius:var(--ag-border-radius);box-shadow:inset var(--ag-focus-shadow)}}:where(.ag-ltr) .ag-filter-toolpanel-group-instance-header-icon,:where(.ag-ltr) .ag-filter-toolpanel-instance-header-icon{margin-left:var(--ag-spacing)}:where(.ag-rtl) .ag-filter-toolpanel-group-instance-header-icon,:where(.ag-rtl) .ag-filter-toolpanel-instance-header-icon{margin-right:var(--ag-spacing)}.ag-filter-toolpanel-search{min-height:var(--ag-header-height);padding-bottom:var(--ag-spacing);padding-top:var(--ag-widget-container-vertical-padding)}:where(.ag-filter-toolpanel-group:not(.ag-has-filter)>.ag-group-title-bar) .ag-filter-toolpanel-group-instance-header-icon{display:none}.ag-filter-toolpanel-search-input{flex-grow:1;height:calc(var(--ag-spacing)*4)}:where(.ag-ltr) .ag-filter-toolpanel-group-title-bar-icon{margin-right:var(--ag-spacing)}:where(.ag-rtl) .ag-filter-toolpanel-group-title-bar-icon{margin-left:var(--ag-spacing)}.ag-filter-toolpanel-expand{cursor:pointer}:where(.ag-ltr) .ag-filter-toolpanel-expand{margin-right:var(--ag-spacing)}:where(.ag-rtl) .ag-filter-toolpanel-expand{margin-left:var(--ag-spacing)}:where(.ag-ltr) .ag-filter-toolpanel-group-title-bar,:where(.ag-ltr) .ag-filter-toolpanel-instance-header{padding-left:calc(var(--ag-spacing) + var(--ag-filter-tool-panel-group-indent)*var(--ag-indentation-level))}:where(.ag-rtl) .ag-filter-toolpanel-group-title-bar,:where(.ag-rtl) .ag-filter-toolpanel-instance-header{padding-right:calc(var(--ag-spacing) + var(--ag-filter-tool-panel-group-indent)*var(--ag-indentation-level))}:where(.ag-ltr) .ag-filter-toolpanel-instance-body{margin-left:var(--ag-filter-tool-panel-group-indent)}:where(.ag-rtl) .ag-filter-toolpanel-instance-body{margin-right:var(--ag-filter-tool-panel-group-indent)}.ag-filter-toolpanel-instance-filter{background-color:var(--ag-chrome-background-color)}.ag-filter-toolpanel-group-level-0{border-top:none}`
);
// packages/ag-grid-enterprise/src/filterToolPanel/filtersToolPanel.ts
var FiltersToolPanelElement = {
tag: "div",
cls: "ag-filter-toolpanel",
children: [
{ tag: "ag-filters-tool-panel-header", ref: "filtersToolPanelHeaderPanel" },
{ tag: "ag-filters-tool-panel-list", ref: "filtersToolPanelListPanel" }
]
};
var FiltersToolPanel = class extends import_ag_grid_community161.Component {
constructor() {
super(FiltersToolPanelElement, [AgFiltersToolPanelHeaderSelector, AgFiltersToolPanelListSelector]);
this.filtersToolPanelHeaderPanel = import_ag_grid_community161.RefPlaceholder;
this.filtersToolPanelListPanel = import_ag_grid_community161.RefPlaceholder;
this.initialised = false;
this.listenerDestroyFuncs = [];
this.registerCSS(filtersToolPanelCSS);
}
init(params) {
if (this.initialised) {
this.listenerDestroyFuncs.forEach((func) => func());
this.listenerDestroyFuncs = [];
}
this.initialised = true;
const defaultParams = {
suppressExpandAll: false,
suppressFilterSearch: false,
suppressSyncLayoutWithGrid: false
};
const newParams = {
...defaultParams,
...params
};
this.params = newParams;
const { filtersToolPanelHeaderPanel, filtersToolPanelListPanel } = this;
filtersToolPanelHeaderPanel.init(newParams);
filtersToolPanelListPanel.init(newParams);
const { suppressExpandAll: hideExpand, suppressFilterSearch: hideSearch } = newParams;
if (hideExpand && hideSearch) {
filtersToolPanelHeaderPanel.setDisplayed(false);
}
this.listenerDestroyFuncs.push(
...this.addManagedListeners(filtersToolPanelHeaderPanel, {
expandAll: () => filtersToolPanelListPanel.expandFilterGroups(true),
collapseAll: () => filtersToolPanelListPanel.expandFilterGroups(false),
searchChanged: (event) => filtersToolPanelListPanel.performFilterSearch(event.searchText)
}),
...this.addManagedListeners(filtersToolPanelListPanel, {
filterExpanded: newParams.onStateUpdated,
groupExpanded: (event) => {
filtersToolPanelHeaderPanel.setExpandState(event.state);
newParams.onStateUpdated();
}
})
);
}
// lazy initialise the panel
setVisible(visible) {
super.setDisplayed(visible);
if (visible && !this.initialised) {
this.init(this.params);
}
}
setFilterLayout(colDefs) {
this.filtersToolPanelListPanel.setFiltersLayout(colDefs);
}
expandFilterGroups(groupIds) {
this.filtersToolPanelListPanel.expandFilterGroups(true, groupIds);
}
collapseFilterGroups(groupIds) {
this.filtersToolPanelListPanel.expandFilterGroups(false, groupIds);
}
expandFilters(colIds) {
this.filtersToolPanelListPanel.expandFilters(true, colIds);
}
collapseFilters(colIds) {
this.filtersToolPanelListPanel.expandFilters(false, colIds);
}
syncLayoutWithGrid() {
this.filtersToolPanelListPanel.syncFilterLayout();
}
refresh(params) {
this.init(params);
return true;
}
getState() {
return this.filtersToolPanelListPanel.getExpandedFiltersAndGroups();
}
};
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterPanelService.ts
var import_ag_grid_community162 = require("ag-grid-community");
var FilterPanelService = class extends import_ag_grid_community162.BeanStub {
constructor() {
super(...arguments);
this.beanName = "filterPanelSvc";
this.states = /* @__PURE__ */ new Map();
this.orderedStates = [];
this.initialStateApplied = false;
this.isActive = false;
}
postConstruct() {
if (!this.gos.get("enableFilterHandlers")) {
return;
}
const updateFilterStates = this.updateFilterStates.bind(this);
const updateApplyButton = () => this.dispatchStatesUpdates(void 0, true);
this.addManagedEventListeners({
newColumnsLoaded: () => {
this.applyInitialState();
updateFilterStates();
},
filterChanged: updateFilterStates,
filterDestroyed: this.onFilterDestroyed.bind(this),
filterOpened: updateApplyButton,
filterClosed: updateApplyButton
});
this.addManagedListeners(this.beans.colFilter, {
filterStateChanged: ({ column }) => {
this.states.get(column.getColId())?.refresh?.();
updateApplyButton();
}
});
}
getIds() {
return Array.from(this.states.keys());
}
getAvailable() {
const beans = this.beans;
const availableFilters = [];
for (const column of beans.colModel.getCols()) {
const id = column.getColId();
if (column.isFilterAllowed() && !column.colDef.suppressFiltersToolPanel && !this.states.get(id)) {
availableFilters.push({
id,
name: getDisplayName(beans, column)
});
}
}
return availableFilters;
}
add(id) {
this.createFilter(id, true);
this.dispatchStatesUpdates(id);
}
remove(id) {
const {
states,
orderedStates,
beans: { colFilter, selectableFilter }
} = this;
const state = states.get(id);
if (!state) {
return;
}
state.destroy?.();
const column = state.state.column;
states.delete(id);
selectableFilter?.clearActive(id);
colFilter?.destroyFilter(column);
this.eventSvc.dispatchEvent({
type: "filterSwitched",
column
});
const index = orderedStates.indexOf(id);
orderedStates.splice(index, 1);
const newActiveId = orderedStates[index];
this.dispatchStatesUpdates(newActiveId);
}
getState(id) {
return this.states.get(id)?.state;
}
updateFilterState(id, key, value, suppressEvents) {
const filterState = this.getState(id);
if (!filterState) {
return;
}
filterState[key] = value;
if (!suppressEvents) {
this.dispatchLocalEvent({
type: "filterPanelStateChanged",
id,
state: filterState
});
}
}
expand(id, expanded) {
const existingFilterState = this.states.get(id);
if (!existingFilterState) {
return;
}
existingFilterState.destroy?.();
const {
handler,
state: { column }
} = existingFilterState;
const newFilterState = this.createFilterState(column, handler, expanded);
this.states.set(id, newFilterState);
this.dispatchLocalEvent({
type: "filterPanelStateChanged",
id,
state: newFilterState.state
});
}
updateType(id, filterDef) {
const stateWrapper = this.states.get(id);
if (!stateWrapper) {
return;
}
const state = stateWrapper.state;
if (state.expanded === false) {
return;
}
const filterDefs = state.filterDefs;
if (!filterDefs) {
return;
}
const { colFilter, selectableFilter } = this.beans;
selectableFilter?.setActive(id, filterDefs, filterDef);
colFilter.filterParamsChanged(id, "columnFilter");
const column = state.column;
this.eventSvc.dispatchEvent({
type: "filterSwitched",
column
});
const newStateWrapper = this.states.get(id);
if (!newStateWrapper) {
return;
}
const newState = newStateWrapper.state;
this.dispatchLocalEvent({
type: "filterPanelStateChanged",
id,
state: newState
});
}
getActions() {
const actions = this.params?.buttons;
if (!actions?.length) {
return void 0;
}
const canApply = !!this.beans.colFilter?.canApplyAll();
return { actions, canApply };
}
doAction(action) {
this.beans.colFilter?.updateAllModels(action);
}
updateParams(params, initialState) {
this.params = params;
if (initialState) {
this.initialState = initialState;
}
this.dispatchStatesUpdates();
this.beans.colFilter?.setGlobalButtons(!!params.buttons?.length);
}
getGridState() {
const filters = [];
this.states.forEach((stateWrapper, colId) => {
filters.push({
colId,
expanded: stateWrapper.state.expanded
});
});
return {
filters
};
}
createFilter(id, expanded) {
const stateWrapper = this.createFilterStateWrapper(id, expanded);
if (stateWrapper) {
this.states.set(id, stateWrapper);
this.orderedStates.push(id);
}
}
createFilterStateWrapper(id, expanded) {
const { colModel, colFilter } = this.beans;
const column = colModel.getColById(id);
if (column && !column.colDef.suppressFiltersToolPanel) {
const handler = colFilter.getHandler(column, true);
if (handler) {
return this.createFilterState(column, handler, expanded);
}
}
return void 0;
}
updateFilterStates() {
const filterModel = this.beans.colFilter.getModel();
const processedIds = /* @__PURE__ */ new Set();
for (const id of Object.keys(filterModel)) {
const existingState = this.states.get(id);
if (!existingState) {
this.createFilter(id);
} else {
existingState.refresh?.();
}
processedIds.add(id);
}
this.states.forEach((state, id) => {
if (!processedIds.has(id)) {
state.refresh?.();
}
});
this.dispatchStatesUpdates();
}
createFilterState(column, handler, expanded) {
const beans = this.beans;
const { colFilter, selectableFilter } = beans;
const name = getDisplayName(beans, column);
const colId = column.getColId();
const getIsEditing = () => !!this.params?.buttons && colFilter.hasUnappliedModel(colId);
const isEditing = getIsEditing();
if (expanded) {
const colDef = column.colDef;
const { filterDefs, activeFilterDef } = selectableFilter?.getDefs(column, colDef) ?? {};
const filterComp = this.createBean(new import_ag_grid_community162.FilterComp(column, "TOOLBAR", true));
return {
state: {
column,
name,
isEditing,
expanded,
detail: filterComp.getGui(),
activeFilterDef,
filterDefs,
afterGuiAttached: filterComp.afterGuiAttached.bind(filterComp),
afterGuiDetached: filterComp.afterGuiDetached.bind(filterComp)
},
handler,
refresh: () => {
this.updateFilterState(colId, "isEditing", getIsEditing());
},
destroy: () => this.destroyBean(filterComp)
};
} else {
const colId2 = column.getColId();
const getSummary = () => handler.getModelAsString?.(colFilter.getStateForColumn(colId2).model, "filterToolPanel") ?? "";
return {
state: {
column,
name,
isEditing,
expanded: false,
summary: getSummary()
},
handler,
refresh: () => {
this.updateFilterState(colId2, "isEditing", getIsEditing(), true);
this.updateFilterState(colId2, "summary", getSummary());
}
};
}
}
onFilterDestroyed({ column, source }) {
if (!this.beans.colFilter?.isAlive()) {
return;
}
const states = this.states;
const id = column.getColId();
const existingState = states.get(id);
if (existingState) {
const stateWrapper = this.createFilterStateWrapper(id, existingState.state.expanded);
if (stateWrapper) {
existingState.destroy?.();
states.set(id, stateWrapper);
} else {
this.remove(id);
}
if (source === "api") {
this.dispatchStatesUpdates();
}
}
}
dispatchStatesUpdates(activeId, action) {
this.dispatchLocalEvent({
type: "filterPanelStatesChanged",
activeId,
action
});
}
applyInitialState() {
if (this.initialStateApplied) {
return;
}
this.initialStateApplied = true;
this.initialState?.filters?.forEach(({ colId, expanded }) => this.createFilter(colId, expanded));
this.initialState = void 0;
}
destroy() {
const { states, orderedStates } = this;
states.forEach((state) => state.destroy?.());
states.clear();
orderedStates.length = 0;
this.params = void 0;
this.initialState = void 0;
super.destroy();
}
};
function getDisplayName(beans, column) {
return beans.colNames.getDisplayNameForColumn(column, "filterToolPanel") ?? column.getColId();
}
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/selectableFilterService.ts
var import_ag_grid_community164 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterPanelUtils.ts
var import_ag_grid_community163 = require("ag-grid-community");
var DEFAULT_LOCALE_TEXT2 = {
addFilterCard: "Add Filter",
ariaLabelAddFilterField: "Add Filter Field",
ariaLabelFilterCardDelete: "Delete Filter",
ariaLabelFilterCardHasEdits: "Has Edits",
agTextColumnFilterDisplayName: "Simple Filter",
agNumberColumnFilterDisplayName: "Simple Filter",
agDateColumnFilterDisplayName: "Simple Filter",
agSetColumnFilterDisplayName: "Selection Filter",
agMultiColumnFilterDisplayName: "Combo Filter",
addFilterPlaceholder: "Search columns..."
};
function translateForFilterPanel(bean, key) {
return (0, import_ag_grid_community163._translate)(bean, DEFAULT_LOCALE_TEXT2, key);
}
function compareAndUpdateListsInDom(eContainer, eNewItems, ePrevItems) {
let newIndex = 0;
for (let prevIndex = 0; prevIndex < ePrevItems.length; prevIndex++) {
const ePrevItem = ePrevItems[prevIndex];
if (ePrevItem === eNewItems[newIndex]) {
newIndex++;
} else {
(0, import_ag_grid_community163._removeFromParent)(ePrevItem);
}
}
while (newIndex < eNewItems.length) {
eContainer.appendChild(eNewItems[newIndex++]);
}
}
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/selectableFilterService.ts
var SelectableFilterService = class extends import_ag_grid_community164.BeanStub {
constructor() {
super(...arguments);
this.beanName = "selectableFilter";
this.selectedFilters = /* @__PURE__ */ new Map();
this.valueGetters = /* @__PURE__ */ new Map();
}
getFilterValueGetter(colId) {
return this.valueGetters.get(colId);
}
isSelectable(filterDef) {
return filterDef.filter === "agSelectableColumnFilter";
}
getFilterDef(column, filterDef) {
return this.getDefs(column, filterDef).activeFilterDef;
}
getDefs(column, filterDef) {
if (!this.isSelectable(filterDef)) {
return void 0;
}
const beans = this.beans;
const { gos, dataTypeSvc, colFilter } = beans;
let filterParams = filterDef.filterParams;
const colDef = column.colDef;
if (typeof filterParams === "function") {
filterParams = filterParams(
(0, import_ag_grid_community164._addGridCommonParams)(gos, {
column,
colDef
})
);
}
const cellDataType = dataTypeSvc?.getBaseDataType(column);
const dataTypeDefinition = dataTypeSvc?.getDataTypeDefinition(column);
const formatValue = dataTypeSvc?.getFormatValue(cellDataType);
const { filters, defaultFilterParams, defaultFilterIndex } = filterParams ?? {};
const updateDef = (def) => {
const { filter, filterParams: defFilterParams, name, filterValueGetter = colDef.filterValueGetter } = def;
const userParams = defaultFilterParams ? { ...defaultFilterParams, ...defFilterParams } : defFilterParams;
let updatedParams;
if (dataTypeDefinition && formatValue) {
if (filter === "agMultiColumnFilter") {
updatedParams = beans.multiFilter?.getParamsForDataType(
userParams,
filterValueGetter,
dataTypeDefinition,
formatValue
);
} else {
updatedParams = (0, import_ag_grid_community164._getFilterParamsForDataType)(
filter,
userParams,
filterValueGetter,
dataTypeDefinition,
formatValue,
beans,
this.getLocaleTextFunc()
);
}
}
let updatedName;
if (!name) {
let filterString = filter;
if (typeof filter === "boolean") {
filterString = colFilter?.getDefaultFilterFromDataType(() => cellDataType);
}
if (typeof filterString === "string") {
updatedName = translateForFilterPanel(this, `${filterString}DisplayName`);
} else {
(0, import_ag_grid_community164._warn)(280, { colId: column.getColId() });
updatedName = "";
}
}
if (defaultFilterParams || updatedParams || updatedName) {
return {
...def,
filterParams: userParams,
name: updatedName ?? name,
...updatedParams
};
}
return def;
};
const filterDefs = (filters ?? this.getDefaultFilters(column)).map(updateDef);
let index = this.selectedFilters.get(column.getColId()) ?? // UI selected value
defaultFilterIndex ?? // col def value
(!filters && (0, import_ag_grid_community164._isSetFilterByDefault)(gos) ? 1 : 0);
if (index >= filterDefs.length) {
index = 0;
}
const activeFilterDef = filterDefs[index];
return { filterDefs, activeFilterDef };
}
setActive(colId, filterDefs, activeFilterDef) {
const index = filterDefs.indexOf(activeFilterDef);
if (index < 0) {
return;
}
const { selectedFilters, valueGetters } = this;
selectedFilters.set(colId, index);
const filterValueGetter = activeFilterDef.filterValueGetter;
if (filterValueGetter) {
valueGetters.set(colId, filterValueGetter);
} else {
valueGetters.delete(colId);
}
}
clearActive(colId) {
const { selectedFilters, valueGetters } = this;
selectedFilters.delete(colId);
valueGetters.delete(colId);
}
destroy() {
const { selectedFilters, valueGetters } = this;
selectedFilters.clear();
valueGetters.clear();
super.destroy();
}
getDefaultFilters(column) {
const beans = this.beans;
const { gos, dataTypeSvc } = beans;
const isMultiFilterEnabled = gos.isModuleRegistered("MultiFilter");
const cellDataType = dataTypeSvc?.getBaseDataType(column);
const simpleFilter = (0, import_ag_grid_community164._getDefaultSimpleFilter)(cellDataType, false);
return [
{ filter: simpleFilter },
{ filter: "agSetColumnFilter" },
...isMultiFilterEnabled ? [
{
filter: "agMultiColumnFilter"
}
] : []
];
}
};
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/wrapperToolPanel.ts
var import_ag_grid_community171 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterPanel.ts
var import_ag_grid_community169 = require("ag-grid-community");
var import_ag_grid_community170 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/addFilterComp.ts
var import_ag_grid_community165 = require("ag-grid-community");
var AddFilterElement = {
tag: "div",
cls: "ag-filter-card ag-filter-card-add"
};
var AddFilterComp = class extends import_ag_grid_community165.Component {
constructor(options) {
super(AddFilterElement);
this.options = /* @__PURE__ */ new Map();
this.setOptions(options);
}
postConstruct() {
this.showButton();
}
refresh(newOptions) {
this.setOptions(newOptions);
const { eSelect, options } = this;
if (eSelect) {
eSelect.setValueList({ valueList: Array.from(options.keys()), refresh: true });
}
}
showButton() {
(0, import_ag_grid_community165._clearElement)(this.getGui());
this.destroySelect();
const eButton = (0, import_ag_grid_community165._createElement)({
tag: "button",
cls: "ag-button ag-standard-button ag-filter-add-button",
children: [
{ tag: "span", children: [() => (0, import_ag_grid_community165._createIconNoSpan)("filterAdd", this.beans)] },
{
tag: "span",
cls: "ag-filter-add-button-label",
children: translateForFilterPanel(this, "addFilterCard")
}
]
});
this.activateTabIndex([eButton]);
const clickListener = this.showSelect.bind(this);
eButton.addEventListener("click", clickListener);
this.removeButton = () => {
eButton.removeEventListener("click", clickListener);
};
this.appendChild(eButton);
eButton.focus();
}
showSelect() {
(0, import_ag_grid_community165._clearElement)(this.getGui());
this.destroyButton();
const pickerAriaLabelKey = "ariaLabelAddFilterField";
const selectParams = {
className: "ag-filter-add-select",
pickerType: "virtual-list",
pickerAriaLabelKey,
pickerAriaLabelValue: translateForFilterPanel(this, pickerAriaLabelKey),
placeholder: translateForFilterPanel(this, "addFilterPlaceholder"),
value: "",
valueList: Array.from(this.options.keys()),
searchType: "matchAny",
allowTyping: true,
filterList: true,
highlightMatch: true,
valueFormatter: (value) => this.options.get(value)
};
const eSelect = this.createManagedBean(new AgRichSelect(selectParams));
this.eSelect = eSelect;
this.appendChild(eSelect.getGui());
eSelect.showPicker();
eSelect.getFocusableElement().focus();
eSelect.addManagedListeners(eSelect, {
fieldPickerValueSelected: ({ value: id }) => this.dispatchLocalEvent({
type: "filterSelected",
id
}),
pickerHidden: () => {
this.showButton();
}
});
}
setOptions(newOptions) {
const options = this.options;
options.clear();
for (const { id, name } of newOptions) {
options.set(id, name);
}
}
destroySelect() {
this.eSelect = this.destroyBean(this.eSelect);
}
destroyButton() {
this.removeButton = this.removeButton?.();
}
destroy() {
this.destroySelect();
this.destroyButton();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterCardComp.ts
var import_ag_grid_community168 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterDetailComp.ts
var import_ag_grid_community166 = require("ag-grid-community");
var FilterDetailElement = {
tag: "div",
cls: "ag-filter-card-body",
children: [{ tag: "ag-select", cls: "ag-filter-type-select", ref: "eFilterType" }]
};
var FilterDetailComp = class extends import_ag_grid_community166.Component {
constructor() {
super(...arguments);
this.eFilterType = import_ag_grid_community166.RefPlaceholder;
}
postConstruct() {
const eFilterTypeParams = {
onValueChange: (filterDef) => this.dispatchLocalEvent({ type: "filterTypeChanged", filterDef })
};
this.setTemplate(FilterDetailElement, [import_ag_grid_community166.AgSelectSelector], { eFilterType: eFilterTypeParams });
this.eFilterType.setDisplayed(false);
}
refresh(newState) {
const oldState = this.state;
this.state = newState;
const {
activeFilterDef: newActiveFilterDef,
filterDefs: newFilterDefs,
detail: newDetail,
afterGuiAttached,
afterGuiDetached
} = newState;
const { activeFilterDef: oldActiveFilterDef, filterDefs: oldFilterDefs, detail: oldDetail } = oldState ?? {};
const eFilterType = this.eFilterType;
if (newFilterDefs !== oldFilterDefs) {
eFilterType.clearOptions();
const options = newFilterDefs?.map((filterDef) => ({ value: filterDef, text: filterDef.name }));
if (options) {
eFilterType.clearOptions().addOptions(options).setValue(newActiveFilterDef, true);
}
eFilterType.setDisplayed(!!options);
} else if (newActiveFilterDef !== oldActiveFilterDef) {
eFilterType.setValue(newActiveFilterDef, true);
}
if (newDetail !== oldDetail) {
if (oldDetail) {
(0, import_ag_grid_community166._removeFromParent)(oldDetail);
afterGuiDetached();
}
this.appendChild(newDetail);
afterGuiAttached({
container: "newFiltersToolPanel",
suppressFocus: true
});
}
}
};
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterSummaryComp.ts
var import_ag_grid_community167 = require("ag-grid-community");
var FilterSummaryElement = {
tag: "div",
cls: "ag-filter-card-summary",
attrs: {
"aria-hidden": "true"
}
};
var FilterSummaryComp = class extends import_ag_grid_community167.Component {
constructor() {
super(FilterSummaryElement);
}
refresh(state) {
this.getGui().textContent = state.summary;
}
};
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterCardComp.ts
var FilterCardElement = {
tag: "div",
cls: "ag-filter-card",
children: [
{
tag: "div",
cls: "ag-filter-card-header",
role: "presentation",
children: [
{
tag: "div",
cls: "ag-filter-card-heading",
role: "heading",
attrs: {
"aria-level": "2"
},
children: [
{
tag: "button",
ref: "eExpand",
cls: "ag-button ag-filter-card-expand",
children: [
{ tag: "span", ref: "eTitle", cls: "ag-filter-card-title" },
{ tag: "span", ref: "eEditing", cls: "ag-filter-card-editing-icon" },
{ tag: "span", ref: "eExpandIcon", cls: "ag-filter-card-expand-icon" }
]
}
]
},
{
tag: "button",
ref: "eDelete",
cls: "ag-button ag-filter-card-delete",
children: [{ tag: "span", ref: "eDeleteIcon", cls: "ag-filter-card-delete-icon" }]
}
]
}
]
};
var FilterCardComp = class extends import_ag_grid_community168.Component {
constructor(id) {
super(FilterCardElement);
this.id = id;
this.eTitle = import_ag_grid_community168.RefPlaceholder;
this.eExpand = import_ag_grid_community168.RefPlaceholder;
this.eDelete = import_ag_grid_community168.RefPlaceholder;
this.eExpandIcon = import_ag_grid_community168.RefPlaceholder;
this.eDeleteIcon = import_ag_grid_community168.RefPlaceholder;
this.eEditing = import_ag_grid_community168.RefPlaceholder;
}
postConstruct() {
const { beans, eDelete, eExpand, eDeleteIcon, eEditing, id } = this;
const filterPanelService = beans.filterPanelSvc;
(0, import_ag_grid_community168._setAriaLabel)(eDelete, translateForFilterPanel(this, "ariaLabelFilterCardDelete"));
eDeleteIcon.appendChild((0, import_ag_grid_community168._createIcon)("close", beans, null));
this.activateTabIndex([eExpand, eDelete]);
this.addManagedElementListeners(eExpand, {
click: () => filterPanelService.expand(id, !this.state?.expanded)
});
this.addManagedElementListeners(eDelete, {
click: () => filterPanelService.remove(id)
});
this.addManagedEventListeners({ filterOpened: this.onFilterOpened.bind(this) });
eEditing.appendChild((0, import_ag_grid_community168._createIcon)("filterCardEditing", beans, null));
}
refresh(newState) {
const { eExpand, eEditing, state: oldState, beans } = this;
this.state = newState;
const { name, expanded, isEditing } = newState;
this.eTitle.textContent = name;
(0, import_ag_grid_community168._setDisplayed)(eEditing, isEditing);
if (!oldState || expanded !== oldState.expanded) {
this.toggleExpand(newState);
}
let ariaLabel = expanded ? null : `${name} ${newState.summary}`;
if (isEditing) {
ariaLabel = `${ariaLabel ?? name}. ${translateForFilterPanel(this, "ariaLabelFilterCardHasEdits")}`;
}
(0, import_ag_grid_community168._setAriaLabel)(eExpand, ariaLabel);
const removeComp = (comp) => {
if (!comp) {
return;
}
(0, import_ag_grid_community168._removeFromParent)(comp.getGui());
return this.destroyBean(comp);
};
const createOrRefreshComp = (comp, FilterComp5, postCreateFunc) => {
if (!comp) {
comp = this.createBean(new FilterComp5());
postCreateFunc?.(comp);
this.appendChild(comp.getGui());
}
comp.refresh(newState);
return comp;
};
if (newState.expanded) {
this.summaryComp = removeComp(this.summaryComp);
const detailComp = createOrRefreshComp(
this.detailComp,
FilterDetailComp,
(comp) => comp.addManagedListeners(comp, {
filterTypeChanged: ({ filterDef }) => beans.filterPanelSvc.updateType(this.id, filterDef)
})
);
this.detailComp = detailComp;
const detailId = `ag-${this.getCompId()}-filter`;
detailComp.getGui().id = detailId;
(0, import_ag_grid_community168._setAriaControls)(eExpand, detailId);
} else {
this.detailComp = removeComp(this.detailComp);
this.summaryComp = createOrRefreshComp(this.summaryComp, FilterSummaryComp);
(0, import_ag_grid_community168._setAriaControls)(eExpand, null);
}
}
toggleExpand(state) {
const expanded = !!state.expanded;
const { eExpandIcon, eExpand, beans } = this;
(0, import_ag_grid_community168._clearElement)(eExpandIcon);
eExpandIcon.appendChild((0, import_ag_grid_community168._createIcon)(expanded ? "filterCardCollapse" : "filterCardExpand", beans, null));
(0, import_ag_grid_community168._setAriaExpanded)(eExpand, expanded);
}
onFilterOpened(event) {
const { state, beans, id } = this;
if (event.source === "COLUMN_MENU" && event.column === state?.column && state?.expanded) {
beans.filterPanelSvc.expand(id, false);
}
}
destroy() {
this.detailComp = this.destroyBean(this.detailComp);
this.summaryComp = this.destroyBean(this.summaryComp);
this.state = void 0;
super.destroy();
}
};
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterPanel.ts
function isSingleRefresh(params) {
return !!params?.id;
}
function isActionRefresh(params) {
return !!params?.action;
}
var FilterPanelElement = {
tag: "div",
cls: "ag-filter-panel",
children: [{ tag: "div", cls: "ag-filter-panel-container", ref: "eContainer" }]
};
var FilterPanel = class extends import_ag_grid_community170.Component {
constructor() {
super(FilterPanelElement);
this.eContainer = import_ag_grid_community170.RefPlaceholder;
this.filters = /* @__PURE__ */ new Map();
}
refresh(params) {
if (isActionRefresh(params)) {
this.refreshActions();
return;
}
if (isSingleRefresh(params)) {
this.filters.get(params.id)?.refresh(params.state);
return;
}
const { eContainer, filters: existingFilters, beans } = this;
const filterPanelSvc = beans.filterPanelSvc;
const filterIds = filterPanelSvc.getIds();
const newFilters = /* @__PURE__ */ new Map();
const somethingIsFocused = !(0, import_ag_grid_community170._isNothingFocused)(beans);
const activeElement = somethingIsFocused ? (0, import_ag_grid_community170._getActiveDomElement)(beans) : void 0;
const containerHasFocus = somethingIsFocused && eContainer.contains(activeElement);
const ePrevItems = [];
const eNewItems = [];
for (const id of filterIds) {
const newFilter = existingFilters.get(id) ?? this.createBean(new FilterCardComp(id));
newFilter.refresh(filterPanelSvc.getState(id));
newFilters.set(id, newFilter);
eNewItems.push(newFilter.getGui());
}
this.filters = newFilters;
const compsToDestroy = [];
existingFilters.forEach((existingFilter, id) => {
ePrevItems.push(existingFilter.getGui());
if (!newFilters.has(id)) {
compsToDestroy.push(existingFilter);
}
});
let addFilterComp = this.addFilterComp;
if (addFilterComp) {
ePrevItems.push(addFilterComp.getGui());
}
const addFilterOptions = filterPanelSvc.getAvailable();
if (addFilterOptions.length) {
if (!addFilterComp) {
addFilterComp = this.createBean(new AddFilterComp(addFilterOptions));
addFilterComp.addManagedListeners(addFilterComp, {
filterSelected: ({ id }) => filterPanelSvc.add(id)
});
}
addFilterComp.refresh(addFilterOptions);
eNewItems.push(addFilterComp.getGui());
} else {
addFilterComp = this.destroyBean(addFilterComp);
}
this.addFilterComp = addFilterComp;
compareAndUpdateListsInDom(eContainer, eNewItems, ePrevItems);
compsToDestroy.forEach((comp) => this.destroyBean(comp));
const activeId = params?.activeId;
const activeItemToFocus = activeId && newFilters.get(activeId)?.getGui();
if (activeItemToFocus) {
(0, import_ag_grid_community170._focusInto)(activeItemToFocus);
} else if (containerHasFocus && (0, import_ag_grid_community170._isNothingFocused)(beans)) {
(0, import_ag_grid_community170._focusInto)(eNewItems[eNewItems.length - 1] ?? eContainer);
}
this.refreshActions();
}
refreshActions() {
const filterPanelSvc = this.beans.filterPanelSvc;
const { actions, canApply } = filterPanelSvc.getActions() ?? {};
let buttonComp = this.buttonComp;
if (actions?.length) {
const buttons = actions.map((type) => ({
type,
label: (0, import_ag_grid_community169._translateForFilter)(this, `${type}Filter`)
}));
if (!buttonComp) {
buttonComp = this.createBean(new import_ag_grid_community169.FilterButtonComp({ className: "ag-filter-panel-buttons" }));
this.getGui().appendChild(buttonComp.getGui());
const listeners = {};
["apply", "clear", "reset", "cancel"].forEach((action) => {
listeners[action] = () => filterPanelSvc.doAction(action);
});
buttonComp.addManagedListeners(buttonComp, listeners);
}
buttonComp.updateButtons(buttons);
buttonComp.updateValidity(canApply !== false);
} else {
if (buttonComp) {
(0, import_ag_grid_community170._removeFromParent)(buttonComp.getGui());
buttonComp = this.destroyBean(buttonComp);
}
}
this.buttonComp = buttonComp;
}
destroy() {
this.addFilterComp = this.destroyBean(this.addFilterComp);
this.buttonComp = this.destroyBean(this.buttonComp);
const filters = this.filters;
filters.forEach((filter) => this.destroyBean(filter));
filters.clear();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/newFiltersToolPanel.css-GENERATED.ts
var newFiltersToolPanelCSS = (
/*css*/
`.ag-filter-panel{display:flex;flex-direction:column;width:100%;:where(.ag-standard-button){transition:background-color .25s ease-in-out,color .25s ease-in-out}}.ag-filter-panel .ag-simple-filter-body-wrapper{padding:var(--ag-widget-vertical-spacing) var(--ag-widget-container-horizontal-padding) 0}.ag-filter-panel .ag-mini-filter{margin-left:var(--ag-widget-container-horizontal-padding);margin-right:var(--ag-widget-container-horizontal-padding);margin-top:var(--ag-widget-vertical-spacing)}.ag-filter-panel-container{flex:1;overflow:auto;padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding) 0}.ag-filter-panel-container>:where(:not(:last-child)){margin-bottom:var(--ag-widget-container-vertical-padding)}.ag-filter-card{background-color:var(--ag-background-color);border:solid var(--ag-border-width) var(--ag-border-color);border-radius:var(--ag-border-radius)}.ag-filter-card-header{align-items:center;display:flex;flex-direction:row;padding-top:var(--ag-widget-vertical-spacing)}:where(.ag-ltr) .ag-filter-card-header{&>:where(:not(:last-child)){padding-right:var(--ag-spacing)}}:where(.ag-rtl) .ag-filter-card-header{&>:where(:not(:last-child)){padding-left:var(--ag-spacing)}}.ag-filter-card-heading{flex:1;overflow:hidden;padding-bottom:calc(var(--ag-widget-container-vertical-padding) - var(--ag-widget-vertical-spacing));padding-top:calc(var(--ag-widget-container-vertical-padding) - var(--ag-widget-vertical-spacing))}:where(.ag-ltr) .ag-filter-card-heading{padding-left:var(--ag-widget-horizontal-spacing)}:where(.ag-rtl) .ag-filter-card-heading{padding-right:var(--ag-widget-horizontal-spacing)}.ag-filter-card-expand{align-items:center;display:flex;flex-direction:row;width:100%}.ag-filter-card-title{font-weight:var(--ag-header-font-weight);overflow:hidden;text-overflow:ellipsis}.ag-filter-card-expand-icon{display:flex;flex:1;justify-content:end}.ag-filter-card-editing-icon{margin:0 var(--ag-spacing)}.ag-filter-card-delete-icon,.ag-filter-card-editing-icon,.ag-filter-card-expand-icon,.ag-filter-card-summary{color:var(--ag-filter-panel-card-subtle-color)}.ag-filter-card-delete-icon,.ag-filter-card-expand-icon{transition:color .25s ease-in-out}.ag-filter-card-delete-icon:hover,.ag-filter-card-expand-icon:hover,.ag-filter-card-heading:hover .ag-filter-card-expand-icon{color:var(--ag-filter-panel-card-subtle-hover-color)}.ag-filter-add-button,.ag-filter-card-delete,.ag-filter-card-expand{border-radius:var(--ag-button-border-radius)}.ag-filter-card-summary,.ag-filter-type-select{margin-left:var(--ag-widget-container-horizontal-padding);margin-right:var(--ag-widget-container-horizontal-padding)}:where(.ag-ltr) .ag-filter-card-delete{margin-right:var(--ag-widget-horizontal-spacing)}:where(.ag-rtl) .ag-filter-card-delete{margin-left:var(--ag-widget-horizontal-spacing)}.ag-filter-card-summary{margin-bottom:var(--ag-widget-container-vertical-padding)}.ag-filter-type-select{padding-top:var(--ag-widget-vertical-spacing)}.ag-filter-card-add{border:0;padding:0}.ag-filter-add-button{align-items:center;display:flex;flex-direction:row;line-height:1.5;width:100%}:where(.ag-ltr) .ag-filter-add-button-label{margin-left:var(--ag-spacing)}:where(.ag-rtl) .ag-filter-add-button-label{margin-right:var(--ag-spacing)}.ag-filter-add-select{border:0;.ag-rich-select-value{border:0;padding:calc(((1.5*var(--ag-font-size) + 2*var(--ag-button-vertical-padding)) - var(--ag-input-height))/2) var(--ag-spacing)}}:where(.ag-ltr) .ag-filter-add-select{.ag-text-field-input{padding-left:calc(var(--ag-spacing)*1.5 + 12px)!important}}:where(.ag-rtl) .ag-filter-add-select{.ag-text-field-input{padding-right:calc(var(--ag-spacing)*1.5 + 12px)!important}}.ag-filter-panel-buttons{display:flex;flex-wrap:wrap;gap:var(--ag-widget-vertical-spacing) var(--ag-widget-horizontal-spacing);justify-content:flex-end;overflow:hidden;padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding) 0}.ag-filter-panel-buttons-button{line-height:1.5}.ag-filter-panel .ag-filter-panel-buttons-apply-button{background-color:var(--ag-filter-panel-apply-button-background-color);color:var(--ag-filter-panel-apply-button-color)}.ag-filter-panel>:where(:last-child){padding-bottom:var(--ag-widget-container-vertical-padding)}.ag-filter-panel .ag-set-filter-body-wrapper,.ag-filter-panel .ag-simple-filter-body-wrapper>:last-child{margin-bottom:var(--ag-widget-container-vertical-padding)}`
);
// packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/wrapperToolPanel.ts
var WrapperToolPanel = class extends import_ag_grid_community171.Component {
constructor() {
super();
this.registerCSS(newFiltersToolPanelCSS);
}
init(params) {
if (!this.gos.get("enableFilterHandlers")) {
(0, import_ag_grid_community171._warn)(282);
return;
}
const filterPanelSvc = this.beans.filterPanelSvc;
filterPanelSvc.isActive = true;
this.addDestroyFunc(() => {
filterPanelSvc.isActive = false;
});
this.updateParams(params, params.initialState);
const filterPanel = this.createManagedBean(new FilterPanel());
this.filterPanel = filterPanel;
const refresh = (event) => {
filterPanel.refresh(event);
params.onStateUpdated();
};
refresh();
this.addManagedListeners(filterPanelSvc, {
filterPanelStatesChanged: refresh,
filterPanelStateChanged: refresh
});
}
getGui() {
return this.filterPanel?.getGui();
}
refresh(params) {
this.updateParams(params);
return true;
}
updateParams(params, initialState) {
this.beans.filterPanelSvc?.updateParams(params, initialState);
}
getState() {
return this.beans.filterPanelSvc?.getGridState() ?? {};
}
};
// packages/ag-grid-enterprise/src/filterToolPanel/filtersToolPanelModule.ts
var FiltersToolPanelModule = {
moduleName: "FiltersToolPanel",
version: VERSION,
userComponents: { agFiltersToolPanel: FiltersToolPanel },
icons: {
// filter tool panel tab
filtersToolPanel: "filter"
},
dependsOn: [SideBarModule, EnterpriseCoreModule, import_ag_grid_community172._ColumnFilterModule]
};
var NewFiltersToolPanelModule = {
moduleName: "NewFiltersToolPanel",
version: VERSION,
userComponents: { agNewFiltersToolPanel: WrapperToolPanel },
beans: [FilterPanelService, SelectableFilterService],
icons: {
// filter add button in new filter tool panel
filterAdd: "filter-add",
// filter tool panel tab
filtersToolPanel: "filter",
// open icon for rich select
richSelectOpen: "small-down",
// remove for rich select editor pills
richSelectRemove: "cancel",
// button to expand filter card in new filter tool panel
filterCardExpand: "chevron-down",
// button to collapse filter card in new filter tool panel
filterCardCollapse: "chevron-up",
// indicates filter card in new filter tool panel has edits
filterCardEditing: "edit"
},
dependsOn: [SideBarModule, EnterpriseCoreModule, import_ag_grid_community172._ColumnFilterModule]
};
// packages/ag-grid-enterprise/src/masterDetail/masterDetailModule.ts
var import_ag_grid_community176 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/masterDetail/detailCellRenderer.ts
var import_ag_grid_community174 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/masterDetail/detailCellRendererCtrl.ts
var import_ag_grid_community173 = require("ag-grid-community");
var DetailCellRendererCtrl = class extends import_ag_grid_community173.BeanStub {
constructor() {
super(...arguments);
this.loadRowDataVersion = 0;
}
wireBeans(beans) {
this.environment = beans.environment;
}
init(comp, params) {
this.params = params;
this.comp = comp;
const doNothingBecauseInsidePinnedSection = params.pinned != null;
if (doNothingBecauseInsidePinnedSection) {
return;
}
this.setAutoHeightClasses();
this.setupRefreshStrategy();
this.createDetailGrid();
this.loadRowData();
this.addManagedEventListeners({ fullWidthRowFocused: this.onFullWidthRowFocused.bind(this) });
}
onFullWidthRowFocused(e) {
const params = this.params;
const row = { rowIndex: params.node.rowIndex, rowPinned: params.node.rowPinned };
const eventRow = { rowIndex: e.rowIndex, rowPinned: e.rowPinned };
const isSameRow = (0, import_ag_grid_community173._isSameRow)(row, eventRow);
if (!isSameRow) {
return;
}
(0, import_ag_grid_community173._focusInto)(this.comp.getGui(), e.fromBelow);
}
setAutoHeightClasses() {
const autoHeight = this.gos.get("detailRowAutoHeight");
const parentClass = autoHeight ? "ag-details-row-auto-height" : "ag-details-row-fixed-height";
const detailClass = autoHeight ? "ag-details-grid-auto-height" : "ag-details-grid-fixed-height";
const comp = this.comp;
comp.toggleCss(parentClass, true);
comp.toggleDetailGridCss(detailClass, true);
}
setupRefreshStrategy() {
const providedStrategy = this.params.refreshStrategy;
const validSelection = providedStrategy == "everything" || providedStrategy == "nothing" || providedStrategy == "rows";
if (validSelection) {
this.refreshStrategy = providedStrategy;
return;
}
if (providedStrategy != null) {
(0, import_ag_grid_community173._warn)(170, { providedStrategy });
}
this.refreshStrategy = "rows";
}
createDetailGrid() {
const { params, gos } = this;
if ((0, import_ag_grid_community173._missing)(params.detailGridOptions)) {
(0, import_ag_grid_community173._warn)(171);
return;
}
const masterTheme = gos.get("theme");
const detailTheme = params.detailGridOptions.theme;
if (detailTheme && detailTheme !== masterTheme) {
(0, import_ag_grid_community173._warn)(267);
}
const gridOptions = {
themeStyleContainer: this.environment.eStyleContainer,
...params.detailGridOptions,
theme: masterTheme
};
const autoHeight = gos.get("detailRowAutoHeight");
if (autoHeight) {
gridOptions.domLayout = "autoHeight";
}
this.comp.setDetailGrid(gridOptions);
}
registerDetailWithMaster(api) {
const {
params,
beans: { selectionSvc, findSvc }
} = this;
const rowId = params.node.id;
const masterGridApi = params.api;
const gridInfo = {
id: rowId,
api
};
const rowNode = params.node;
if (masterGridApi.isDestroyed()) {
return;
}
masterGridApi.addDetailGridInfo(rowId, gridInfo);
rowNode.detailGridInfo = gridInfo;
const masterNode = rowNode.parent;
findSvc?.registerDetailGrid(rowNode, api);
function onDetailSelectionChanged() {
if (masterNode) {
selectionSvc?.refreshMasterNodeState(masterNode);
}
}
function onMasterRowSelected({ node, source }) {
if (node !== masterNode || source === "masterDetail" || api.isDestroyed()) {
return;
}
selectionSvc?.setDetailSelectionState(masterNode, params.detailGridOptions, api);
}
api.addEventListener("firstDataRendered", () => {
if (api.isDestroyed() || masterGridApi.isDestroyed())
return;
selectionSvc?.setDetailSelectionState(masterNode, params.detailGridOptions, api);
api.addEventListener("selectionChanged", onDetailSelectionChanged);
masterGridApi.addEventListener("rowSelected", onMasterRowSelected);
});
this.addDestroyFunc(() => {
if (rowNode.detailGridInfo !== gridInfo) {
return;
}
if (!masterGridApi.isDestroyed()) {
masterGridApi.removeDetailGridInfo(rowId);
}
rowNode.detailGridInfo = null;
});
}
loadRowData() {
this.loadRowDataVersion++;
const versionThisCall = this.loadRowDataVersion;
const params = this.params;
if (params.detailGridOptions?.rowModelType === "serverSide") {
const node = params.node;
node.detailGridInfo?.api?.refreshServerSide({ purge: true });
return;
}
const userFunc = params.getDetailRowData;
if (!userFunc) {
(0, import_ag_grid_community173._warn)(172);
return;
}
const successCallback = (rowData) => {
const mostRecentCall = this.loadRowDataVersion === versionThisCall;
if (mostRecentCall) {
this.comp.setRowData(rowData);
}
};
const funcParams = {
node: params.node,
// we take data from node, rather than params.data
// as the data could have been updated with new instance
data: params.node.data,
successCallback,
context: (0, import_ag_grid_community173._addGridCommonParams)(this.gos, {}).context
};
userFunc(funcParams);
}
refresh() {
const GET_GRID_TO_REFRESH = false;
const GET_GRID_TO_DO_NOTHING = true;
switch (this.refreshStrategy) {
case "nothing":
return GET_GRID_TO_DO_NOTHING;
case "everything":
return GET_GRID_TO_REFRESH;
}
this.loadRowData();
return GET_GRID_TO_DO_NOTHING;
}
};
// packages/ag-grid-enterprise/src/masterDetail/detailFrameworkComponentWrapper.ts
var DetailFrameworkComponentWrapper = class {
constructor(parentWrapper) {
this.parentWrapper = parentWrapper;
}
wrap(frameworkComponent, mandatoryMethods, optionalMethods, componentType) {
return this.parentWrapper.wrap(frameworkComponent, mandatoryMethods, optionalMethods, componentType);
}
};
// packages/ag-grid-enterprise/src/masterDetail/detailCellRenderer.ts
var PinnedDetailCellRendererElement = { tag: "div", cls: "ag-details-row" };
var DetailCellRendererElement = {
tag: "div",
cls: "ag-details-row",
role: "gridcell",
children: [{ tag: "div", ref: "eDetailGrid", cls: "ag-details-grid", role: "presentation" }]
};
var DetailCellRenderer = class extends import_ag_grid_community174.Component {
constructor() {
super(...arguments);
this.eDetailGrid = import_ag_grid_community174.RefPlaceholder;
}
wireBeans(beans) {
this.context = beans.context;
}
init(params) {
this.params = params;
this.selectAndSetTemplate();
const compProxy = {
toggleCss: (cssClassName, on) => this.toggleCss(cssClassName, on),
toggleDetailGridCss: (cssClassName, on) => this.eDetailGrid.classList.toggle(cssClassName, on),
setDetailGrid: (gridOptions) => this.setDetailGrid(gridOptions),
setRowData: (rowData) => this.setRowData(rowData),
getGui: () => this.eDetailGrid
};
this.ctrl = this.createManagedBean(new DetailCellRendererCtrl());
this.ctrl.init(compProxy, params);
}
refresh() {
return this.ctrl?.refresh() ?? false;
}
selectAndSetTemplate() {
const params = this.params;
if (params.pinned) {
this.setTemplate(PinnedDetailCellRendererElement);
return;
}
const setDefaultTemplate = () => {
this.setTemplate(DetailCellRendererElement);
};
if ((0, import_ag_grid_community174._missing)(params.template)) {
setDefaultTemplate();
} else {
if (typeof params.template === "string") {
this.setTemplate(params.template, []);
} else if (typeof params.template === "function") {
const templateFunc = params.template;
const template = templateFunc(params);
this.setTemplate(template, []);
} else {
(0, import_ag_grid_community174._warn)(168);
setDefaultTemplate();
}
}
if (this.eDetailGrid == null) {
(0, import_ag_grid_community174._warn)(169);
}
}
setDetailGrid(gridOptions) {
if (!this.eDetailGrid) {
return;
}
const parentFrameworkComponentWrapper = this.context.getBean("frameworkCompWrapper");
const frameworkCompWrapper = new DetailFrameworkComponentWrapper(parentFrameworkComponentWrapper);
const { frameworkOverrides } = this.beans;
const api = (0, import_ag_grid_community174.createGrid)(this.eDetailGrid, gridOptions, {
frameworkOverrides,
providedBeanInstances: { frameworkCompWrapper },
modules: (0, import_ag_grid_community174._getGridRegisteredModules)(this.params.api.getGridId(), gridOptions.rowModelType ?? "clientSide")
});
this.detailApi = api;
this.ctrl?.registerDetailWithMaster(api);
this.addDestroyFunc(() => {
api.destroy();
});
}
setRowData(rowData) {
this.detailApi?.setGridOption("rowData", rowData);
}
};
// packages/ag-grid-enterprise/src/masterDetail/masterDetailApi.ts
function operateOnStore(beans, callback) {
const store = beans.masterDetailSvc?.store;
return store ? callback(store) : void 0;
}
function addDetailGridInfo(beans, id, gridInfo) {
operateOnStore(beans, (store) => {
store[id] = gridInfo;
});
}
function removeDetailGridInfo(beans, id) {
operateOnStore(beans, (store) => {
delete store[id];
});
}
function getDetailGridInfo(beans, id) {
return operateOnStore(beans, (store) => store[id]);
}
function forEachDetailGridInfo(beans, callback) {
operateOnStore(beans, (store) => {
let index = 0;
Object.values(store).forEach((gridInfo) => {
if (gridInfo) {
callback(gridInfo, index++);
}
});
});
}
// packages/ag-grid-enterprise/src/masterDetail/masterDetailModule.css-GENERATED.ts
var masterDetailModuleCSS = (
/*css*/
`.ag-details-row{width:100%}.ag-details-row-fixed-height{height:100%}.ag-details-grid{width:100%}.ag-details-grid-fixed-height{height:100%}`
);
// packages/ag-grid-enterprise/src/masterDetail/masterDetailService.ts
var import_ag_grid_community175 = require("ag-grid-community");
var MasterDetailService = class extends import_ag_grid_community175.BeanStub {
constructor() {
super(...arguments);
this.beanName = "masterDetailSvc";
this.store = {};
}
isEnabled() {
return !!this.gos.get("masterDetail");
}
postConstruct() {
if ((0, import_ag_grid_community175._isClientSideRowModel)(this.gos)) {
this.enabled = this.isEnabled();
}
}
refreshModel(params) {
if (params.changedProps) {
const enabled = this.isEnabled();
if (this.enabled !== enabled) {
this.setMasters(null);
return;
}
}
if (params.rowDataUpdated) {
this.setMasters(params.changedRowNodes);
}
}
setMasters(changedRowNodes) {
const enabled = this.isEnabled();
this.enabled = enabled;
const gos = this.gos;
const isRowMaster = gos.get("isRowMaster");
const treeData = gos.get("treeData");
const setMaster = (row, created, updated) => {
const oldMaster = row.master;
let newMaster = enabled;
if (enabled) {
if (created || updated) {
if (isRowMaster) {
const data = row.data;
newMaster = !!data && !!isRowMaster(data);
}
} else {
newMaster = oldMaster;
}
}
if (!treeData) {
if (newMaster && created) {
const level = this.beans.rowGroupColsSvc?.columns.length ?? 0;
row.expanded = _getRowDefaultExpanded(this.beans, row, level, false);
} else if (!newMaster && oldMaster) {
row.expanded = false;
}
}
if (newMaster !== oldMaster) {
row.master = newMaster;
row.dispatchRowEvent("masterChanged");
}
};
if (changedRowNodes) {
for (const node of changedRowNodes.updates) {
setMaster(node, false, true);
}
for (const node of changedRowNodes.adds) {
setMaster(node, true, false);
}
} else {
const allLeafChildren = (0, import_ag_grid_community175._getClientSideRowModel)(this.beans)?.rootNode?.allLeafChildren;
if (allLeafChildren) {
for (let i = 0, len = allLeafChildren.length; i < len; ++i) {
setMaster(allLeafChildren[i], true, false);
}
}
}
}
/** Used by flatten stage to get or create a detail node from a master node */
getDetail(masterNode) {
if (!masterNode.master || !masterNode.expanded) {
return null;
}
let detailNode = masterNode.detailNode;
if (detailNode) {
return detailNode;
}
detailNode = new import_ag_grid_community175.RowNode(this.beans);
detailNode.detail = true;
detailNode.selectable = false;
detailNode.parent = masterNode;
if ((0, import_ag_grid_community175._exists)(masterNode.id)) {
detailNode.id = "detail_" + masterNode.id;
}
detailNode.data = masterNode.data;
detailNode.level = masterNode.level + 1;
masterNode.detailNode = detailNode;
return detailNode;
}
setupDetailRowAutoHeight(rowCtrl, eDetailGui) {
const { gos, beans } = this;
if (!gos.get("detailRowAutoHeight")) {
return;
}
const checkRowSizeFunc = () => {
const clientHeight = eDetailGui.clientHeight;
if (clientHeight != null && clientHeight > 0) {
const updateRowHeightFunc = () => {
const { rowModel } = this.beans;
const { rowNode } = rowCtrl;
rowNode.setRowHeight(clientHeight);
if ((0, import_ag_grid_community175._isClientSideRowModel)(gos, rowModel) || (0, import_ag_grid_community175._isServerSideRowModel)(gos, rowModel)) {
rowModel.onRowHeightChanged();
}
};
window.setTimeout(updateRowHeightFunc, 0);
}
};
const resizeObserverDestroyFunc = (0, import_ag_grid_community175._observeResize)(beans, eDetailGui, checkRowSizeFunc);
rowCtrl.addDestroyFunc(resizeObserverDestroyFunc);
checkRowSizeFunc();
}
destroy() {
this.store = {};
super.destroy();
}
};
// packages/ag-grid-enterprise/src/masterDetail/masterDetailModule.ts
var SharedMasterDetailModule = {
moduleName: "SharedMasterDetail",
version: VERSION,
beans: [MasterDetailService],
userComponents: { agDetailCellRenderer: DetailCellRenderer },
dynamicBeans: { detailCellRendererCtrl: DetailCellRendererCtrl },
apiFunctions: {
addDetailGridInfo,
removeDetailGridInfo,
getDetailGridInfo,
forEachDetailGridInfo
},
dependsOn: [EnterpriseCoreModule, GroupCellRendererModule, StickyRowModule],
css: [masterDetailModuleCSS]
};
var MasterDetailModule = {
moduleName: "MasterDetail",
version: VERSION,
dependsOn: [SharedMasterDetailModule, ClientSideRowModelHierarchyModule, import_ag_grid_community176.EventApiModule]
};
// packages/ag-grid-enterprise/src/rangeSelection/rangeSelectionModule.ts
var import_ag_grid_community184 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rangeSelection/agFillHandle.ts
var import_ag_grid_community178 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rangeSelection/abstractSelectionHandle.ts
var import_ag_grid_community177 = require("ag-grid-community");
var AbstractSelectionHandle = class extends import_ag_grid_community177.Component {
constructor() {
super(...arguments);
this.changedCalculatedValues = false;
this.dragging = false;
this.shouldDestroyOnEndDragging = false;
}
postConstruct() {
const { dragSvc, rangeSvc } = this.beans;
dragSvc.addDragSource({
dragStartPixels: 0,
eElement: this.getGui(),
onDragStart: this.onDragStart.bind(this),
onDragging: (e) => {
this.dragging = true;
rangeSvc.autoScrollService.check(e);
if (this.changedCalculatedValues) {
this.onDrag(e);
this.changedCalculatedValues = false;
}
},
onDragStop: (e) => {
this.dragging = false;
this.onDragEnd(e);
this.clearDragProperties();
if (this.shouldDestroyOnEndDragging) {
this.destroy();
}
},
onDragCancel: () => {
this.dragging = false;
this.onDragCancel();
this.clearDragProperties();
}
});
this.addManagedElementListeners(this.getGui(), { mousedown: this.preventRangeExtension.bind(this) });
}
getLastCellHovered() {
return this.lastCellHovered;
}
preventRangeExtension(e) {
e.stopPropagation();
}
onDragStart(_) {
[this.cellHoverListener] = this.addManagedElementListeners(this.beans.ctrlsSvc.get("gridCtrl").getGui(), {
mousemove: this.updateValuesOnMove.bind(this)
});
document.body.classList.add(this.getDraggingCssClass());
}
getDraggingCssClass() {
return `ag-dragging-${this.type === 0 /* FILL */ ? "fill" : "range"}-handle`;
}
updateValuesOnMove(e) {
const cell = (0, import_ag_grid_community177._getCellPositionForEvent)(this.gos, e);
if (!cell || this.shouldSkipCell(cell) || this.lastCellHovered && (0, import_ag_grid_community177._areCellsEqual)(cell, this.lastCellHovered)) {
return;
}
this.lastCellHovered = cell;
this.changedCalculatedValues = true;
}
clearDragProperties() {
this.clearValues();
this.beans.rangeSvc.autoScrollService.ensureCleared();
document.body.classList.remove(this.getDraggingCssClass());
}
getType() {
return this.type;
}
refresh(cellCtrl) {
const oldCellComp = this.cellCtrl;
const eGui = this.getGui();
const cellRange = (0, import_ag_grid_community177._last)(this.beans.rangeSvc.getCellRanges());
const start = cellRange.startRow;
const end = cellRange.endRow;
if (start && end) {
const isBefore = (0, import_ag_grid_community177._isRowBefore)(end, start);
if (isBefore) {
this.rangeStartRow = end;
this.rangeEndRow = start;
} else {
this.rangeStartRow = start;
this.rangeEndRow = end;
}
}
if (oldCellComp !== cellCtrl || !(0, import_ag_grid_community177._isVisible)(eGui)) {
this.cellCtrl = cellCtrl;
const eParentOfValue = cellCtrl.comp.getParentOfValue();
if (eParentOfValue) {
eParentOfValue.appendChild(eGui);
}
}
this.cellRange = cellRange;
}
clearValues() {
this.lastCellHovered = void 0;
this.removeListeners();
}
removeListeners() {
const cellHoverListener = this.cellHoverListener;
if (cellHoverListener) {
cellHoverListener();
this.cellHoverListener = void 0;
}
}
destroy() {
if (!this.shouldDestroyOnEndDragging && this.dragging) {
(0, import_ag_grid_community177._setDisplayed)(this.getGui(), false);
this.shouldDestroyOnEndDragging = true;
return;
}
this.shouldDestroyOnEndDragging = false;
super.destroy();
this.removeListeners();
const eGui = this.getGui();
eGui.parentElement?.removeChild(eGui);
}
};
// packages/ag-grid-enterprise/src/rangeSelection/utils.ts
function findLineByLeastSquares(values) {
const len = values.length;
let maxDecimals = 0;
if (len <= 1) {
return values;
}
for (let i = 0; i < values.length; i++) {
const value = values[i];
const splitExponent = value.toString().split("e-");
if (splitExponent.length > 1) {
maxDecimals = Math.max(maxDecimals, parseInt(splitExponent[1], 10));
continue;
}
if (Math.floor(value) === value) {
continue;
}
maxDecimals = Math.max(maxDecimals, value.toString().split(".")[1].length);
}
let sum_x = 0;
let sum_y = 0;
let sum_xy = 0;
let sum_xx = 0;
let y = 0;
for (let x = 0; x < len; x++) {
y = values[x];
sum_x += x;
sum_y += y;
sum_xx += x * x;
sum_xy += x * y;
}
const m = (len * sum_xy - sum_x * sum_y) / (len * sum_xx - sum_x * sum_x);
const b = sum_y / len - m * sum_x / len;
const result = [];
for (let x = 0; x <= len; x++) {
result.push(parseFloat((x * m + b).toFixed(maxDecimals)));
}
return result;
}
// packages/ag-grid-enterprise/src/rangeSelection/agFillHandle.ts
var FillHandleElement = {
tag: "div",
cls: "ag-fill-handle"
};
var AgFillHandle = class extends AbstractSelectionHandle {
constructor() {
super(FillHandleElement);
this.markedCells = [];
this.cellValues = [];
this.isUp = false;
this.isLeft = false;
this.isReduce = false;
this.type = 0 /* FILL */;
}
postConstruct() {
super.postConstruct();
this.addManagedElementListeners(this.getGui(), {
dblclick: this.onDblClick.bind(this)
});
}
onDblClick(e) {
(0, import_ag_grid_community178._stopPropagationForAgGrid)(e);
const { cellRange: initialRange, rangeStartRow, beans } = this;
const { rangeSvc } = beans;
const lastRow = (0, import_ag_grid_community178._getLastRow)(beans);
if (!lastRow) {
return;
}
const finalRange = rangeSvc?.createCellRangeFromCellRangeParams({
rowStartIndex: rangeStartRow.rowIndex,
rowStartPinned: rangeStartRow.rowPinned,
columnStart: initialRange.columns[0],
rowEndIndex: lastRow.rowIndex,
rowEndPinned: lastRow.rowPinned,
columnEnd: (0, import_ag_grid_community178._last)(initialRange.columns)
});
this.dragAxis = "y";
this.isUp = false;
this.isLeft = false;
if (finalRange) {
this.performFill({
event: e,
initialRange,
finalRange
});
}
this.dragAxis = void 0;
}
updateValuesOnMove(e) {
super.updateValuesOnMove(e);
if (!this.initialXY) {
this.initialXY = (0, import_ag_grid_community178._getNormalisedMousePosition)(this.beans, e);
}
const { x, y } = this.initialXY;
const { x: newX, y: newY } = (0, import_ag_grid_community178._getNormalisedMousePosition)(this.beans, e);
const diffX = Math.abs(x - newX);
const diffY = Math.abs(y - newY);
const allowedDirection = this.getFillHandleDirection();
let direction;
if (allowedDirection === "xy") {
direction = diffX > diffY ? "x" : "y";
} else {
direction = allowedDirection;
}
if (direction !== this.dragAxis) {
this.dragAxis = direction;
this.changedCalculatedValues = true;
}
}
shouldSkipCell(cell) {
return (0, import_ag_grid_community178.isRowNumberCol)(cell.column);
}
onDrag(_) {
if (!this.initialPosition) {
const cellCtrl = this.cellCtrl;
if (!cellCtrl) {
return;
}
this.initialPosition = cellCtrl.cellPosition;
}
const lastCellHovered = this.getLastCellHovered();
if (lastCellHovered) {
this.markPathFrom(this.initialPosition, lastCellHovered);
}
}
onDragEnd(e) {
this.initialXY = null;
if (!this.markedCells.length) {
return;
}
const isX = this.dragAxis === "x";
const {
cellRange: initialRange,
rangeStartRow,
rangeEndRow,
beans: { rangeSvc }
} = this;
const colLen = initialRange.columns.length;
let finalRange;
if (!this.isUp && !this.isLeft) {
finalRange = rangeSvc.createCellRangeFromCellRangeParams({
rowStartIndex: rangeStartRow.rowIndex,
rowStartPinned: rangeStartRow.rowPinned,
columnStart: initialRange.columns[0],
rowEndIndex: isX ? rangeEndRow.rowIndex : this.lastCellMarked.rowIndex,
rowEndPinned: isX ? rangeEndRow.rowPinned : this.lastCellMarked.rowPinned,
columnEnd: isX ? this.lastCellMarked.column : initialRange.columns[colLen - 1]
});
} else {
const startRow = isX ? rangeStartRow : this.lastCellMarked;
finalRange = rangeSvc.createCellRangeFromCellRangeParams({
rowStartIndex: startRow.rowIndex,
rowStartPinned: startRow.rowPinned,
columnStart: isX ? this.lastCellMarked.column : initialRange.columns[0],
rowEndIndex: rangeEndRow.rowIndex,
rowEndPinned: rangeEndRow.rowPinned,
columnEnd: initialRange.columns[colLen - 1]
});
}
if (finalRange) {
this.performFill({
event: e,
initialRange,
finalRange,
shouldUpdateRange: true
});
}
}
onDragCancel() {
this.initialXY = null;
if (!this.markedCells.length) {
return;
}
this.clearMarkedPath();
}
performFill({
event,
initialRange,
finalRange,
shouldUpdateRange
}) {
const { eventSvc, rangeSvc } = this.beans;
eventSvc.dispatchEvent({ type: "fillStart" });
this.handleValueChanged(initialRange, finalRange, event);
if (shouldUpdateRange) {
rangeSvc.setCellRanges([finalRange]);
}
eventSvc.dispatchEvent({
type: "fillEnd",
initialRange,
finalRange
});
}
getFillHandleDirection() {
const direction = (0, import_ag_grid_community178._getFillHandle)(this.gos)?.direction;
if (!direction) {
return "xy";
}
if (direction !== "x" && direction !== "y" && direction !== "xy") {
(0, import_ag_grid_community178._warn)(177);
return "xy";
}
return direction;
}
handleValueChanged(initialRange, finalRange, e) {
const { beans } = this;
const { rangeSvc, gos, valueSvc } = beans;
const initialRangeEndRow = rangeSvc.getRangeEndRow(initialRange);
const initialRangeStartRow = rangeSvc.getRangeStartRow(initialRange);
const finalRangeEndRow = rangeSvc.getRangeEndRow(finalRange);
const finalRangeStartRow = rangeSvc.getRangeStartRow(finalRange);
const isVertical = this.dragAxis === "y";
if (this.isReduce && !(0, import_ag_grid_community178._getFillHandle)(gos)?.suppressClearOnFillReduction) {
const columns = isVertical ? initialRange.columns : initialRange.columns.filter((col) => finalRange.columns.indexOf(col) < 0);
const startRow = isVertical ? (0, import_ag_grid_community178._getRowBelow)(beans, finalRangeEndRow) : finalRangeStartRow;
if (startRow) {
this.clearCellsInRange(startRow, initialRangeEndRow, columns);
}
return;
}
const values = [];
const initialValues = [];
const initialNonAggregatedValues = [];
const initialFormattedValues = [];
let withinInitialRange = true;
let idx = 0;
const resetValues = () => {
values.length = 0;
initialValues.length = 0;
initialNonAggregatedValues.length = 0;
initialFormattedValues.length = 0;
idx = 0;
};
const iterateAcrossCells = (column, columns) => {
let currentRow = this.isUp ? initialRangeEndRow : initialRangeStartRow;
let finished = false;
if (isVertical) {
withinInitialRange = true;
resetValues();
}
while (!finished && currentRow) {
const rowNode = (0, import_ag_grid_community178._getRowNode)(beans, currentRow);
if (!rowNode) {
break;
}
if (isVertical && column) {
fillValues(
values,
column,
rowNode,
() => !(0, import_ag_grid_community178._isSameRow)(currentRow, this.isUp ? initialRangeStartRow : initialRangeEndRow)
);
} else if (columns) {
withinInitialRange = true;
resetValues();
columns.forEach(
(col) => fillValues(
values,
col,
rowNode,
() => col !== (this.isLeft ? initialRange.columns[0] : (0, import_ag_grid_community178._last)(initialRange.columns))
)
);
}
finished = (0, import_ag_grid_community178._isSameRow)(currentRow, this.isUp ? finalRangeStartRow : finalRangeEndRow);
currentRow = this.isUp ? (0, import_ag_grid_community178._getRowAbove)(this.beans, currentRow) : (0, import_ag_grid_community178._getRowBelow)(beans, currentRow);
}
};
const fillValues = (currentValues, col, rowNode, updateInitialSet) => {
let currentValue;
let skipValue = false;
if (withinInitialRange) {
currentValue = valueSvc.getValue(col, rowNode);
initialValues.push(currentValue);
initialNonAggregatedValues.push(valueSvc.getValue(col, rowNode, true));
initialFormattedValues.push(valueSvc.formatValue(col, rowNode, currentValue));
withinInitialRange = updateInitialSet();
} else {
const { value, fromUserFunction, sourceCol, sourceRowNode } = this.processValues({
event: e,
values: currentValues,
initialValues,
initialNonAggregatedValues,
initialFormattedValues,
col,
rowNode,
idx: idx++
});
currentValue = value;
if (col.isCellEditable(rowNode)) {
const cellValue = valueSvc.getValue(col, rowNode);
if (!fromUserFunction) {
if (sourceCol) {
const sourceColDef = sourceCol.getColDef();
if (sourceColDef.useValueFormatterForExport !== false && sourceColDef.valueFormatter) {
const formattedValue = valueSvc.formatValue(sourceCol, sourceRowNode, currentValue);
if (formattedValue != null) {
currentValue = formattedValue;
}
}
}
if (col.getColDef().useValueParserForImport !== false) {
currentValue = valueSvc.parseValue(
col,
rowNode,
// if no sourceCol, then currentValue is a number
sourceCol ? currentValue : (0, import_ag_grid_community178._toStringOrNull)(currentValue),
cellValue
);
}
}
if (!fromUserFunction || cellValue !== currentValue) {
rowNode.setDataValue(col, currentValue, "rangeSvc");
} else {
skipValue = true;
}
}
}
if (!skipValue) {
currentValues.push({
value: currentValue,
column: col,
rowNode
});
}
};
if (isVertical) {
initialRange.columns.forEach((col) => {
iterateAcrossCells(col);
});
} else {
const columns = this.isLeft ? [...finalRange.columns].reverse() : finalRange.columns;
iterateAcrossCells(void 0, columns);
}
this.beans.editSvc?.stopEditing(void 0, { source: "fillHandle" });
}
clearCellsInRange(startRow, endRow, columns) {
const cellRange = {
startRow,
endRow,
columns,
startColumn: columns[0]
};
this.beans.rangeSvc.clearCellRangeCellValues({ cellRanges: [cellRange] });
}
processValues(params) {
const { event, values, initialValues, initialNonAggregatedValues, initialFormattedValues, col, rowNode, idx } = params;
const userFillOperation = (0, import_ag_grid_community178._getFillHandle)(this.gos)?.setFillValue;
const isVertical = this.dragAxis === "y";
let direction;
if (isVertical) {
direction = this.isUp ? "up" : "down";
} else {
direction = this.isLeft ? "left" : "right";
}
if (userFillOperation) {
const params2 = (0, import_ag_grid_community178._addGridCommonParams)(this.gos, {
event,
values: values.map(({ value }) => value),
initialValues,
initialNonAggregatedValues,
initialFormattedValues,
currentIndex: idx,
currentCellValue: this.beans.valueSvc.getValue(col, rowNode),
direction,
column: col,
rowNode
});
const userResult = userFillOperation(params2);
if (userResult !== false) {
return { value: userResult, fromUserFunction: true };
}
}
const allNumbers = !values.some(({ value }) => {
const asFloat = parseFloat(value);
return isNaN(asFloat) || asFloat.toString() !== value.toString();
});
if (event.altKey || !allNumbers) {
if (allNumbers && initialValues.length === 1) {
const multiplier = this.isUp || this.isLeft ? -1 : 1;
return { value: parseFloat((0, import_ag_grid_community178._last)(values).value) + 1 * multiplier, fromUserFunction: false };
}
const { value, column: sourceCol, rowNode: sourceRowNode } = values[idx % values.length];
return { value, fromUserFunction: false, sourceCol, sourceRowNode };
}
return {
value: (0, import_ag_grid_community178._last)(findLineByLeastSquares(values.map(({ value }) => Number(value)))),
fromUserFunction: false
};
}
clearValues() {
this.clearMarkedPath();
this.clearCellValues();
this.lastCellMarked = void 0;
super.clearValues();
}
clearMarkedPath() {
this.markedCells.forEach((cell) => {
if (!cell.isAlive()) {
return;
}
const { comp } = cell;
comp.toggleCss("ag-selection-fill-top", false);
comp.toggleCss("ag-selection-fill-right", false);
comp.toggleCss("ag-selection-fill-bottom", false);
comp.toggleCss("ag-selection-fill-left", false);
});
this.markedCells.length = 0;
this.isUp = false;
this.isLeft = false;
this.isReduce = false;
}
clearCellValues() {
this.cellValues.length = 0;
}
markPathFrom(initialPosition, currentPosition) {
this.clearMarkedPath();
this.clearCellValues();
if (this.dragAxis === "y") {
if ((0, import_ag_grid_community178._isSameRow)(currentPosition, initialPosition)) {
return;
}
const isBefore = (0, import_ag_grid_community178._isRowBefore)(currentPosition, initialPosition);
const { rangeStartRow, rangeEndRow } = this;
if (isBefore && (currentPosition.rowPinned == rangeStartRow.rowPinned && currentPosition.rowIndex >= rangeStartRow.rowIndex || rangeStartRow.rowPinned != rangeEndRow.rowPinned && currentPosition.rowPinned == rangeEndRow.rowPinned && currentPosition.rowIndex <= rangeEndRow.rowIndex)) {
this.reduceVertical(initialPosition, currentPosition);
this.isReduce = true;
} else {
this.extendVertical(initialPosition, currentPosition, isBefore);
this.isReduce = false;
}
} else {
const initialColumn = initialPosition.column;
const currentColumn = currentPosition.column;
if (initialColumn === currentColumn) {
return;
}
const displayedColumns = this.beans.visibleCols.allCols;
const initialIndex = displayedColumns.indexOf(initialColumn);
const currentIndex = displayedColumns.indexOf(currentColumn);
if (currentIndex <= initialIndex && currentIndex >= displayedColumns.indexOf(this.cellRange.columns[0])) {
this.reduceHorizontal(initialPosition, currentPosition);
this.isReduce = true;
} else {
this.extendHorizontal(initialPosition, currentPosition, currentIndex < initialIndex);
this.isReduce = false;
}
}
this.lastCellMarked = currentPosition;
}
extendVertical(initialPosition, endPosition, isMovingUp) {
const beans = this.beans;
const { rangeSvc } = beans;
let row = initialPosition;
do {
const cellRange = this.cellRange;
const colLen = cellRange.columns.length;
for (let i = 0; i < colLen; i++) {
const column = cellRange.columns[i];
const rowPos = { rowIndex: row.rowIndex, rowPinned: row.rowPinned };
const cellPos = { ...rowPos, column };
const cellInRange = rangeSvc.isCellInSpecificRange(cellPos, cellRange);
const isInitialRow = (0, import_ag_grid_community178._isSameRow)(row, initialPosition);
if (isMovingUp) {
this.isUp = true;
}
if (!isInitialRow) {
const cell = (0, import_ag_grid_community178._getCellByPosition)(beans, cellPos);
if (cell) {
this.markedCells.push(cell);
const cellComp = cell.comp;
if (!cellInRange) {
cellComp.toggleCss("ag-selection-fill-left", i === 0);
cellComp.toggleCss("ag-selection-fill-right", i === colLen - 1);
}
cellComp.toggleCss(
isMovingUp ? "ag-selection-fill-top" : "ag-selection-fill-bottom",
(0, import_ag_grid_community178._isSameRow)(row, endPosition)
);
}
}
}
if ((0, import_ag_grid_community178._isSameRow)(row, endPosition)) {
break;
}
} while (
// tslint:disable-next-line
row = isMovingUp ? (0, import_ag_grid_community178._getRowAbove)(this.beans, row) : (0, import_ag_grid_community178._getRowBelow)(beans, row)
);
}
reduceVertical(initialPosition, endPosition) {
let row = initialPosition;
const beans = this.beans;
do {
const cellRange = this.cellRange;
const colLen = cellRange.columns.length;
const isLastRow = (0, import_ag_grid_community178._isSameRow)(row, endPosition);
for (let i = 0; i < colLen; i++) {
const rowPos = { rowIndex: row.rowIndex, rowPinned: row.rowPinned };
const celPos = { ...rowPos, column: cellRange.columns[i] };
const cell = (0, import_ag_grid_community178._getCellByPosition)(beans, celPos);
if (cell) {
this.markedCells.push(cell);
cell.comp.toggleCss("ag-selection-fill-bottom", (0, import_ag_grid_community178._isSameRow)(row, endPosition));
}
}
if (isLastRow) {
break;
}
} while (row = (0, import_ag_grid_community178._getRowAbove)(beans, row));
}
extendHorizontal(initialPosition, endPosition, isMovingLeft) {
const beans = this.beans;
const { visibleCols } = beans;
const allCols = visibleCols.allCols;
const startCol = allCols.indexOf(isMovingLeft ? endPosition.column : initialPosition.column);
const endCol = allCols.indexOf(isMovingLeft ? this.cellRange.columns[0] : endPosition.column);
const offset = isMovingLeft ? 0 : 1;
const colsToMark = allCols.slice(startCol + offset, endCol + offset);
const { rangeStartRow, rangeEndRow } = this;
colsToMark.forEach((column) => {
let row = rangeStartRow;
let isLastRow = false;
do {
isLastRow = (0, import_ag_grid_community178._isSameRow)(row, rangeEndRow);
const cell = (0, import_ag_grid_community178._getCellByPosition)(beans, {
rowIndex: row.rowIndex,
rowPinned: row.rowPinned,
column
});
if (cell) {
this.markedCells.push(cell);
const cellComp = cell.comp;
cellComp.toggleCss("ag-selection-fill-top", (0, import_ag_grid_community178._isSameRow)(row, rangeStartRow));
cellComp.toggleCss("ag-selection-fill-bottom", (0, import_ag_grid_community178._isSameRow)(row, rangeEndRow));
if (isMovingLeft) {
this.isLeft = true;
cellComp.toggleCss("ag-selection-fill-left", column === colsToMark[0]);
} else {
cellComp.toggleCss("ag-selection-fill-right", column === (0, import_ag_grid_community178._last)(colsToMark));
}
}
row = (0, import_ag_grid_community178._getRowBelow)(beans, row);
} while (!isLastRow);
});
}
reduceHorizontal(initialPosition, endPosition) {
const beans = this.beans;
const { visibleCols } = beans;
const allCols = visibleCols.allCols;
const startCol = allCols.indexOf(endPosition.column);
const endCol = allCols.indexOf(initialPosition.column);
const colsToMark = allCols.slice(startCol, endCol);
const { rangeStartRow, rangeEndRow } = this;
colsToMark.forEach((column) => {
let row = rangeStartRow;
let isLastRow = false;
do {
isLastRow = (0, import_ag_grid_community178._isSameRow)(row, rangeEndRow);
const cell = (0, import_ag_grid_community178._getCellByPosition)(this.beans, {
rowIndex: row.rowIndex,
rowPinned: row.rowPinned,
column
});
if (cell) {
this.markedCells.push(cell);
cell.comp.toggleCss("ag-selection-fill-right", column === colsToMark[0]);
}
row = (0, import_ag_grid_community178._getRowBelow)(beans, row);
} while (!isLastRow);
});
}
refresh(cellCtrl) {
const cellRange = this.beans.rangeSvc.getCellRanges()[0];
const isColumnRange = !cellRange.startRow || !cellRange.endRow;
if (isColumnRange) {
this.destroy();
return;
}
super.refresh(cellCtrl);
}
};
// packages/ag-grid-enterprise/src/rangeSelection/agRangeHandle.ts
var import_ag_grid_community179 = require("ag-grid-community");
var AgRangeHandle = class extends AbstractSelectionHandle {
constructor() {
super({ tag: "div", cls: "ag-range-handle" });
this.type = 1 /* RANGE */;
this.rangeFixed = false;
}
onDrag(_) {
const lastCellHovered = this.getLastCellHovered();
if (!lastCellHovered) {
return;
}
const rangeSvc = this.beans.rangeSvc;
const cellRanges = rangeSvc.getCellRanges();
const lastRange = (0, import_ag_grid_community179._last)(cellRanges);
if (!this.rangeFixed) {
this.fixRangeStartEnd(lastRange);
this.rangeFixed = true;
}
this.endPosition = {
rowIndex: lastCellHovered.rowIndex,
rowPinned: lastCellHovered.rowPinned,
column: lastCellHovered.column
};
if (cellRanges.length === 2 && cellRanges[0].type === import_ag_grid_community179.CellRangeType.DIMENSION && lastRange.type === import_ag_grid_community179.CellRangeType.VALUE) {
const rowChanged = !(0, import_ag_grid_community179._isSameRow)(this.endPosition, rangeSvc.getRangeEndRow(lastRange));
if (rowChanged) {
rangeSvc.updateRangeEnd(
cellRanges[0],
{
...this.endPosition,
column: cellRanges[0].columns[0]
},
true
);
}
}
rangeSvc.extendLatestRangeToCell(this.endPosition);
}
shouldSkipCell(_) {
return false;
}
onDragEnd(_) {
const cellRange = (0, import_ag_grid_community179._last)(this.beans.rangeSvc.getCellRanges());
this.fixRangeStartEnd(cellRange);
this.rangeFixed = false;
}
onDragCancel() {
this.rangeFixed = false;
}
fixRangeStartEnd(cellRange) {
const rangeSvc = this.beans.rangeSvc;
const startRow = rangeSvc.getRangeStartRow(cellRange);
const endRow = rangeSvc.getRangeEndRow(cellRange);
const column = cellRange.columns[0];
cellRange.startRow = startRow;
cellRange.endRow = endRow;
cellRange.startColumn = column;
}
};
// packages/ag-grid-enterprise/src/rangeSelection/rangeSelection.css-GENERATED.ts
var rangeSelectionCSS = (
/*css*/
`.ag-body-viewport:not(.ag-has-focus) .ag-cell-range-single-cell:not(.ag-cell-inline-editing),.ag-cell-range-selected.ag-cell-range-chart,.ag-cell-range-selected:not(.ag-cell-focus){background-color:var(--ag-range-selection-background-color);&.ag-cell-range-chart{background-color:var(--ag-range-selection-chart-background-color)!important;&.ag-cell-range-chart-category{background-color:var(--ag-range-selection-chart-category-background-color)!important}}}.ag-cell-range-selected-1.ag-cell-range-chart,.ag-cell-range-selected-1:not(.ag-cell-focus),.ag-root:not(.ag-context-menu-open) .ag-body-viewport:not(.ag-has-focus) .ag-cell-range-selected-1:not(.ag-cell-inline-editing){background-color:var(--ag-range-selection-background-color)}.ag-cell-range-selected-2.ag-cell-range-chart,.ag-cell-range-selected-2:not(.ag-cell-focus){background-image:linear-gradient(var(--ag-range-selection-background-color),var(--ag-range-selection-background-color))}.ag-cell-range-selected-3.ag-cell-range-chart,.ag-cell-range-selected-3:not(.ag-cell-focus){background-image:linear-gradient(var(--ag-range-selection-background-color),var(--ag-range-selection-background-color)),linear-gradient(var(--ag-range-selection-background-color),var(--ag-range-selection-background-color))}.ag-cell-range-selected-4.ag-cell-range-chart,.ag-cell-range-selected-4:not(.ag-cell-focus){background-image:linear-gradient(var(--ag-range-selection-background-color),var(--ag-range-selection-background-color)),linear-gradient(var(--ag-range-selection-background-color),var(--ag-range-selection-background-color)),linear-gradient(var(--ag-range-selection-background-color),var(--ag-range-selection-background-color))}.ag-cell.ag-cell-range-selected:not(.ag-cell-range-single-cell){&.ag-cell-range-top{border-top-color:var(--ag-range-selection-border-color);border-top-style:var(--ag-range-selection-border-style)}&.ag-cell-range-right{border-right-color:var(--ag-range-selection-border-color);border-right-style:var(--ag-range-selection-border-style)}&.ag-cell-range-bottom{border-bottom-color:var(--ag-range-selection-border-color);border-bottom-style:var(--ag-range-selection-border-style)}&.ag-cell-range-left{border-left-color:var(--ag-range-selection-border-color);border-left-style:var(--ag-range-selection-border-style)}}.ag-cell.ag-selection-fill-top,.ag-cell.ag-selection-fill-top.ag-cell-range-selected{border-top:1px dashed;border-top-color:var(--ag-range-selection-border-color)}:where(.ag-ltr) .ag-cell.ag-selection-fill-right,:where(.ag-ltr) .ag-cell.ag-selection-fill-right.ag-cell-range-selected{border-right:1px dashed var(--ag-range-selection-border-color)!important}:where(.ag-rtl) .ag-cell.ag-selection-fill-right,:where(.ag-rtl) .ag-cell.ag-selection-fill-right.ag-cell-range-selected{border-left:1px dashed var(--ag-range-selection-border-color)!important}.ag-cell.ag-selection-fill-bottom,.ag-cell.ag-selection-fill-bottom.ag-cell-range-selected{border-bottom:1px dashed;border-bottom-color:var(--ag-range-selection-border-color)}:where(.ag-ltr) .ag-cell.ag-selection-fill-left,:where(.ag-ltr) .ag-cell.ag-selection-fill-left.ag-cell-range-selected{border-left:1px dashed var(--ag-range-selection-border-color)!important}:where(.ag-rtl) .ag-cell.ag-selection-fill-left,:where(.ag-rtl) .ag-cell.ag-selection-fill-left.ag-cell-range-selected{border-right:1px dashed var(--ag-range-selection-border-color)!important}.ag-fill-handle,.ag-range-handle{background-color:var(--ag-range-selection-border-color);bottom:-1px;height:6px;position:absolute;width:6px}:where(.ag-ltr) .ag-fill-handle,:where(.ag-ltr) .ag-range-handle{right:-1px}:where(.ag-rtl) .ag-fill-handle,:where(.ag-rtl) .ag-range-handle{left:-1px}.ag-fill-handle{cursor:crosshair}:where(.ag-ltr) .ag-range-handle{cursor:nwse-resize}:where(.ag-rtl) .ag-range-handle{cursor:nesw-resize}`
);
// packages/ag-grid-enterprise/src/rangeSelection/rangeSelectionApi.ts
function getCellRanges(beans) {
return beans.rangeSvc?.getCellRanges() ?? null;
}
function addCellRange(beans, params) {
beans.rangeSvc?.addCellRange(params);
}
function clearRangeSelection(beans) {
beans.rangeSvc?.removeAllCellRanges();
}
// packages/ag-grid-enterprise/src/rangeSelection/rangeService.ts
var import_ag_grid_community183 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/rangeSelection/cellRangeFeature.ts
var import_ag_grid_community180 = require("ag-grid-community");
var CSS_CELL_RANGE_SELECTED = "ag-cell-range-selected";
var CSS_CELL_RANGE_CHART = "ag-cell-range-chart";
var CSS_CELL_RANGE_SINGLE_CELL = "ag-cell-range-single-cell";
var CSS_CELL_RANGE_CHART_CATEGORY = "ag-cell-range-chart-category";
var CSS_CELL_RANGE_HANDLE = "ag-cell-range-handle";
var CSS_CELL_RANGE_TOP = "ag-cell-range-top";
var CSS_CELL_RANGE_RIGHT = "ag-cell-range-right";
var CSS_CELL_RANGE_BOTTOM = "ag-cell-range-bottom";
var CSS_CELL_RANGE_LEFT = "ag-cell-range-left";
function _isRangeHandleEnabled(gos) {
const selection = gos.get("cellSelection");
const useNewAPI = selection !== void 0;
if (!useNewAPI) {
return gos.get("enableRangeHandle");
}
return typeof selection !== "boolean" ? selection.handle?.mode === "range" : false;
}
function _isFillHandleEnabled(gos) {
const selection = gos.get("cellSelection");
const useNewAPI = selection !== void 0;
if (!useNewAPI) {
return gos.get("enableFillHandle");
}
return typeof selection !== "boolean" ? selection.handle?.mode === "fill" : false;
}
var CellRangeFeature = class {
constructor(beans, cellCtrl) {
this.beans = beans;
this.cellCtrl = cellCtrl;
this.rangeSvc = beans.rangeSvc;
}
setComp(cellComp) {
this.cellComp = cellComp;
this.eGui = this.cellCtrl.eGui;
this.onCellSelectionChanged();
}
onCellSelectionChanged() {
const cellComp = this.cellComp;
if (!cellComp) {
return;
}
const { rangeSvc, cellCtrl, eGui } = this;
const rangeCount = rangeSvc.getCellRangeCount(cellCtrl.cellPosition);
this.rangeCount = rangeCount;
const hasChartRange = this.getHasChartRange();
this.hasChartRange = hasChartRange;
cellComp.toggleCss(CSS_CELL_RANGE_SELECTED, rangeCount !== 0);
cellComp.toggleCss(`${CSS_CELL_RANGE_SELECTED}-1`, rangeCount === 1);
cellComp.toggleCss(`${CSS_CELL_RANGE_SELECTED}-2`, rangeCount === 2);
cellComp.toggleCss(`${CSS_CELL_RANGE_SELECTED}-3`, rangeCount === 3);
cellComp.toggleCss(`${CSS_CELL_RANGE_SELECTED}-4`, rangeCount >= 4);
cellComp.toggleCss(CSS_CELL_RANGE_CHART, hasChartRange);
(0, import_ag_grid_community180._setAriaSelected)(eGui, rangeCount > 0 ? true : void 0);
cellComp.toggleCss(CSS_CELL_RANGE_SINGLE_CELL, this.isSingleCell());
this.updateRangeBorders();
this.refreshHandle();
}
updateRangeBorders() {
const rangeBorders = this.getRangeBorders();
const isSingleCell = this.isSingleCell();
const isTop = !isSingleCell && rangeBorders.top;
const isRight = !isSingleCell && rangeBorders.right;
const isBottom = !isSingleCell && rangeBorders.bottom;
const isLeft = !isSingleCell && rangeBorders.left;
const cellComp = this.cellComp;
cellComp.toggleCss(CSS_CELL_RANGE_TOP, isTop);
cellComp.toggleCss(CSS_CELL_RANGE_RIGHT, isRight);
cellComp.toggleCss(CSS_CELL_RANGE_BOTTOM, isBottom);
cellComp.toggleCss(CSS_CELL_RANGE_LEFT, isLeft);
}
isSingleCell() {
const { rangeSvc } = this;
return this.rangeCount === 1 && !!rangeSvc && !rangeSvc.isMoreThanOneCell();
}
getHasChartRange() {
const { rangeSvc } = this;
if (!this.rangeCount || !rangeSvc) {
return false;
}
const cellRanges = rangeSvc.getCellRanges();
return cellRanges.length > 0 && cellRanges.every((range) => [import_ag_grid_community180.CellRangeType.DIMENSION, import_ag_grid_community180.CellRangeType.VALUE].includes(range.type));
}
updateRangeBordersIfRangeCount() {
if (this.rangeCount > 0) {
this.updateRangeBorders();
this.refreshHandle();
}
}
getRangeBorders() {
const isRtl = this.beans.gos.get("enableRtl");
let top = false;
let right = false;
let bottom = false;
let left = false;
const {
rangeSvc,
beans: { visibleCols },
cellCtrl: { cellPosition }
} = this;
const thisCol = cellPosition.column;
const ranges = rangeSvc.getCellRanges().filter((range) => rangeSvc.isCellInSpecificRange(cellPosition, range));
if (!ranges.length) {
return { top, right, bottom, left };
}
let leftCol;
let rightCol;
if (isRtl) {
leftCol = visibleCols.getColAfter(thisCol);
rightCol = visibleCols.getColBefore(thisCol);
} else {
leftCol = visibleCols.getColBefore(thisCol);
rightCol = visibleCols.getColAfter(thisCol);
}
if (!leftCol) {
left = true;
}
if (!rightCol) {
right = true;
}
for (let i = 0; i < ranges.length; i++) {
if (top && right && bottom && left) {
break;
}
const range = ranges[i];
const startRow = rangeSvc.getRangeStartRow(range);
const endRow = rangeSvc.getRangeEndRow(range);
if (!top && (0, import_ag_grid_community180._isSameRow)(startRow, cellPosition)) {
top = true;
}
if (!bottom && (0, import_ag_grid_community180._isSameRow)(endRow, cellPosition)) {
bottom = true;
}
if (!left && leftCol && range.columns.indexOf(leftCol) < 0) {
left = true;
}
if (!right && rightCol && range.columns.indexOf(rightCol) < 0) {
right = true;
}
}
return { top, right, bottom, left };
}
refreshHandle() {
if (this.beans.context.isDestroyed()) {
return;
}
const shouldHaveSelectionHandle = this.shouldHaveSelectionHandle();
if (this.selectionHandle && !shouldHaveSelectionHandle) {
this.selectionHandle = this.beans.context.destroyBean(this.selectionHandle);
}
if (shouldHaveSelectionHandle) {
this.addSelectionHandle();
}
this.cellComp.toggleCss(CSS_CELL_RANGE_HANDLE, !!this.selectionHandle);
}
shouldHaveSelectionHandle() {
const { gos, editSvc } = this.beans;
const rangeSvc = this.rangeSvc;
const cellRanges = rangeSvc.getCellRanges();
const rangesLen = cellRanges.length;
if (this.rangeCount < 1 || rangesLen < 1) {
return false;
}
const cellRange = (0, import_ag_grid_community180._last)(cellRanges);
const { cellPosition, column } = this.cellCtrl;
const isFillHandleAvailable = _isFillHandleEnabled(gos) && !column.isSuppressFillHandle();
const isRangeHandleAvailable = _isRangeHandleEnabled(gos);
const isCellEditing = editSvc?.isEditing(this.cellCtrl, { withOpenEditor: true });
let handleIsAvailable = rangesLen === 1 && !isCellEditing && (isFillHandleAvailable || isRangeHandleAvailable);
if (this.hasChartRange) {
const hasCategoryRange = cellRanges[0].type === import_ag_grid_community180.CellRangeType.DIMENSION;
const isCategoryCell = hasCategoryRange && rangeSvc.isCellInSpecificRange(cellPosition, cellRanges[0]);
this.cellComp.toggleCss(CSS_CELL_RANGE_CHART_CATEGORY, isCategoryCell);
handleIsAvailable = cellRange.type === import_ag_grid_community180.CellRangeType.VALUE;
}
return handleIsAvailable && cellRange.endRow != null && rangeSvc.isContiguousRange(cellRange) && rangeSvc.isBottomRightCell(cellRange, cellPosition);
}
addSelectionHandle() {
const { beans, rangeSvc } = this;
const cellRangeType = (0, import_ag_grid_community180._last)(rangeSvc.getCellRanges()).type;
const selectionHandleFill = _isFillHandleEnabled(beans.gos) && (0, import_ag_grid_community180._missing)(cellRangeType);
const type = selectionHandleFill ? 0 /* FILL */ : 1 /* RANGE */;
if (this.selectionHandle && this.selectionHandle.getType() !== type) {
this.selectionHandle = beans.context.destroyBean(this.selectionHandle);
}
if (!this.selectionHandle) {
const selectionHandle = beans.registry.createDynamicBean(
type === 0 /* FILL */ ? "fillHandle" : "rangeHandle",
false
);
if (selectionHandle) {
this.selectionHandle = beans.context.createBean(selectionHandle);
}
}
this.selectionHandle?.refresh(this.cellCtrl);
}
destroy() {
this.beans.context.destroyBean(this.selectionHandle);
}
};
// packages/ag-grid-enterprise/src/rangeSelection/dragListenerFeature.ts
var import_ag_grid_community181 = require("ag-grid-community");
var DragListenerFeature = class extends import_ag_grid_community181.BeanStub {
constructor(eContainer) {
super();
this.eContainer = eContainer;
}
postConstruct() {
const { beans, gos, eContainer } = this;
const rangeSvc = beans.rangeSvc;
const params = {
eElement: eContainer,
onDragStart: rangeSvc.onDragStart.bind(rangeSvc),
onDragStop: rangeSvc.onDragStop.bind(rangeSvc),
onDragging: rangeSvc.onDragging.bind(rangeSvc)
};
const dragSvc = beans.dragSvc;
const enableFeature = dragSvc.addDragSource.bind(dragSvc, params);
const disableFeature = dragSvc.removeDragSource.bind(dragSvc, params);
this.addManagedPropertyListeners(["enableRangeSelection", "cellSelection"], () => {
if ((0, import_ag_grid_community181._isCellSelectionEnabled)(gos)) {
enableFeature();
} else {
disableFeature();
}
});
this.addDestroyFunc(disableFeature);
if ((0, import_ag_grid_community181._isCellSelectionEnabled)(gos)) {
enableFeature();
}
}
};
// packages/ag-grid-enterprise/src/rangeSelection/rangeHeaderHighlightFeature.ts
var import_ag_grid_community182 = require("ag-grid-community");
var RangeHeaderHighlightFeature = class extends import_ag_grid_community182.BeanStub {
constructor(column, comp) {
super();
this.column = column;
this.comp = comp;
this.columnMap = /* @__PURE__ */ new Map();
this.isActive = false;
this.resetColumnMap();
}
postConstruct() {
this.addManagedPropertyListener("cellSelection", () => {
this.refreshActive();
});
this.refreshActive();
this.setupRangeHeaderHighlight();
}
resetColumnMap() {
this.columnMap.clear();
let columns;
if (this.column.isColumn) {
columns = [this.column];
} else {
columns = this.column.getDisplayedLeafColumns();
}
for (const column of columns) {
this.columnMap.set(column, false);
}
}
refreshActive() {
const { gos, rangeSvc } = this.beans;
const selection = gos.get("cellSelection");
this.isActive = !!(selection && rangeSvc && typeof selection === "object" && selection.enableHeaderHighlight);
}
setupRangeHeaderHighlight() {
const listener = this.onRangeSelectionChanged.bind(this);
this.addManagedEventListeners({
rangeSelectionChanged: listener,
columnPinned: listener,
columnMoved: listener,
columnGroupOpened: listener
});
listener();
}
onRangeSelectionChanged() {
if (!this.isActive) {
return;
}
this.resetColumnMap();
const ranges = this.beans.rangeSvc.getCellRanges();
let hasRange = false;
let isAllColumnRange = true;
for (const range of ranges) {
if (hasRange) {
break;
}
for (const column of range.columns) {
if (this.columnMap.has(column)) {
this.columnMap.set(column, true);
hasRange || (hasRange = true);
}
}
}
for (const value of Array.from(this.columnMap.values())) {
if (value === false) {
isAllColumnRange = false;
break;
}
}
this.comp.toggleCss("ag-header-range-highlight", hasRange && isAllColumnRange);
}
destroy() {
super.destroy();
this.comp = null;
this.column = null;
}
};
// packages/ag-grid-enterprise/src/rangeSelection/rangeService.ts
var RangeService = class extends import_ag_grid_community183.BeanStub {
constructor() {
super(...arguments);
this.beanName = "rangeSvc";
this.cellRanges = [];
this.bodyScrollListener = this.onBodyScroll.bind(this);
this.dragging = false;
this.intersectionRange = false;
}
wireBeans(beans) {
this.rowModel = beans.rowModel;
this.dragSvc = beans.dragSvc;
this.colModel = beans.colModel;
this.visibleCols = beans.visibleCols;
this.cellNavigation = beans.cellNavigation;
this.ctrlsSvc = beans.ctrlsSvc;
this.valueSvc = beans.valueSvc;
}
postConstruct() {
const onColumnsChanged = this.onColumnsChanged.bind(this);
const removeAllCellRanges = () => this.removeAllCellRanges();
const refreshLastRangeStart = this.refreshLastRangeStart.bind(this);
this.addManagedEventListeners({
newColumnsLoaded: onColumnsChanged,
columnVisible: onColumnsChanged,
columnValueChanged: onColumnsChanged,
columnPivotModeChanged: removeAllCellRanges,
columnRowGroupChanged: removeAllCellRanges,
columnPivotChanged: removeAllCellRanges,
columnGroupOpened: refreshLastRangeStart,
columnMoved: refreshLastRangeStart,
columnPinned: refreshLastRangeStart
});
this.ctrlsSvc.whenReady(this, (p) => {
const gridBodyCtrl = p.gridBodyCtrl;
this.autoScrollService = new import_ag_grid_community183.AutoScrollService({
scrollContainer: gridBodyCtrl.eBodyViewport,
scrollAxis: "xy",
getVerticalPosition: () => gridBodyCtrl.scrollFeature.getVScrollPosition().top,
setVerticalPosition: (position) => gridBodyCtrl.scrollFeature.setVerticalScrollPosition(position),
getHorizontalPosition: () => gridBodyCtrl.scrollFeature.getHScrollPosition().left,
setHorizontalPosition: (position) => gridBodyCtrl.scrollFeature.setHorizontalScrollPosition(position),
shouldSkipVerticalScroll: () => !(0, import_ag_grid_community183._isDomLayout)(this.gos, "normal"),
shouldSkipHorizontalScroll: () => !gridBodyCtrl.scrollFeature.isHorizontalScrollShowing()
});
});
}
// Drag And Drop Target Methods
onDragStart(mouseEvent) {
if (!(0, import_ag_grid_community183._isCellSelectionEnabled)(this.gos)) {
return;
}
const { ctrlKey, metaKey, shiftKey } = mouseEvent;
const isMultiKey = ctrlKey || metaKey;
const allowMulti = !(0, import_ag_grid_community183._getSuppressMultiRanges)(this.gos);
const isMultiSelect = allowMulti ? isMultiKey : false;
const extendRange = shiftKey && !!this.cellRanges?.length;
if (!isMultiSelect && (!extendRange || (0, import_ag_grid_community183._exists)((0, import_ag_grid_community183._last)(this.cellRanges).type))) {
this.removeAllCellRanges(true);
}
const startTarget = this.dragSvc.startTarget;
if (startTarget) {
this.updateValuesOnMove(startTarget);
}
if (!this.lastCellHovered) {
return;
}
this.dragging = true;
this.lastMouseEvent = mouseEvent;
this.intersectionRange = isMultiSelect && this.getCellRangeCount(this.lastCellHovered) > 1;
if (!extendRange) {
this.setNewestRangeStartCell(this.lastCellHovered);
}
if (this.cellRanges.length > 0) {
this.draggingRange = (0, import_ag_grid_community183._last)(this.cellRanges);
} else {
const mouseRowPosition = {
rowIndex: this.lastCellHovered.rowIndex,
rowPinned: this.lastCellHovered.rowPinned
};
const columns = this.getColumnsFromModel([this.lastCellHovered.column]);
if (!columns || !columns.length) {
return;
}
this.draggingRange = {
startRow: mouseRowPosition,
endRow: mouseRowPosition,
columns,
startColumn: this.newestRangeStartCell.column
};
this.cellRanges.push(this.draggingRange);
}
this.ctrlsSvc.getGridBodyCtrl().eBodyViewport.addEventListener("scroll", this.bodyScrollListener, { passive: true });
this.dispatchChangedEvent(true, false, this.draggingRange.id);
}
onDragging(mouseEvent) {
const { dragging, lastCellHovered, newestRangeStartCell, autoScrollService, cellHasChanged } = this;
if (!dragging || !mouseEvent) {
return;
}
this.updateValuesOnMove(mouseEvent.target);
this.lastMouseEvent = mouseEvent;
const isMouseAndStartInPinned = (position) => lastCellHovered && lastCellHovered.rowPinned === position && newestRangeStartCell.rowPinned === position;
const skipVerticalScroll = isMouseAndStartInPinned("top") || isMouseAndStartInPinned("bottom");
autoScrollService.check(mouseEvent, skipVerticalScroll);
if (!cellHasChanged || !lastCellHovered) {
return;
}
const startColumn = newestRangeStartCell?.column;
const currentColumn = lastCellHovered?.column;
const columns = this.calculateColumnsBetween(startColumn, currentColumn);
if (!columns) {
return;
}
const { rowIndex, rowPinned } = lastCellHovered;
this.draggingRange.endRow = {
rowIndex,
rowPinned
};
this.draggingRange.columns = columns;
this.dispatchChangedEvent(false, false, this.draggingRange.id);
}
onDragStop() {
if (!this.dragging) {
return;
}
const { id } = this.draggingRange;
this.autoScrollService.ensureCleared();
this.ctrlsSvc.getGridBodyCtrl().eBodyViewport.removeEventListener("scroll", this.bodyScrollListener);
this.lastMouseEvent = null;
this.dragging = false;
this.draggingRange = void 0;
this.lastCellHovered = void 0;
if (this.intersectionRange) {
this.intersectionRange = false;
this.intersectLastRange();
}
this.dispatchChangedEvent(false, true, id);
}
// Called for both columns loaded & column visibility events
onColumnsChanged() {
this.refreshLastRangeStart();
const allColumns = this.visibleCols.allCols;
this.cellRanges.forEach((cellRange) => {
const beforeCols = cellRange.columns;
cellRange.columns = cellRange.columns.filter(
(col) => col.isVisible() && allColumns.indexOf(col) !== -1
);
const colsInRangeChanged = !(0, import_ag_grid_community183._areEqual)(beforeCols, cellRange.columns);
if (colsInRangeChanged) {
this.dispatchChangedEvent(false, true, cellRange.id);
}
});
const countBefore = this.cellRanges.length;
this.cellRanges = this.cellRanges.filter((range) => range.columns.length > 0);
if (countBefore > this.cellRanges.length) {
this.dispatchChangedEvent(false, true);
}
}
refreshLastRangeStart() {
const lastRange = (0, import_ag_grid_community183._last)(this.cellRanges);
if (!lastRange) {
return;
}
this.refreshRangeStart(lastRange);
}
isContiguousRange(cellRange) {
const rangeColumns = cellRange.columns;
if (!rangeColumns.length) {
return false;
}
const allColumns = this.visibleCols.allCols;
const allPositions = rangeColumns.map((c) => allColumns.indexOf(c)).sort((a, b) => a - b);
return (0, import_ag_grid_community183._last)(allPositions) - allPositions[0] + 1 === rangeColumns.length;
}
getRangeStartRow(cellRange) {
if (cellRange.startRow && cellRange.endRow) {
return (0, import_ag_grid_community183._isRowBefore)(cellRange.startRow, cellRange.endRow) ? cellRange.startRow : cellRange.endRow;
}
const pinnedTopRowCount = this.beans.pinnedRowModel?.getPinnedTopRowCount() ?? 0;
const rowPinned = pinnedTopRowCount > 0 ? "top" : null;
return { rowIndex: 0, rowPinned };
}
getRangeEndRow(cellRange) {
if (cellRange.startRow && cellRange.endRow) {
return (0, import_ag_grid_community183._isRowBefore)(cellRange.startRow, cellRange.endRow) ? cellRange.endRow : cellRange.startRow;
}
const pinnedBottomRowCount = this.beans.pinnedRowModel?.getPinnedBottomRowCount() ?? 0;
const pinnedBottom = pinnedBottomRowCount > 0;
if (pinnedBottom) {
return {
rowIndex: pinnedBottomRowCount - 1,
rowPinned: "bottom"
};
}
return {
rowIndex: this.rowModel.getRowCount() - 1,
rowPinned: null
};
}
setRangeToCell(cell, appendRange = false) {
const { gos } = this;
if (!(0, import_ag_grid_community183._isCellSelectionEnabled)(gos)) {
return;
}
const isRowNumbersEnabled = gos.get("rowNumbers");
const allColumnsRange = (0, import_ag_grid_community183.isRowNumberCol)(cell.column);
if (isRowNumbersEnabled) {
this.setSelectionMode(allColumnsRange);
}
const columns = this.calculateColumnsBetween(cell.column, cell.column);
if (!columns) {
return;
}
const suppressMultiRangeSelections = (0, import_ag_grid_community183._getSuppressMultiRanges)(this.gos);
if (suppressMultiRangeSelections || !appendRange || (0, import_ag_grid_community183._missing)(this.cellRanges)) {
this.removeAllCellRanges(true);
}
const rowForCell = {
rowIndex: cell.rowIndex,
rowPinned: cell.rowPinned
};
const cellRange = {
startRow: rowForCell,
endRow: rowForCell,
columns,
startColumn: cell.column
};
this.cellRanges.push(cellRange);
this.setNewestRangeStartCell(cell);
this.onDragStop();
this.dispatchChangedEvent(true, true);
}
extendLatestRangeToCell(cellPosition) {
if (this.isEmpty() || !this.newestRangeStartCell) {
return;
}
const cellRange = (0, import_ag_grid_community183._last)(this.cellRanges);
this.setSelectionMode((0, import_ag_grid_community183.isRowNumberCol)(cellPosition.column));
this.updateRangeEnd(cellRange, cellPosition);
}
updateRangeEnd(cellRange, cellPosition, silent = false) {
const endColumn = cellPosition.column;
const colsToAdd = this.calculateColumnsBetween(cellRange.startColumn, endColumn);
if (!colsToAdd || this.isLastCellOfRange(cellRange, cellPosition)) {
return;
}
cellRange.columns = colsToAdd;
cellRange.endRow = { rowIndex: cellPosition.rowIndex, rowPinned: cellPosition.rowPinned };
if (!silent) {
this.dispatchChangedEvent(true, true, cellRange.id);
}
}
getRangeEdgeColumns(cellRange) {
const allColumns = this.visibleCols.allCols;
const allIndices = cellRange.columns.map((c) => allColumns.indexOf(c)).filter((i) => i > -1).sort((a, b) => a - b);
return {
left: allColumns[allIndices[0]],
right: allColumns[(0, import_ag_grid_community183._last)(allIndices)]
};
}
// returns true if successful, false if not successful
extendLatestRangeInDirection(event) {
if (this.isEmpty() || !this.newestRangeStartCell) {
return;
}
const key = event.key;
const ctrlKey = event.ctrlKey || event.metaKey;
const lastRange = (0, import_ag_grid_community183._last)(this.cellRanges);
const startCell = this.newestRangeStartCell;
const firstCol = lastRange.columns[0];
const lastCol = (0, import_ag_grid_community183._last)(lastRange.columns);
const endCellIndex = lastRange.endRow.rowIndex;
const endCellFloating = lastRange.endRow.rowPinned;
const endCellColumn = startCell.column === firstCol ? lastCol : firstCol;
const endCell = { column: endCellColumn, rowIndex: endCellIndex, rowPinned: endCellFloating };
const newEndCell = this.cellNavigation.getNextCellToFocus(key, endCell, ctrlKey);
if (!newEndCell) {
return;
}
this.setCellRange({
rowStartIndex: startCell.rowIndex,
rowStartPinned: startCell.rowPinned,
rowEndIndex: newEndCell.rowIndex,
rowEndPinned: newEndCell.rowPinned,
columnStart: startCell.column,
columnEnd: newEndCell.column
});
return newEndCell;
}
setCellRange(params) {
if (!(0, import_ag_grid_community183._isCellSelectionEnabled)(this.gos)) {
return;
}
this.removeAllCellRanges(true);
this.addCellRange(params);
}
setCellRanges(cellRanges) {
if ((0, import_ag_grid_community183._areEqual)(this.cellRanges, cellRanges)) {
return;
}
if (!this.verifyCellRanges(this.gos)) {
return;
}
this.removeAllCellRanges(true);
for (const cellRange of cellRanges) {
if (cellRange.columns && cellRange.startRow) {
const columns = this.getColumnsFromModel(cellRange.columns);
if (!columns || columns.length === 0) {
continue;
}
cellRange.columns = columns;
const { startRow } = cellRange;
this.setNewestRangeStartCell({
rowIndex: startRow.rowIndex,
rowPinned: startRow.rowPinned,
column: cellRange.columns[0]
});
}
this.cellRanges.push(cellRange);
}
this.dispatchChangedEvent(false, true);
}
clearCellRangeCellValues(params) {
const { beans, valueSvc, eventSvc } = this;
const { cellEventSource = "rangeSvc", dispatchWrapperEvents, wrapperEventSource = "deleteKey" } = params;
let { cellRanges } = params;
if (dispatchWrapperEvents) {
eventSvc.dispatchEvent({
type: "cellSelectionDeleteStart",
source: wrapperEventSource
});
eventSvc.dispatchEvent({
type: "rangeDeleteStart",
source: wrapperEventSource
});
}
if (!cellRanges) {
cellRanges = this.cellRanges;
}
cellRanges.forEach((cellRange) => {
this.forEachRowInRange(cellRange, (rowPosition) => {
const rowNode = (0, import_ag_grid_community183._getRowNode)(beans, rowPosition);
if (!rowNode) {
return;
}
for (let i = 0; i < cellRange.columns.length; i++) {
const column = this.getColumnFromModel(cellRange.columns[i]);
if (!column || !column.isCellEditable(rowNode)) {
continue;
}
const emptyValue = valueSvc.getDeleteValue(column, rowNode);
rowNode.setDataValue(column, emptyValue, cellEventSource);
}
});
});
if (dispatchWrapperEvents) {
eventSvc.dispatchEvent({
type: "cellSelectionDeleteEnd",
source: wrapperEventSource
});
eventSvc.dispatchEvent({
type: "rangeDeleteEnd",
source: wrapperEventSource
});
}
}
createCellRangeFromCellRangeParams(params) {
return this.createPartialCellRangeFromRangeParams(params, false);
}
// Range service can't normally support a range without columns, but charts can
createPartialCellRangeFromRangeParams(params, allowEmptyColumns) {
const {
columns: paramColumns,
columnStart,
columnEnd,
rowStartIndex,
rowStartPinned,
rowEndIndex,
rowEndPinned
} = params;
const columnInfo = this.getColumnsFromParams(
paramColumns,
columnStart,
columnEnd
);
if (!columnInfo || !allowEmptyColumns && columnInfo.columns.length === 0) {
return;
}
const { columns, startsOnTheRight } = columnInfo;
const startRow = this.createRowPosition(rowStartIndex, rowStartPinned);
const endRow = this.createRowPosition(rowEndIndex, rowEndPinned);
return {
startRow,
endRow,
columns,
startColumn: this.getColumnFromModel(columnStart) ?? (startsOnTheRight ? (0, import_ag_grid_community183._last)(columns) : columns[0])
};
}
addCellRange(params) {
const gos = this.gos;
if (!(0, import_ag_grid_community183._isCellSelectionEnabled)(gos) || !this.verifyCellRanges(gos)) {
return;
}
this.setSelectionMode(false);
const newRange = this.createCellRangeFromCellRangeParams(params);
if (newRange) {
if (newRange.startRow) {
this.setNewestRangeStartCell({
rowIndex: newRange.startRow.rowIndex,
rowPinned: newRange.startRow.rowPinned,
column: newRange.startColumn
});
}
this.cellRanges.push(newRange);
this.dispatchChangedEvent(false, true, newRange.id);
}
}
getCellRanges() {
return this.cellRanges;
}
isEmpty() {
return this.cellRanges.length === 0;
}
isMoreThanOneCell() {
const len = this.cellRanges.length;
if (len === 0) {
return false;
}
if (len > 1) {
return true;
}
const range = this.cellRanges[0];
const startRow = this.getRangeStartRow(range);
const endRow = this.getRangeEndRow(range);
return startRow.rowPinned !== endRow.rowPinned || startRow.rowIndex !== endRow.rowIndex || range.columns.length !== 1;
}
areAllRangesAbleToMerge() {
const rowToColumnMap = /* @__PURE__ */ new Map();
const len = this.cellRanges.length;
if (len <= 1)
return true;
this.cellRanges.forEach((range) => {
this.forEachRowInRange(range, (row) => {
const rowName = `${row.rowPinned || "normal"}_${row.rowIndex}`;
const columns = rowToColumnMap.get(rowName);
const currentRangeColIds = range.columns.map((col) => col.getId());
if (columns) {
const filteredColumns = currentRangeColIds.filter((col) => columns.indexOf(col) === -1);
columns.push(...filteredColumns);
} else {
rowToColumnMap.set(rowName, currentRangeColIds);
}
});
});
let columnsString;
for (const val of rowToColumnMap.values()) {
const currentValString = val.sort().join();
if (columnsString === void 0) {
columnsString = currentValString;
continue;
}
if (columnsString !== currentValString) {
return false;
}
}
return true;
}
removeAllCellRanges(silent) {
if (this.isEmpty()) {
return;
}
this.onDragStop();
this.cellRanges.length = 0;
if (!silent) {
this.dispatchChangedEvent(false, true);
}
}
isCellInAnyRange(cell) {
return this.getCellRangeCount(cell) > 0;
}
isCellInSpecificRange(cell, range) {
const columnInRange = range.columns !== null && range.columns.includes(cell.column);
const rowInRange = this.isRowInRange(cell.rowIndex, cell.rowPinned, range);
return columnInRange && rowInRange;
}
isBottomRightCell(cellRange, cell) {
const allColumns = this.visibleCols.allCols;
const allPositions = cellRange.columns.map((c) => allColumns.indexOf(c)).sort((a, b) => a - b);
const { startRow, endRow } = cellRange;
const lastRow = (0, import_ag_grid_community183._isRowBefore)(startRow, endRow) ? endRow : startRow;
const isRightColumn = allColumns.indexOf(cell.column) === (0, import_ag_grid_community183._last)(allPositions);
const isLastRow = cell.rowIndex === lastRow.rowIndex && (0, import_ag_grid_community183._makeNull)(cell.rowPinned) === (0, import_ag_grid_community183._makeNull)(lastRow.rowPinned);
return isRightColumn && isLastRow;
}
// returns the number of ranges this cell is in
getCellRangeCount(cell) {
if (this.isEmpty()) {
return 0;
}
return this.cellRanges.filter((cellRange) => this.isCellInSpecificRange(cell, cellRange)).length;
}
isRowInRange(rowIndex, rowPinned, cellRange) {
const firstRow = this.getRangeStartRow(cellRange);
const lastRow = this.getRangeEndRow(cellRange);
const thisRow = { rowIndex, rowPinned: rowPinned || null };
const equalsFirstRow = thisRow.rowIndex === firstRow.rowIndex && thisRow.rowPinned == firstRow.rowPinned;
const equalsLastRow = thisRow.rowIndex === lastRow.rowIndex && thisRow.rowPinned == lastRow.rowPinned;
if (equalsFirstRow || equalsLastRow) {
return true;
}
const afterFirstRow = !(0, import_ag_grid_community183._isRowBefore)(thisRow, firstRow);
const beforeLastRow = (0, import_ag_grid_community183._isRowBefore)(thisRow, lastRow);
return afterFirstRow && beforeLastRow;
}
intersectLastRange(fromMouseClick) {
if (fromMouseClick && this.dragging) {
return;
}
if ((0, import_ag_grid_community183._getSuppressMultiRanges)(this.gos)) {
return;
}
if (this.isEmpty()) {
return;
}
const lastRange = (0, import_ag_grid_community183._last)(this.cellRanges);
const intersectionStartRow = this.getRangeStartRow(lastRange);
const intersectionEndRow = this.getRangeEndRow(lastRange);
const newRanges = [];
this.cellRanges.slice(0, -1).forEach((range) => {
const startRow = this.getRangeStartRow(range);
const endRow = this.getRangeEndRow(range);
const cols = range.columns;
const intersectCols = cols.filter((col) => lastRange.columns.indexOf(col) === -1);
if (intersectCols.length === cols.length) {
newRanges.push(range);
return;
}
if ((0, import_ag_grid_community183._isRowBefore)(intersectionEndRow, startRow) || (0, import_ag_grid_community183._isRowBefore)(endRow, intersectionStartRow)) {
newRanges.push(range);
return;
}
const rangeCountBefore = newRanges.length;
if ((0, import_ag_grid_community183._isRowBefore)(startRow, intersectionStartRow)) {
const top = {
columns: [...cols],
startColumn: lastRange.startColumn,
startRow: { ...startRow },
endRow: (0, import_ag_grid_community183._getRowAbove)(this.beans, intersectionStartRow)
};
newRanges.push(top);
}
if (intersectCols.length > 0) {
const middle = {
columns: intersectCols,
startColumn: intersectCols.includes(lastRange.startColumn) ? lastRange.startColumn : intersectCols[0],
startRow: this.rowMax([{ ...intersectionStartRow }, { ...startRow }]),
endRow: this.rowMin([{ ...intersectionEndRow }, { ...endRow }])
};
newRanges.push(middle);
}
if ((0, import_ag_grid_community183._isRowBefore)(intersectionEndRow, endRow)) {
newRanges.push({
columns: [...cols],
startColumn: lastRange.startColumn,
startRow: (0, import_ag_grid_community183._getRowBelow)(this.beans, intersectionEndRow),
endRow: { ...endRow }
});
}
if (newRanges.length - rangeCountBefore === 1) {
newRanges[newRanges.length - 1].id = range.id;
}
});
this.cellRanges = newRanges;
if (fromMouseClick) {
this.dispatchChangedEvent(false, true);
}
}
createRangeHighlightFeature(compBean, column, headerComp) {
compBean.createManagedBean(new RangeHeaderHighlightFeature(column, headerComp));
}
setSelectionMode(allColumns) {
this.selectionMode = allColumns ? 1 /* ALL_COLUMNS */ : 0 /* NORMAL */;
}
refreshRangeStart(cellRange) {
const { startColumn, columns } = cellRange;
const moveColInCellRange = (colToMove, moveToFront) => {
const otherCols = cellRange.columns.filter((col) => col !== colToMove);
if (colToMove) {
cellRange.startColumn = colToMove;
cellRange.columns = moveToFront ? [colToMove, ...otherCols] : [...otherCols, colToMove];
} else {
cellRange.columns = otherCols;
}
};
const { left, right } = this.getRangeEdgeColumns(cellRange);
const shouldMoveLeftCol = startColumn === columns[0] && startColumn !== left;
if (shouldMoveLeftCol) {
moveColInCellRange(left, true);
return;
}
const shouldMoveRightCol = startColumn === (0, import_ag_grid_community183._last)(columns) && startColumn === right;
if (shouldMoveRightCol) {
moveColInCellRange(right, false);
return;
}
}
setNewestRangeStartCell(position) {
this.newestRangeStartCell = position;
}
getColumnsFromParams(columns, columnA, columnB) {
const noColsInfo = !columns && !columnA && !columnB;
let processedColumns;
let startsOnTheRight = false;
if (noColsInfo || columns) {
processedColumns = this.getColumnsFromModel(noColsInfo ? void 0 : columns);
} else if (columnA && columnB) {
processedColumns = this.calculateColumnsBetween(columnA, columnB);
if (processedColumns && processedColumns.length) {
startsOnTheRight = processedColumns[0] !== this.getColumnFromModel(columnA);
}
}
return processedColumns ? {
columns: processedColumns,
startsOnTheRight
} : void 0;
}
createRowPosition(rowIndex, rowPinned) {
return rowIndex != null ? { rowIndex, rowPinned } : void 0;
}
verifyCellRanges(gos) {
const invalid = (0, import_ag_grid_community183._isUsingNewCellSelectionAPI)(gos) && (0, import_ag_grid_community183._getSuppressMultiRanges)(gos) && this.cellRanges.length > 1;
if (invalid) {
(0, import_ag_grid_community183._warn)(93);
}
return !invalid;
}
forEachRowInRange(cellRange, callback) {
const topRow = this.getRangeStartRow(cellRange);
const bottomRow = this.getRangeEndRow(cellRange);
let currentRow = topRow;
while (currentRow) {
callback(currentRow);
if ((0, import_ag_grid_community183._isSameRow)(currentRow, bottomRow)) {
break;
}
currentRow = (0, import_ag_grid_community183._getRowBelow)(this.beans, currentRow);
}
}
// as the user is dragging outside of the panel, the div starts to scroll, which in turn
// means we are selection more (or less) cells, but the mouse isn't moving, so we recalculate
// the selection my mimicking a new mouse event
onBodyScroll() {
if (this.dragging && this.lastMouseEvent) {
this.onDragging(this.lastMouseEvent);
}
}
isLastCellOfRange(cellRange, cell) {
const { startRow, endRow } = cellRange;
const lastRow = (0, import_ag_grid_community183._isRowBefore)(startRow, endRow) ? endRow : startRow;
const isLastRow = cell.rowIndex === lastRow.rowIndex && cell.rowPinned === lastRow.rowPinned;
const rangeFirstIndexColumn = cellRange.columns[0];
const rangeLastIndexColumn = (0, import_ag_grid_community183._last)(cellRange.columns);
const lastRangeColumn = cellRange.startColumn === rangeFirstIndexColumn ? rangeLastIndexColumn : rangeFirstIndexColumn;
const isLastColumn = cell.column === lastRangeColumn;
return isLastColumn && isLastRow;
}
rowMax(rows) {
let max;
rows.forEach((row) => {
if (max === void 0 || (0, import_ag_grid_community183._isRowBefore)(max, row)) {
max = row;
}
});
return max;
}
rowMin(rows) {
let min;
rows.forEach((row) => {
if (min === void 0 || (0, import_ag_grid_community183._isRowBefore)(row, min)) {
min = row;
}
});
return min;
}
updateValuesOnMove(eventTarget) {
const cellCtrl = (0, import_ag_grid_community183._getCellCtrlForEventTarget)(this.gos, eventTarget);
const cell = cellCtrl?.cellPosition;
this.cellHasChanged = false;
if (!cell || this.lastCellHovered && (0, import_ag_grid_community183._areCellsEqual)(cell, this.lastCellHovered)) {
return;
}
const editing = this.beans.editSvc?.isEditing(cellCtrl, {
withOpenEditor: true
});
if (editing) {
this.dragSvc.cancelDrag(eventTarget);
return;
}
if (this.lastCellHovered) {
this.cellHasChanged = true;
}
this.lastCellHovered = cell;
}
shouldSkipCurrentColumn(currentColumn) {
return (0, import_ag_grid_community183.isRowNumberCol)(currentColumn);
}
dispatchChangedEvent(started, finished, id) {
this.eventSvc.dispatchEvent({
type: "cellSelectionChanged",
started,
finished,
id
});
this.eventSvc.dispatchEvent({
type: "rangeSelectionChanged",
started,
finished,
id
});
}
getColumnFromModel(col) {
return typeof col === "string" ? this.colModel.getCol(col) : col;
}
getColumnsFromModel(cols) {
const { gos, visibleCols } = this;
const isRowHeaderActive = gos.get("rowNumbers");
if (!cols || this.selectionMode === 1 /* ALL_COLUMNS */) {
cols = visibleCols.allCols;
}
const columns = [];
for (const col of cols) {
const column = this.getColumnFromModel(col);
if (!column || isRowHeaderActive && this.shouldSkipCurrentColumn(column)) {
continue;
}
columns.push(column);
}
return columns.length ? columns : void 0;
}
calculateColumnsBetween(columnA, columnB) {
const allColumns = this.visibleCols.allCols;
const fromColumn = this.getColumnFromModel(columnA);
const toColumn = this.getColumnFromModel(columnB);
const isSameColumn = fromColumn === toColumn;
const fromIndex = allColumns.indexOf(fromColumn);
if (fromIndex < 0) {
(0, import_ag_grid_community183._warn)(178, { colId: fromColumn.getId() });
return;
}
const toIndex = isSameColumn ? fromIndex : allColumns.indexOf(toColumn);
if (toIndex < 0) {
(0, import_ag_grid_community183._warn)(178, { colId: toColumn.getId() });
return;
}
if (isSameColumn || this.selectionMode === 1 /* ALL_COLUMNS */) {
return this.getColumnsFromModel([fromColumn]);
}
const firstIndex = Math.min(fromIndex, toIndex);
const lastIndex = firstIndex === fromIndex ? toIndex : fromIndex;
const columns = [];
for (let i = firstIndex; i <= lastIndex; i++) {
columns.push(allColumns[i]);
}
return this.getColumnsFromModel(columns);
}
createDragListenerFeature(eContainer) {
return new DragListenerFeature(eContainer);
}
createCellRangeFeature(beans, ctrl) {
return new CellRangeFeature(beans, ctrl);
}
};
// packages/ag-grid-enterprise/src/rangeSelection/rangeSelectionModule.ts
var CellSelectionModule = {
moduleName: "CellSelection",
version: VERSION,
beans: [RangeService],
dynamicBeans: { fillHandle: AgFillHandle, rangeHandle: AgRangeHandle },
apiFunctions: {
getCellRanges,
addCellRange,
clearRangeSelection,
clearCellSelection: clearRangeSelection
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community184._KeyboardNavigationModule, import_ag_grid_community184._DragModule],
css: [rangeSelectionCSS]
};
var RangeSelectionModule = {
moduleName: "RangeSelection",
version: VERSION,
dependsOn: [CellSelectionModule]
};
// packages/ag-grid-enterprise/src/serverSideRowModel/serverSideRowModelModule.ts
var import_ag_grid_community212 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/cellRenderers/loadingCellRenderer.ts
var import_ag_grid_community185 = require("ag-grid-community");
var LoadingCellRendererElement = {
tag: "div",
cls: "ag-loading",
children: [
{ tag: "span", ref: "eLoadingIcon", cls: "ag-loading-icon" },
{ tag: "span", ref: "eLoadingText", cls: "ag-loading-text" }
]
};
var LoadingCellRenderer = class extends import_ag_grid_community185.Component {
constructor() {
super(LoadingCellRendererElement);
this.eLoadingIcon = import_ag_grid_community185.RefPlaceholder;
this.eLoadingText = import_ag_grid_community185.RefPlaceholder;
}
init(params) {
params.node.failedLoad ? this.setupFailed() : this.setupLoading();
}
setupFailed() {
this.eLoadingText.textContent = this.getLocaleTextFunc()("loadingError", "ERR");
}
setupLoading() {
const eLoadingIcon = (0, import_ag_grid_community185._createIconNoSpan)("groupLoading", this.beans, null);
if (eLoadingIcon) {
this.eLoadingIcon.appendChild(eLoadingIcon);
}
this.eLoadingText.textContent = this.getLocaleTextFunc()("loadingOoo", "Loading");
}
refresh(_params) {
return false;
}
};
// packages/ag-grid-enterprise/src/cellRenderers/enterpriseCellRendererModule.ts
var LoadingCellRendererModule = {
moduleName: "LoadingCellRenderer",
version: VERSION,
userComponents: {
agLoadingCellRenderer: LoadingCellRenderer
},
icons: {
// rotating spinner shown by the loading cell renderer
groupLoading: "loading"
},
dependsOn: [EnterpriseCoreModule]
};
// packages/ag-grid-enterprise/src/pivot/pivotModule.ts
var import_ag_grid_community189 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/pivot/pivotApi.ts
function isPivotMode(beans) {
return beans.colModel.isPivotMode();
}
function getPivotResultColumn(beans, pivotKeys, valueColKey) {
return beans.pivotResultCols?.lookupPivotResultCol(pivotKeys, valueColKey) ?? null;
}
function setValueColumns(beans, colKeys) {
beans.valueColsSvc?.setColumns(colKeys, "api");
}
function getValueColumns(beans) {
return beans.valueColsSvc?.columns ?? [];
}
function removeValueColumns(beans, colKeys) {
beans.valueColsSvc?.removeColumns(colKeys, "api");
}
function addValueColumns(beans, colKeys) {
beans.valueColsSvc?.addColumns(colKeys, "api");
}
function setPivotColumns(beans, colKeys) {
beans.pivotColsSvc?.setColumns(colKeys, "api");
}
function removePivotColumns(beans, colKeys) {
beans.pivotColsSvc?.removeColumns(colKeys, "api");
}
function addPivotColumns(beans, colKeys) {
beans.pivotColsSvc?.addColumns(colKeys, "api");
}
function getPivotColumns(beans) {
return beans.pivotColsSvc?.columns ?? [];
}
function setPivotResultColumns(beans, colDefs) {
beans.pivotResultCols?.setPivotResultCols(colDefs, "api");
}
function getPivotResultColumns(beans) {
const pivotResultCols = beans.pivotResultCols?.getPivotResultCols();
return pivotResultCols ? pivotResultCols.list : null;
}
// packages/ag-grid-enterprise/src/pivot/pivotColDefService.ts
var import_ag_grid_community186 = require("ag-grid-community");
var PIVOT_ROW_TOTAL_PREFIX = "PivotRowTotal_";
var headerNameComparator = ({ headerName: a }, { headerName: b }) => {
if (a && !b) {
return 1;
} else if (!a && b) {
return -1;
} else if (!a && !b) {
return 0;
}
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
};
var convertToHeaderNameComparator = (comparator) => (a, b) => comparator(a.headerName, b.headerName);
var PivotColDefService = class extends import_ag_grid_community186.BeanStub {
constructor() {
super(...arguments);
this.beanName = "pivotColDefSvc";
}
wireBeans(beans) {
this.colModel = beans.colModel;
this.pivotColsSvc = beans.pivotColsSvc;
this.valueColsSvc = beans.valueColsSvc;
this.colNames = beans.colNames;
}
postConstruct() {
const getFieldSeparator = () => this.gos.get("serverSidePivotResultFieldSeparator") ?? "_";
this.fieldSeparator = getFieldSeparator();
this.addManagedPropertyListener("serverSidePivotResultFieldSeparator", () => {
this.fieldSeparator = getFieldSeparator();
});
const getPivotDefaultExpanded = () => this.gos.get("pivotDefaultExpanded");
this.pivotDefaultExpanded = getPivotDefaultExpanded();
this.addManagedPropertyListener("pivotDefaultExpanded", () => {
this.pivotDefaultExpanded = getPivotDefaultExpanded();
});
}
createPivotColumnDefs(uniqueValues) {
const pivotColumnGroupDefs = this.createPivotColumnsFromUniqueValues(uniqueValues);
function extractColDefs(input, arr = []) {
input.forEach((def) => {
if (def.children !== void 0) {
extractColDefs(def.children, arr);
} else {
arr.push(def);
}
});
return arr;
}
const pivotColumnDefs = extractColDefs(pivotColumnGroupDefs);
this.addRowGroupTotals(pivotColumnGroupDefs, pivotColumnDefs);
this.addExpandablePivotGroups(pivotColumnGroupDefs, pivotColumnDefs);
this.addPivotTotalsToGroups(pivotColumnGroupDefs, pivotColumnDefs);
return pivotColumnGroupDefs;
}
createPivotColumnsFromUniqueValues(uniqueValues) {
const pivotColumns = this.pivotColsSvc?.columns ?? [];
const maxDepth = pivotColumns.length;
const pivotColumnGroupDefs = this.recursivelyBuildGroup(
0,
uniqueValues,
[],
maxDepth,
pivotColumns
);
return pivotColumnGroupDefs;
}
recursivelyBuildGroup(index, uniqueValue, pivotKeys, maxDepth, primaryPivotColumns) {
if (index >= maxDepth) {
return this.buildMeasureCols(pivotKeys);
}
const { pivotComparator } = primaryPivotColumns[index].getColDef();
const comparator = pivotComparator ? convertToHeaderNameComparator(pivotComparator) : headerNameComparator;
const measureColumns = this.valueColsSvc?.columns;
if (measureColumns?.length === 1 && this.gos.get("removePivotHeaderRowWhenSingleValueColumn") && index === maxDepth - 1) {
const leafCols = [];
for (const key of uniqueValue.keys()) {
const newPivotKeys = [...pivotKeys, key];
const colDef = this.createColDef(measureColumns[0], key, newPivotKeys);
colDef.columnGroupShow = "open";
leafCols.push(colDef);
}
leafCols.sort(comparator);
return leafCols;
}
const groups = [];
for (const key of uniqueValue.keys()) {
const openByDefault = this.pivotDefaultExpanded === -1 || index < this.pivotDefaultExpanded;
const newPivotKeys = [...pivotKeys, key];
groups.push({
children: this.recursivelyBuildGroup(
index + 1,
uniqueValue.get(key),
newPivotKeys,
maxDepth,
primaryPivotColumns
),
headerName: key,
pivotKeys: newPivotKeys,
columnGroupShow: "open",
openByDefault,
groupId: this.generateColumnGroupId(newPivotKeys)
});
}
groups.sort(comparator);
return groups;
}
buildMeasureCols(pivotKeys) {
const measureColumns = this.valueColsSvc?.columns ?? [];
if (measureColumns.length === 0) {
return [this.createColDef(null, "-", pivotKeys)];
}
return measureColumns.map((measureCol) => {
const columnName = this.colNames.getDisplayNameForColumn(measureCol, "header");
const colDef = this.createColDef(measureCol, columnName, pivotKeys);
colDef.columnGroupShow = "open";
return colDef;
});
}
addExpandablePivotGroups(pivotColumnGroupDefs, pivotColumnDefs) {
const isSuppressExpand = this.gos.get("suppressExpandablePivotGroups");
if (isSuppressExpand || this.gos.get("pivotColumnGroupTotals")) {
return;
}
const recursivelyAddSubTotals = (def, currentPivotColumnDefs, acc) => {
if ("children" in def) {
const { valueColsSvc } = this;
const { columns: valueCols = [] } = valueColsSvc ?? {};
const childAcc = /* @__PURE__ */ new Map();
def.children.forEach((grp) => {
recursivelyAddSubTotals(grp, currentPivotColumnDefs, childAcc);
});
const leafGroup = !def.children.some((child) => child.children);
const hasCollapsedLeafGroup = leafGroup && valueCols.length === 1 && this.gos.get("removePivotHeaderRowWhenSingleValueColumn");
valueCols.forEach((valueColumn) => {
const columnName = this.colNames.getDisplayNameForColumn(valueColumn, "header");
const totalColDef = this.createColDef(valueColumn, columnName, def.pivotKeys);
totalColDef.pivotTotalColumnIds = childAcc.get(valueColumn.getColId());
totalColDef.columnGroupShow = !isSuppressExpand ? "closed" : "open";
totalColDef.aggFunc = valueColumn.getAggFunc();
if (!leafGroup || hasCollapsedLeafGroup) {
const children = def.children;
children.push(totalColDef);
currentPivotColumnDefs.push(totalColDef);
}
});
this.merge(acc, childAcc);
return;
}
if (!def.pivotValueColumn) {
return;
}
const pivotValueColId = def.pivotValueColumn.getColId();
const exists = acc.has(pivotValueColId);
if (exists) {
const arr = acc.get(pivotValueColId);
arr.push(def.colId);
} else {
acc.set(pivotValueColId, [def.colId]);
}
};
pivotColumnGroupDefs.forEach((groupDef) => {
recursivelyAddSubTotals(groupDef, pivotColumnDefs, /* @__PURE__ */ new Map());
});
}
addPivotTotalsToGroups(pivotColumnGroupDefs, pivotColumnDefs) {
if (!this.gos.get("pivotColumnGroupTotals")) {
return;
}
const insertAfter = this.gos.get("pivotColumnGroupTotals") === "after";
const valueCols = this.valueColsSvc?.columns;
const aggFuncs = valueCols?.map((valueCol) => valueCol.getAggFunc());
if (!aggFuncs || aggFuncs.length < 1 || !this.sameAggFuncs(aggFuncs)) {
return;
}
if (valueCols) {
const valueColumn = valueCols[0];
pivotColumnGroupDefs.forEach((groupDef) => {
this.recursivelyAddPivotTotal(groupDef, pivotColumnDefs, valueColumn, insertAfter);
});
}
}
recursivelyAddPivotTotal(groupDef, pivotColumnDefs, valueColumn, insertAfter) {
const group = groupDef;
if (!group.children) {
const def = groupDef;
return def.colId ? [def.colId] : null;
}
let colIds = [];
group.children.forEach((grp) => {
const childColIds = this.recursivelyAddPivotTotal(grp, pivotColumnDefs, valueColumn, insertAfter);
if (childColIds) {
colIds = colIds.concat(childColIds);
}
});
if (group.children.length > 1) {
const localeTextFunc = this.getLocaleTextFunc();
const headerName = localeTextFunc("pivotColumnGroupTotals", "Total");
const totalColDef = this.createColDef(valueColumn, headerName, groupDef.pivotKeys, true);
totalColDef.pivotTotalColumnIds = colIds;
totalColDef.aggFunc = valueColumn.getAggFunc();
totalColDef.columnGroupShow = this.gos.get("suppressExpandablePivotGroups") ? "open" : void 0;
const children = groupDef.children;
insertAfter ? children.push(totalColDef) : children.unshift(totalColDef);
pivotColumnDefs.push(totalColDef);
}
return colIds;
}
addRowGroupTotals(pivotColumnGroupDefs, pivotColumnDefs) {
if (!this.gos.get("pivotRowTotals")) {
return;
}
const insertAtEnd = this.gos.get("pivotRowTotals") === "after";
const valueColumns = this.valueColsSvc?.columns ?? [];
const valueCols = valueColumns.slice();
if (!insertAtEnd) {
valueCols.reverse();
}
const isCreateTotalGroups = valueCols.length > 1 || !this.gos.get("removePivotHeaderRowWhenSingleValueColumn");
for (let i = 0; i < valueCols.length; i++) {
const valueCol = valueCols[i];
const columnName = this.colNames.getDisplayNameForColumn(valueCol, "header");
const colDef = this.createColDef(valueCol, columnName, []);
const colIds = [];
for (let i2 = 0; i2 < pivotColumnDefs.length; i2++) {
const colDef2 = pivotColumnDefs[i2];
if (colDef2.pivotValueColumn === valueCol) {
colIds.push(colDef2.colId);
}
}
colDef.pivotTotalColumnIds = colIds;
colDef.colId = PIVOT_ROW_TOTAL_PREFIX + colDef.colId;
const valueGroup = isCreateTotalGroups ? {
children: [colDef],
pivotKeys: [],
groupId: `${PIVOT_ROW_TOTAL_PREFIX}_pivotGroup_${valueCol.getColId()}`
} : colDef;
pivotColumnDefs.push(colDef);
insertAtEnd ? pivotColumnGroupDefs.push(valueGroup) : pivotColumnGroupDefs.unshift(valueGroup);
}
}
/**
* Recreate a pivot colDef to update from a changed valueColumn colDef
*/
recreateColDef(colDef) {
const {
pivotValueColumn,
headerName,
pivotKeys,
pivotTotalColumnIds,
columnGroupShow,
colId,
valueGetter,
aggFunc
} = colDef;
if (!pivotValueColumn) {
return colDef;
}
const newColDef = this.createColDef(pivotValueColumn, headerName, pivotKeys, !!pivotTotalColumnIds);
newColDef.columnGroupShow = columnGroupShow;
newColDef.colId = colId;
newColDef.valueGetter = valueGetter;
newColDef.aggFunc = aggFunc;
newColDef.pivotTotalColumnIds = pivotTotalColumnIds;
this.gos.get("processPivotResultColDef")?.(newColDef);
return newColDef;
}
createColDef(valueColumn, headerName, pivotKeys, totalColumn = false) {
const colDef = {};
if (valueColumn) {
const colDefToCopy = valueColumn.getColDef();
Object.assign(colDef, colDefToCopy);
colDef.hide = false;
}
colDef.headerName = headerName;
colDef.colId = this.generateColumnId(
pivotKeys || [],
valueColumn && !totalColumn ? valueColumn.getColId() : ""
);
colDef.field = colDef.colId;
colDef.valueGetter = (params) => params.data?.[params.colDef.field];
colDef.pivotKeys = pivotKeys;
colDef.pivotValueColumn = valueColumn;
if (colDef.filter === true) {
colDef.filter = "agNumberColumnFilter";
}
return colDef;
}
sameAggFuncs(aggFuncs) {
if (aggFuncs.length == 1) {
return true;
}
for (let i = 1; i < aggFuncs.length; i++) {
if (aggFuncs[i] !== aggFuncs[0]) {
return false;
}
}
return true;
}
merge(m1, m2) {
m2.forEach((value, key) => {
const existingList = m1.has(key) ? m1.get(key) : [];
const updatedList = [...existingList, ...value];
m1.set(key, updatedList);
});
}
generateColumnGroupId(pivotKeys) {
const pivotCols = (this.pivotColsSvc?.columns ?? []).map((col) => col.getColId());
return `pivotGroup_${pivotCols.join("-")}_${pivotKeys.join("-")}`;
}
generateColumnId(pivotKeys, measureColumnId) {
const pivotCols = (this.pivotColsSvc?.columns ?? []).map((col) => col.getColId());
return `pivot_${pivotCols.join("-")}_${pivotKeys.join("-")}_${measureColumnId}`;
}
/**
* Used by the SSRM to create secondary columns from provided fields
* @param fields
*/
createColDefsFromFields(fields) {
const uniqueValues = /* @__PURE__ */ new Map();
for (let i = 0; i < fields.length; i++) {
const field = fields[i];
const parts = field.split(this.fieldSeparator);
let level = uniqueValues;
for (let p = 0; p < parts.length; p++) {
const part = parts[p];
let map = level.get(part);
if (!map) {
map = /* @__PURE__ */ new Map();
level.set(part, map);
}
level = map;
}
}
const uniqueValuesToGroups = (id, key, uniqueValues2, depth) => {
const children = [];
for (const [key2, item] of uniqueValues2) {
const child = uniqueValuesToGroups(`${id}${this.fieldSeparator}${key2}`, key2, item, depth + 1);
children.push(child);
}
if (children.length === 0) {
const potentialAggCol = this.colModel.getColDefCol(key);
if (potentialAggCol) {
const headerName = this.colNames.getDisplayNameForColumn(potentialAggCol, "header") ?? key;
const colDef = this.createColDef(potentialAggCol, headerName, void 0, false);
colDef.colId = id;
colDef.aggFunc = potentialAggCol.getAggFunc();
colDef.valueGetter = (params) => params.data?.[id];
return colDef;
}
const col = {
colId: id,
headerName: key,
// this is to support using pinned rows, normally the data will be extracted from the aggData object using the colId
// however pinned rows still access the data object by field, this prevents values with dots from being treated as complex objects
valueGetter: (params) => params.data?.[id]
};
return col;
}
const collapseSingleChildren = this.gos.get("removePivotHeaderRowWhenSingleValueColumn");
if (collapseSingleChildren && children.length === 1 && "colId" in children[0]) {
children[0].headerName = key;
return children[0];
}
const group = {
openByDefault: this.pivotDefaultExpanded === -1 || depth < this.pivotDefaultExpanded,
groupId: id,
headerName: key,
children
};
return group;
};
const res = [];
for (const [key, item] of uniqueValues) {
const col = uniqueValuesToGroups(key, key, item, 0);
res.push(col);
}
return res;
}
};
// packages/ag-grid-enterprise/src/pivot/pivotResultColsService.ts
var import_ag_grid_community187 = require("ag-grid-community");
var PivotResultColsService = class extends import_ag_grid_community187.BeanStub {
constructor() {
super(...arguments);
this.beanName = "pivotResultCols";
}
wireBeans(beans) {
this.colModel = beans.colModel;
this.visibleCols = beans.visibleCols;
}
destroy() {
(0, import_ag_grid_community187._destroyColumnTree)(this.beans, this.pivotResultCols?.tree);
super.destroy();
}
isPivotResultColsPresent() {
return this.pivotResultCols != null;
}
lookupPivotResultCol(pivotKeys, valueColKey) {
if (this.pivotResultCols == null) {
return null;
}
const valueColumnToFind = this.colModel.getColDefCol(valueColKey);
let foundColumn = null;
this.pivotResultCols.list.forEach((column) => {
const thisPivotKeys = column.getColDef().pivotKeys;
const pivotValueColumn = column.getColDef().pivotValueColumn;
const pivotKeyMatches = (0, import_ag_grid_community187._areEqual)(thisPivotKeys, pivotKeys);
const pivotValueMatches = pivotValueColumn === valueColumnToFind;
if (pivotKeyMatches && pivotValueMatches) {
foundColumn = column;
}
});
return foundColumn;
}
getPivotResultCols() {
return this.pivotResultCols;
}
getPivotResultCol(key) {
if (!this.pivotResultCols) {
return null;
}
return this.colModel.getColFromCollection(key, this.pivotResultCols);
}
setPivotResultCols(colDefs, source) {
if (!this.colModel.ready) {
return;
}
if (colDefs == null && this.pivotResultCols == null) {
return;
}
if (colDefs) {
this.processPivotResultColDef(colDefs);
const createColTreeFunc = source === "api" ? import_ag_grid_community187._createColumnTree : import_ag_grid_community187._createColumnTreeWithIds;
const balancedTreeResult = createColTreeFunc(
this.beans,
colDefs,
false,
this.pivotResultCols?.tree || this.previousPivotResultCols || void 0,
source
);
(0, import_ag_grid_community187._destroyColumnTree)(this.beans, this.pivotResultCols?.tree, balancedTreeResult.columnTree);
const tree = balancedTreeResult.columnTree;
const treeDepth = balancedTreeResult.treeDepth;
const list = (0, import_ag_grid_community187._getColumnsFromTree)(tree);
const map = {};
this.pivotResultCols = { tree, treeDepth, list, map };
this.pivotResultCols.list.forEach((col) => this.pivotResultCols.map[col.getId()] = col);
const hasPreviousCols = !!this.previousPivotResultCols;
this.previousPivotResultCols = null;
this.colModel.refreshCols(!hasPreviousCols);
} else {
this.previousPivotResultCols = this.pivotResultCols ? this.pivotResultCols.tree : null;
this.pivotResultCols = null;
this.colModel.refreshCols(false);
}
this.visibleCols.refresh(source);
}
processPivotResultColDef(colDefs) {
const columnCallback = this.gos.get("processPivotResultColDef");
const groupCallback = this.gos.get("processPivotResultColGroupDef");
if (!columnCallback && !groupCallback) {
return void 0;
}
const searchForColDefs = (colDefs2) => {
colDefs2.forEach((abstractColDef) => {
const isGroup = (0, import_ag_grid_community187._exists)(abstractColDef.children);
if (isGroup) {
const colGroupDef = abstractColDef;
if (groupCallback) {
groupCallback(colGroupDef);
}
searchForColDefs(colGroupDef.children);
} else {
const colDef = abstractColDef;
if (columnCallback) {
columnCallback(colDef);
}
}
});
};
if (colDefs) {
searchForColDefs(colDefs);
}
}
};
// packages/ag-grid-enterprise/src/pivot/pivotStage.ts
var import_ag_grid_community188 = require("ag-grid-community");
var EXCEEDED_MAX_UNIQUE_VALUES = "Exceeded maximum allowed pivot column count.";
var mapToObject = (map) => {
const obj = {};
map.forEach((value, key) => obj[key] = value instanceof Map ? mapToObject(value) : value);
return obj;
};
var PivotStage = class extends import_ag_grid_community188.BeanStub {
constructor() {
super(...arguments);
this.beanName = "pivotStage";
this.refreshProps = /* @__PURE__ */ new Set([
"removePivotHeaderRowWhenSingleValueColumn",
"pivotRowTotals",
"pivotColumnGroupTotals",
"suppressExpandablePivotGroups"
]);
this.step = "pivot";
this.uniqueValues = /* @__PURE__ */ new Map();
this.lastTimeFailed = false;
this.maxUniqueValues = -1;
this.currentUniqueCount = 0;
}
wireBeans(beans) {
this.valueSvc = beans.valueSvc;
this.colModel = beans.colModel;
this.pivotResultCols = beans.pivotResultCols;
this.rowGroupColsSvc = beans.rowGroupColsSvc;
this.valueColsSvc = beans.valueColsSvc;
this.pivotColsSvc = beans.pivotColsSvc;
this.pivotColDefSvc = beans.pivotColDefSvc;
}
execute(params) {
const changedPath = params.changedPath;
if (this.colModel.isPivotActive()) {
this.executePivotOn(changedPath);
} else {
this.executePivotOff(changedPath);
}
}
executePivotOff(changedPath) {
this.aggregationColumnsHashLastTime = null;
this.uniqueValues = /* @__PURE__ */ new Map();
if (this.pivotResultCols.isPivotResultColsPresent()) {
this.pivotResultCols.setPivotResultCols(null, "rowModelUpdated");
if (changedPath) {
changedPath.active = false;
}
}
}
executePivotOn(changedPath) {
const numberOfAggregationColumns = this.valueColsSvc?.columns.length ?? 1;
const configuredMaxCols = this.gos.get("pivotMaxGeneratedColumns");
this.maxUniqueValues = configuredMaxCols === -1 ? -1 : configuredMaxCols / numberOfAggregationColumns;
let uniqueValues;
try {
uniqueValues = this.bucketUpRowNodes(changedPath);
} catch (e) {
if (e.message === EXCEEDED_MAX_UNIQUE_VALUES) {
this.pivotResultCols.setPivotResultCols([], "rowModelUpdated");
this.eventSvc.dispatchEvent({
type: "pivotMaxColumnsExceeded",
message: e.message
});
this.lastTimeFailed = true;
return;
}
throw e;
}
const uniqueValuesChanged = this.setUniqueValues(uniqueValues);
const aggregationColumns = this.valueColsSvc?.columns ?? [];
const aggregationColumnsHash = aggregationColumns.map((column) => `${column.getId()}-${column.getColDef().headerName}`).join("#");
const aggregationFuncsHash = aggregationColumns.map((column) => column.getAggFunc().toString()).join("#");
const aggregationColumnsChanged = this.aggregationColumnsHashLastTime !== aggregationColumnsHash;
const aggregationFuncsChanged = this.aggregationFuncsHashLastTime !== aggregationFuncsHash;
this.aggregationColumnsHashLastTime = aggregationColumnsHash;
this.aggregationFuncsHashLastTime = aggregationFuncsHash;
const groupColumnsHash = (this.rowGroupColsSvc?.columns ?? []).map((column) => column.getId()).join("#");
const groupColumnsChanged2 = groupColumnsHash !== this.groupColumnsHashLastTime;
this.groupColumnsHashLastTime = groupColumnsHash;
const pivotRowTotals = this.gos.get("pivotRowTotals");
const pivotColumnGroupTotals = this.gos.get("pivotColumnGroupTotals");
const suppressExpandablePivotGroups = this.gos.get("suppressExpandablePivotGroups");
const removePivotHeaderRowWhenSingleValueColumn = this.gos.get("removePivotHeaderRowWhenSingleValueColumn");
const anyGridOptionsChanged = pivotRowTotals !== this.pivotRowTotalsLastTime || pivotColumnGroupTotals !== this.pivotColumnGroupTotalsLastTime || suppressExpandablePivotGroups !== this.suppressExpandablePivotGroupsLastTime || removePivotHeaderRowWhenSingleValueColumn !== this.removePivotHeaderRowWhenSingleValueColumnLastTime;
this.pivotRowTotalsLastTime = pivotRowTotals;
this.pivotColumnGroupTotalsLastTime = pivotColumnGroupTotals;
this.suppressExpandablePivotGroupsLastTime = suppressExpandablePivotGroups;
this.removePivotHeaderRowWhenSingleValueColumnLastTime = removePivotHeaderRowWhenSingleValueColumn;
if (this.lastTimeFailed || uniqueValuesChanged || aggregationColumnsChanged || groupColumnsChanged2 || aggregationFuncsChanged || anyGridOptionsChanged) {
const pivotColumnGroupDefs = this.pivotColDefSvc.createPivotColumnDefs(this.uniqueValues);
this.pivotResultCols.setPivotResultCols(pivotColumnGroupDefs, "rowModelUpdated");
if (changedPath) {
changedPath.active = false;
}
}
this.lastTimeFailed = false;
}
setUniqueValues(newValues) {
const json1 = JSON.stringify(mapToObject(this.uniqueValues));
const json2 = JSON.stringify(mapToObject(newValues));
const uniqueValuesChanged = json1 !== json2;
if (uniqueValuesChanged) {
this.uniqueValues = newValues;
return true;
} else {
return false;
}
}
bucketUpRowNodes(changedPath) {
this.currentUniqueCount = 0;
const uniqueValues = /* @__PURE__ */ new Map();
changedPath.forEachChangedNodeDepthFirst((node) => {
if (node.leafGroup) {
node.childrenMapped = null;
}
});
const recursivelyBucketFilteredChildren = (node) => {
if (node.leafGroup) {
this.bucketRowNode(node, uniqueValues);
} else {
node.childrenAfterFilter?.forEach(recursivelyBucketFilteredChildren);
}
};
changedPath.executeFromRootNode(recursivelyBucketFilteredChildren);
return uniqueValues;
}
bucketRowNode(rowNode, uniqueValues) {
const pivotColumns = this.pivotColsSvc?.columns;
if (pivotColumns?.length === 0) {
rowNode.childrenMapped = null;
} else {
rowNode.childrenMapped = mapToObject(
this.bucketChildren(rowNode.childrenAfterFilter, pivotColumns, 0, uniqueValues)
);
}
if (rowNode.sibling) {
rowNode.sibling.childrenMapped = rowNode.childrenMapped;
}
}
bucketChildren(children, pivotColumns = [], pivotIndex, uniqueValues) {
const mappedChildren = /* @__PURE__ */ new Map();
const pivotColumn = pivotColumns[pivotIndex];
children.forEach((child) => {
let key = this.valueSvc.getKeyForNode(pivotColumn, child);
if ((0, import_ag_grid_community188._missing)(key)) {
key = "";
}
if (!uniqueValues.get(key)) {
this.currentUniqueCount += 1;
uniqueValues.set(key, /* @__PURE__ */ new Map());
const doesGeneratedColMaxExist = this.maxUniqueValues !== -1;
const hasExceededColMax = this.currentUniqueCount > this.maxUniqueValues;
if (doesGeneratedColMaxExist && hasExceededColMax) {
throw Error(EXCEEDED_MAX_UNIQUE_VALUES);
}
}
if (!mappedChildren.has(key)) {
mappedChildren.set(key, []);
}
mappedChildren.get(key).push(child);
});
if (pivotIndex === pivotColumns.length - 1) {
return mappedChildren;
}
const result = /* @__PURE__ */ new Map();
for (const key of mappedChildren.keys()) {
result.set(
key,
this.bucketChildren(mappedChildren.get(key), pivotColumns, pivotIndex + 1, uniqueValues.get(key))
);
}
return result;
}
};
// packages/ag-grid-enterprise/src/pivot/pivotModule.ts
var SharedPivotModule = {
moduleName: "SharedPivot",
version: VERSION,
beans: [PivotResultColsService, PivotColDefService, PivotColsSvc],
apiFunctions: {
isPivotMode,
getPivotResultColumn,
setValueColumns,
getValueColumns,
removeValueColumns,
addValueColumns,
setPivotColumns,
removePivotColumns,
addPivotColumns,
getPivotColumns,
setPivotResultColumns,
getPivotResultColumns
},
dependsOn: [SharedRowGroupingModule, import_ag_grid_community189._ColumnGroupModule]
};
var PivotModule = {
moduleName: "Pivot",
version: VERSION,
rowModels: ["clientSide"],
beans: [PivotStage],
dependsOn: [SharedPivotModule, RowGroupingModule, ClientSideRowModelHierarchyModule]
};
// packages/ag-grid-enterprise/src/treeData/clientSideChildrenTreeNodeManager.ts
var import_ag_grid_community190 = require("ag-grid-community");
var import_ag_grid_community191 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/treeData/fieldAccess.ts
var parseFieldPath = (fieldPath) => {
if (typeof fieldPath !== "string" || !fieldPath.length) {
return [];
}
const segments = fieldPath.split(".");
if (segments.includes("__proto__")) {
return [];
}
return segments;
};
var makeFieldPathGetter = (fieldPath) => {
const splitPath = parseFieldPath(fieldPath);
let result = null;
const last = splitPath.length - 1;
if (last === 0) {
result = (data) => data?.[fieldPath];
} else if (last > 0) {
result = (data) => {
let value = data;
for (let i = 0; i <= last && value !== null && value !== void 0; ++i) {
value = value[splitPath[i]];
if (i < last && typeof value !== "object" && value !== void 0) {
return null;
}
}
return value;
};
} else {
result = () => void 0;
}
result.path = fieldPath;
return result;
};
// packages/ag-grid-enterprise/src/treeData/clientSideChildrenTreeNodeManager.ts
var ClientSideChildrenTreeNodeManager = class extends import_ag_grid_community190.AbstractClientSideNodeManager {
constructor() {
super(...arguments);
this.beanName = "csrmChildrenTreeNodeSvc";
this.childrenGetter = null;
}
destroy() {
super.destroy();
this.childrenGetter = null;
}
extractRowData() {
return this.rootNode?.childrenAfterGroup?.map(({ data }) => data);
}
activate(rootNode) {
const oldChildrenGetter = this.childrenGetter;
const childrenField = this.gos.get("treeDataChildrenField") ?? null;
if (!oldChildrenGetter || oldChildrenGetter.path !== childrenField) {
this.childrenGetter = makeFieldPathGetter(childrenField);
}
super.activate(rootNode);
}
deactivate() {
this.childrenGetter = null;
super.deactivate();
}
updateRowData(_rowDataTran, changedRowNodes) {
(0, import_ag_grid_community191._warn)(268);
return {
changedRowNodes,
rowNodeTransaction: { add: [], remove: [], update: [] },
rowsInserted: false
};
}
loadNewRowData(rowData) {
const rootNode = this.rootNode;
const childrenGetter = this.childrenGetter;
const processedData = /* @__PURE__ */ new Map();
const allLeafChildren = [];
rootNode.allLeafChildren = allLeafChildren;
const processChild = (parent, data) => {
let row = processedData.get(data);
if (row !== void 0) {
(0, import_ag_grid_community191._error)(2, { nodeId: row.id });
return;
}
row = this.createRowNode(data, allLeafChildren.length);
row.treeParent = parent;
processedData.set(data, row);
allLeafChildren.push(row);
const children = childrenGetter?.(data);
if (children) {
for (let i = 0, len = children.length; i < len; ++i) {
processChild(row, children[i]);
}
}
};
for (let i = 0, len = rowData.length; i < len; ++i) {
processChild(rootNode, rowData[i]);
}
}
setImmutableRowData(params, rowData) {
this.dispatchRowDataUpdateStartedEvent(rowData);
const gos = this.gos;
const rootNode = this.rootNode;
const childrenGetter = this.childrenGetter;
const getRowIdFunc = (0, import_ag_grid_community191._getRowIdCallback)(gos);
const canReorder = !gos.get("suppressMaintainUnsortedOrder");
const processedData = /* @__PURE__ */ new Map();
const changedPath = new import_ag_grid_community191.ChangedPath(false, rootNode);
params.changedPath = changedPath;
const changedRowNodes = params.changedRowNodes;
const oldAllLeafChildren = rootNode.allLeafChildren;
const allLeafChildren = [];
const nodesToUnselect = [];
let orderChanged = false;
let rowsChanged = false;
const processChildren = (parent, children, childrenLevel) => {
const childrenLen = children?.length;
let inOrder = true;
let prevIndex = -1;
for (let i = 0; i < childrenLen; ++i) {
const oldSourceRowIndex = processChild(parent, children[i], childrenLevel);
if (canReorder && oldSourceRowIndex >= 0) {
if (oldSourceRowIndex < prevIndex) {
inOrder = false;
}
prevIndex = oldSourceRowIndex;
}
}
if (!inOrder) {
orderChanged = true;
}
};
const processChild = (parent, data, level) => {
let row = processedData.get(data);
if (row !== void 0) {
(0, import_ag_grid_community191._warn)(2, { nodeId: row.id });
return -1;
}
const id = getRowIdFunc({ data, level });
row = this.getRowNode(id);
if (row) {
let rowChanged = false;
if (row.data !== data) {
rowChanged = true;
row.updateData(data);
if (!row.selectable && row.isSelected()) {
nodesToUnselect.push(row);
}
}
if (row.treeParent !== parent) {
row.treeParent = parent;
rowChanged = true;
}
if (rowChanged) {
rowsChanged = true;
changedRowNodes.update(row);
}
} else {
row = this.createRowNode(data, -1);
row.treeParent = parent;
rowsChanged = true;
changedRowNodes.add(row);
}
processedData.set(data, row);
let oldSourceRowIndex;
if (canReorder) {
oldSourceRowIndex = row.sourceRowIndex;
row.sourceRowIndex = allLeafChildren.push(row) - 1;
} else {
oldSourceRowIndex = -1;
}
const children = childrenGetter?.(data);
if (children) {
processChildren(row, children, level + 1);
}
return oldSourceRowIndex;
};
processChildren(rootNode, rowData, 0);
if (oldAllLeafChildren) {
const pinnedRowModel = this.beans.pinnedRowModel;
for (let i = 0, len = oldAllLeafChildren.length; i < len; ++i) {
const row = oldAllLeafChildren[i];
if (!processedData.has(row.data)) {
row.treeParent = null;
row.treeNodeFlags = 0;
const pinnedSibling = row.pinnedSibling;
if (pinnedSibling) {
pinnedRowModel?.pinRow(pinnedSibling, null);
}
row.clearRowTopAndRowIndex();
this.rowNodeDeleted(row);
if (row.isSelected()) {
nodesToUnselect.push(row);
}
changedRowNodes.remove(row);
}
}
}
if (!canReorder) {
if (oldAllLeafChildren) {
const removals = changedRowNodes.removals;
for (let i = 0, len = oldAllLeafChildren.length; i < len; ++i) {
const row = oldAllLeafChildren[i];
if (!removals.has(row)) {
row.sourceRowIndex = allLeafChildren.push(row) - 1;
}
}
}
for (const row of changedRowNodes.adds) {
row.sourceRowIndex = allLeafChildren.push(row) - 1;
}
}
rootNode.allLeafChildren = allLeafChildren;
if (nodesToUnselect.length) {
this.deselectNodes(nodesToUnselect);
}
const sibling = rootNode.sibling;
if (sibling) {
sibling.allLeafChildren = allLeafChildren;
}
if (rowsChanged || orderChanged) {
params.rowDataUpdated = true;
params.rowNodesOrderChanged || (params.rowNodesOrderChanged = orderChanged);
}
}
};
// packages/ag-grid-enterprise/src/treeData/treeGroupStrategy.ts
var import_ag_grid_community192 = require("ag-grid-community");
var import_ag_grid_community193 = require("ag-grid-community");
var FLAG_CHILDREN_CHANGED = 2147483648;
var FLAG_CHANGED = 1073741824;
var FLAG_MARKED_FILLER = 536870912;
var FLAG_EXPANDED_INITIALIZED = 268435456;
var MASK_CHILDREN_LEN = 268435455;
var PATH_KEY_SEPARATOR = String.fromCharCode(31, 4096 + Math.random() * 61440, 4096 + Math.random() * 61440, 8291);
var TreeGroupStrategy = class extends import_ag_grid_community193.BeanStub {
constructor() {
super(...arguments);
this.groupColsIds = "";
this.groupColsChanged = true;
this.parentIdGetter = null;
this.fillerNodesById = null;
this.nodesToUnselect = null;
}
destroy() {
super.destroy();
this.groupColsIds = "";
this.parentIdGetter = null;
this.fillerNodesById = null;
this.nodesToUnselect = null;
}
reset() {
this.destroyFillerRows();
this.deselectHiddenNodes(false);
this.groupColsIds = "";
this.groupColsChanged = true;
this.parentIdGetter = null;
}
getNode(id) {
return this.fillerNodesById?.get(id);
}
execute(params, approach) {
const { changedRowNodes, changedPath, afterColumnsChanged } = params;
this.checkGroupColsUpdated(afterColumnsChanged);
const rootNode = params.rowNode;
const activeChangedPath = changedPath?.active ? changedPath : void 0;
const fullReload = !changedRowNodes && !activeChangedPath;
const hasUpdates = !!changedRowNodes && this.flagUpdatedNodes(changedRowNodes);
if (fullReload || hasUpdates) {
if (approach === "treeNested") {
this.loadNested(params, fullReload);
} else if (approach === "treeSelfRef") {
this.loadSelfRef(params, fullReload);
} else {
this.loadDataPath(params, fullReload);
}
}
const parentsChanged = this.initRowsParents(rootNode);
this.destroyFillerRows();
this.initRowsChildrenSize(rootNode);
let preprocessedCount = this.preprocessRows(rootNode);
const treeChanged = parentsChanged || (preprocessedCount & FLAG_CHILDREN_CHANGED) !== 0;
preprocessedCount &= ~FLAG_CHILDREN_CHANGED;
const traverseCount = this.traverseRoot(rootNode, activeChangedPath);
if (preprocessedCount > 0 && preprocessedCount !== traverseCount) {
this.handleCycles(rootNode);
this.traverseRoot(rootNode, activeChangedPath);
}
rootNode.treeNodeFlags = 0;
this.deselectHiddenNodes(parentsChanged || fullReload);
return treeChanged;
}
flagUpdatedNodes(changedRowNodes) {
const { adds, updates, removals } = changedRowNodes;
let hasUpdates = removals.size > 0;
if (adds.size > 0) {
hasUpdates = true;
for (const node of adds) {
node.treeNodeFlags |= FLAG_CHANGED;
}
}
if (updates.size > 0) {
hasUpdates = true;
for (const node of updates) {
node.treeNodeFlags |= FLAG_CHANGED;
}
}
return hasUpdates;
}
initRowsParents(rootNode) {
const rootAllLeafChildren = rootNode.allLeafChildren;
const allLeafChildrenLen = rootAllLeafChildren.length;
let treeChanged = false;
for (let i = 0; i < allLeafChildrenLen; ++i) {
let current = rootAllLeafChildren[i];
while (true) {
const oldParent = current.parent;
const parent = current.treeParent;
if (parent === null) {
if (oldParent) {
treeChanged = true;
this.hideRow(current);
}
break;
}
let parentFlags = parent.treeNodeFlags + 1;
if (oldParent !== parent) {
treeChanged = true;
parentFlags |= FLAG_CHANGED;
current.parent = parent;
if (oldParent) {
const oldParentFlags = oldParent.treeNodeFlags;
if ((oldParentFlags & FLAG_EXPANDED_INITIALIZED) !== 0 && (parentFlags & FLAG_EXPANDED_INITIALIZED) === 0 && parent.treeParent !== null && !parent.data) {
parent.expanded = oldParent.expanded;
parentFlags |= FLAG_EXPANDED_INITIALIZED;
}
oldParent.treeNodeFlags = oldParentFlags | FLAG_CHANGED;
}
}
if (parent.data || (parent.treeNodeFlags & FLAG_MARKED_FILLER) !== 0 || parent.treeParent === null) {
parent.treeNodeFlags = parentFlags;
break;
}
parent.treeNodeFlags = parentFlags | FLAG_MARKED_FILLER | current.treeNodeFlags & FLAG_CHANGED;
current = parent;
}
}
return treeChanged;
}
destroyFillerRows() {
const fillerNodesById = this.fillerNodesById;
if (fillerNodesById) {
for (const node of fillerNodesById.values()) {
if (node.treeParent === null || (node.treeNodeFlags & MASK_CHILDREN_LEN) === 0) {
fillerNodesById.delete(node.id);
this.hideRow(node);
}
}
if (fillerNodesById.size === 0) {
this.fillerNodesById = null;
}
}
}
initRowsChildrenSize(rootNode) {
this.initRowChildrenSize(rootNode);
const rootAllLeafChildren = rootNode.allLeafChildren;
const allLeafChildrenLen = rootAllLeafChildren.length;
for (let i = 0; i < allLeafChildrenLen; ++i) {
this.initRowChildrenSize(rootAllLeafChildren[i]);
}
const fillerNodesById = this.fillerNodesById;
if (fillerNodesById !== null) {
for (const filler of fillerNodesById.values()) {
this.initRowChildrenSize(filler);
}
}
}
initRowChildrenSize(row) {
let { childrenAfterGroup, allLeafChildren, treeNodeFlags } = row;
const oldLen = childrenAfterGroup?.length;
const len = treeNodeFlags & MASK_CHILDREN_LEN;
row.treeNodeFlags = treeNodeFlags & ~MASK_CHILDREN_LEN | ((oldLen || 0) !== len ? FLAG_CHILDREN_CHANGED : 0);
if (len === 0 && row.level >= 0) {
if (childrenAfterGroup !== import_ag_grid_community193._EmptyArray) {
row.childrenAfterGroup = import_ag_grid_community193._EmptyArray;
const sibling = row.sibling;
if (sibling)
sibling.childrenAfterGroup = import_ag_grid_community193._EmptyArray;
}
} else if (oldLen !== len || childrenAfterGroup === allLeafChildren) {
if (!childrenAfterGroup || childrenAfterGroup === import_ag_grid_community193._EmptyArray || childrenAfterGroup === allLeafChildren) {
row.childrenAfterGroup = childrenAfterGroup = new Array(len);
const sibling = row.sibling;
if (sibling)
sibling.childrenAfterGroup = childrenAfterGroup;
} else {
childrenAfterGroup.length = len;
}
}
}
preprocessRows(rootNode) {
const rootAllLeafChildren = rootNode.allLeafChildren;
const allLeafChildrenLen = rootAllLeafChildren.length;
const groupColsChanged = this.groupColsChanged;
let preprocessedCount = 0;
let treeChanged = false;
for (let i = 0; i < allLeafChildrenLen; ++i) {
let current = rootAllLeafChildren[i];
while (true) {
const parent = current.treeParent;
if (parent === null) {
break;
}
++preprocessedCount;
let parentFlags = parent.treeNodeFlags;
const parentChildren = parent.childrenAfterGroup;
const indexInParent = parentFlags & MASK_CHILDREN_LEN;
parentFlags = parentFlags & ~MASK_CHILDREN_LEN | indexInParent + 1;
if (parentFlags & FLAG_CHILDREN_CHANGED || parentChildren[indexInParent] !== current) {
parentFlags |= FLAG_CHILDREN_CHANGED;
parentChildren[indexInParent] = current;
treeChanged = true;
}
parent.treeNodeFlags = parentFlags;
if (!current.groupData || groupColsChanged) {
current.treeNodeFlags |= FLAG_CHANGED;
this.setGroupData(current, current.key);
}
if (parent.data || (parent.treeNodeFlags & FLAG_MARKED_FILLER) === 0 || parent.treeParent === null) {
break;
}
parent.treeNodeFlags = parentFlags & ~FLAG_MARKED_FILLER | current.treeNodeFlags & FLAG_CHANGED;
current = parent;
}
}
return preprocessedCount | (treeChanged ? FLAG_CHILDREN_CHANGED : 0);
}
traverseRoot(rootNode, activeChangedPath) {
let traverseCount = 0;
const rootChildrenAfterGroup = rootNode.childrenAfterGroup;
for (let i = 0, len = rootChildrenAfterGroup.length; i < len; ++i) {
traverseCount += this.traverse(rootChildrenAfterGroup[i], 0, false, activeChangedPath);
}
return traverseCount & ~FLAG_CHILDREN_CHANGED;
}
/**
* After all the rows are initialized and treeParent is set and childrenAfterGroup is filled,
* we traverse the tree to finalize it
* @returns the number of leaf nodes processed, which is used to detect cycles in the tree, and a flag set if leaf children were changed.
*/
traverse(row, level, collapsed, activeChangedPath) {
const children = row.childrenAfterGroup;
const len = children.length;
let flags = row.treeNodeFlags;
row.treeNodeFlags = flags & FLAG_EXPANDED_INITIALIZED;
row.level = level;
if (row.group !== !!len) {
setRowNodeGroup(row, this.beans, !!len);
flags |= FLAG_CHANGED;
} else if (row.hasChildren() !== !!len) {
row.updateHasChildren();
flags |= FLAG_CHANGED;
}
if ((flags & (FLAG_CHANGED | FLAG_CHILDREN_CHANGED)) !== 0) {
activeChangedPath?.addParentNode(row);
}
const canBeExpanded = len !== 0 || row.master;
if (!canBeExpanded) {
if (row.expanded) {
row.expanded = false;
}
if ((flags & FLAG_EXPANDED_INITIALIZED) !== 0) {
row.treeNodeFlags &= ~FLAG_EXPANDED_INITIALIZED;
}
} else if ((flags & FLAG_EXPANDED_INITIALIZED) === 0) {
row.treeNodeFlags |= FLAG_EXPANDED_INITIALIZED;
row.expanded = _getRowDefaultExpanded(this.beans, row, level);
}
if (collapsed && row.rowIndex !== null) {
row.clearRowTopAndRowIndex();
}
collapsed || (collapsed = row.expanded === false);
++level;
flags &= FLAG_CHILDREN_CHANGED;
let leafsLen = 0;
for (let i = 0; i < len; ++i) {
const child = children[i];
const childFlags = this.traverse(child, level, collapsed, activeChangedPath);
flags = flags + (childFlags & ~FLAG_CHILDREN_CHANGED) | childFlags & FLAG_CHILDREN_CHANGED;
leafsLen += (child.allLeafChildren?.length || 0) + (child.data ? 1 : 0);
}
if (this.updateAllLeafChildren(row, leafsLen, (flags & FLAG_CHILDREN_CHANGED) !== 0)) {
return (flags | FLAG_CHILDREN_CHANGED) + 1;
}
return (flags & ~FLAG_CHILDREN_CHANGED) + 1;
}
updateAllLeafChildren(row, len, maybeChanged) {
let leafs = row.allLeafChildren;
let trulyChanged = (leafs?.length || 0) !== len;
if (len === 0) {
if (leafs !== null) {
row.allLeafChildren = null;
const sibling = row.sibling;
if (sibling)
sibling.allLeafChildren = null;
}
} else if (trulyChanged || maybeChanged) {
if (!leafs) {
row.allLeafChildren = leafs = new Array(len);
const sibling = row.sibling;
if (sibling)
sibling.allLeafChildren = leafs;
} else if (trulyChanged) {
leafs.length = len;
}
const rows = row.childrenAfterGroup;
for (let i = 0, writeIdx = 0, childrenLen = rows.length; i < childrenLen; ++i) {
const child = rows[i];
if (child.data) {
if (trulyChanged || (trulyChanged = leafs[writeIdx] !== child))
leafs[writeIdx] = child;
++writeIdx;
}
const childLeafs = child.allLeafChildren;
if (childLeafs) {
for (let j = 0, len2 = childLeafs.length; j < len2; ++j, ++writeIdx) {
const leaf = childLeafs[j];
if (trulyChanged || (trulyChanged = leafs[writeIdx] !== leaf))
leafs[writeIdx] = leaf;
}
}
}
}
return trulyChanged;
}
/** Handle cycles in a tree. Is not optimal for performance but this is an edge case that shouldn't happen as is a warning. */
handleCycles(rootNode) {
const marked = /* @__PURE__ */ new Set();
const mark = (row) => {
if (marked.has(row))
return false;
marked.add(row);
row.childrenAfterGroup.forEach(mark);
return true;
};
mark(rootNode);
const rootChildrenAfterGroup = rootNode.childrenAfterGroup;
rootChildrenAfterGroup.length = 0;
for (const row of rootNode.allLeafChildren) {
const parent = row.treeParent;
if (parent && mark(row)) {
parent.treeNodeFlags |= FLAG_CHILDREN_CHANGED | FLAG_CHANGED;
row.parent = rootNode;
(0, import_ag_grid_community192._removeFromArray)(parent.childrenAfterGroup, row);
rootChildrenAfterGroup.push(row);
(0, import_ag_grid_community193._warn)(270, { id: row.id, parentId: parent?.id ?? "" });
} else if (parent === rootNode) {
rootChildrenAfterGroup.push(row);
}
}
}
setGroupData(row, key) {
const groupData = {};
const groupDisplayCols = this.beans.showRowGroupCols?.getShowRowGroupCols();
row.groupData = groupData;
if (groupDisplayCols) {
for (const col of groupDisplayCols) {
groupData[col.getColId()] = key;
}
}
}
/** Load the tree structure for nested groups, aka children property */
loadNested({ rowNode: rootNode, changedRowNodes }, fullReload) {
if (!fullReload && changedRowNodes) {
for (const row of changedRowNodes.adds) {
row.key = row.id;
}
return;
}
const rootAllLeafChildren = rootNode.allLeafChildren;
for (let i = 0, len = rootAllLeafChildren.length; i < len; ++i) {
const row = rootAllLeafChildren[i];
const id = row.id;
if (row.key !== id) {
row.key = id;
row.groupData = null;
}
}
}
/** Load the tree structure for self-referencing data, aka parentId field */
loadSelfRef({ rowNode: rootNode, changedRowNodes }, fullReload) {
const rootAllLeafChildren = rootNode.allLeafChildren;
const gos = this.gos;
if (!gos.get("getRowId")) {
for (let i = 0, len = rootAllLeafChildren.length; i < len; ++i) {
rootAllLeafChildren[i].treeParent = null;
}
return;
}
const rowModel = this.beans.rowModel;
const removals = changedRowNodes?.removals;
let parentIdGetter = this.parentIdGetter;
const parentIdField = gos.get("treeDataParentIdField") || null;
if (parentIdGetter?.path !== parentIdField) {
this.parentIdGetter = parentIdGetter = makeFieldPathGetter(parentIdField);
fullReload = true;
}
for (let i = 0, len = rootAllLeafChildren.length; i < len; ++i) {
const row = rootAllLeafChildren[i];
if (fullReload || row.treeNodeFlags & FLAG_CHANGED || removals?.has(row.treeParent)) {
let newParent;
const parentId = parentIdGetter(row.data);
if (parentId !== null && parentId !== void 0) {
newParent = rowModel.getRowNode(parentId);
if (!newParent) {
(0, import_ag_grid_community193._warn)(271, { id: row.id, parentId });
}
}
row.treeParent = newParent ?? rootNode;
const id = row.id;
if (row.key !== id) {
row.key = id;
row.groupData = null;
}
} else {
row.treeParent ?? (row.treeParent = rootNode);
}
}
}
loadFlattened(rootNode) {
const allLeafChildren = rootNode.allLeafChildren;
for (let i = 0, len = allLeafChildren.length; i < len; ++i) {
const row = allLeafChildren[i];
row.treeParent = rootNode;
const id = row.id;
if (row.key !== id) {
row.key = id;
row.groupData = null;
}
}
}
/** Load the tree structure for data paths, aka getDataPath callback */
loadDataPath({ rowNode: rootNode }, fullReload) {
const getDataPath = this.gos.get("getDataPath");
if (!getDataPath) {
this.loadFlattened(rootNode);
return;
}
const nodesByPath = /* @__PURE__ */ new Map();
const paths = /* @__PURE__ */ new Map();
let dupPaths;
if (!fullReload) {
dupPaths = this.loadExistingDataPath(rootNode, nodesByPath, paths);
}
const allLeafChildren = rootNode.allLeafChildren;
for (let i = 0, len = allLeafChildren.length; i < len; ++i) {
const node = allLeafChildren[i];
if (!fullReload && node.treeParent !== null && (node.treeNodeFlags & FLAG_CHANGED) === 0) {
continue;
}
const path = getDataPath(node.data);
const pathLen = path?.length;
if (!pathLen) {
(0, import_ag_grid_community193._warn)(185, { data: node.data });
continue;
}
const key = path[pathLen - 1];
if (node.key !== key) {
node.key = key;
node.groupData = null;
}
const pathKey = path.join(PATH_KEY_SEPARATOR);
paths.set(node, pathKey);
const existing = nodesByPath.get(pathKey);
if (existing === void 0) {
nodesByPath.set(pathKey, node);
} else if (existing !== node) {
dupPaths = this.duplicatedPath(nodesByPath, dupPaths, existing, node, pathKey);
}
}
if (dupPaths) {
this.processDuplicatePaths(dupPaths, paths);
}
this.buildFromPaths(rootNode, nodesByPath, paths);
}
loadExistingDataPath(rootNode, nodesByPath, paths) {
let dupPaths;
const allLeafChildren = rootNode.allLeafChildren;
for (let i = 0, len = allLeafChildren.length; i < len; ++i) {
const node = allLeafChildren[i];
const treeParent = node.treeParent;
if (treeParent === null || (node.treeNodeFlags & FLAG_CHANGED) !== 0) {
continue;
}
let pathKey = node.key;
let current = treeParent;
while (current && current !== rootNode && current !== node) {
pathKey = PATH_KEY_SEPARATOR + pathKey;
const existingPathKey = paths.get(current);
if (existingPathKey !== void 0) {
pathKey = existingPathKey + pathKey;
break;
}
pathKey = current.key + pathKey;
current = current.treeParent;
}
if (current !== node) {
paths.set(node, pathKey);
const existing = nodesByPath.get(pathKey);
if (existing === void 0) {
nodesByPath.set(pathKey, node);
} else if (existing !== node) {
dupPaths = this.duplicatedPath(nodesByPath, dupPaths, existing, node, pathKey);
}
}
}
return dupPaths;
}
duplicatedPath(nodesByPath, dupPaths, existing, node, pathKey) {
if (node.sourceRowIndex < existing.sourceRowIndex) {
nodesByPath.set(pathKey, node);
}
const duplicates = (dupPaths ?? (dupPaths = /* @__PURE__ */ new Map())).get(pathKey);
if (duplicates === void 0) {
dupPaths.set(pathKey, [existing, node]);
} else {
duplicates.push(node);
}
return dupPaths;
}
buildFromPaths(rootNode, nodesByPath, paths) {
const SEP = PATH_KEY_SEPARATOR;
const SEP_LEN = PATH_KEY_SEPARATOR.length;
const segments = new Array(32);
const allLeafChildren = rootNode.allLeafChildren;
for (let i = 0, len = allLeafChildren.length; i < len; ++i) {
const node = allLeafChildren[i];
const pathKey = paths.get(node);
if (pathKey === void 0) {
continue;
}
let segmentsLen = 0;
let scanPos = 0;
while (scanPos < pathKey.length) {
const sepPos = pathKey.indexOf(SEP, scanPos);
if (sepPos === -1)
break;
segments[segmentsLen++] = sepPos;
scanPos = sepPos + SEP_LEN;
}
let startLevel = 0;
let treeParent = rootNode;
for (let level = segmentsLen - 1; level >= 0; --level) {
const existing = nodesByPath.get(pathKey.slice(0, segments[level]));
if (existing) {
treeParent = existing;
startLevel = level + 1;
break;
}
}
for (let level = startLevel; level < segmentsLen; ++level) {
const end = segments[level];
const start = level === 0 ? 0 : segments[level - 1] + SEP_LEN;
const subPath = pathKey.slice(0, end);
let current = nodesByPath.get(subPath);
if (current === void 0) {
current = this.getOrCreateFiller(treeParent, pathKey.slice(start, end), level);
nodesByPath.set(subPath, current);
} else {
current.treeParent = treeParent;
}
treeParent = current;
}
node.treeParent = treeParent;
}
}
processDuplicatePaths(duplicatePaths, paths) {
for (const duplicates of duplicatePaths.values()) {
duplicates.sort(compareSourceRowIndex);
const len = duplicates.length;
const duplicateRowsData = new Array(len - 1);
for (let i = 1; i < len; ++i) {
const node = duplicates[i];
paths.delete(node);
node.treeParent = null;
duplicateRowsData[i - 1] = node.data;
}
const first = duplicates[0];
(0, import_ag_grid_community193._warn)(186, { rowId: first.id, rowData: first.data, duplicateRowsData });
}
}
getOrCreateFiller(treeParent, key, level) {
let id = level + "-" + key;
let current = treeParent;
while (--level >= 0) {
id = level + "-" + current.key + "-" + id;
current = current.treeParent;
}
id = import_ag_grid_community192._ROW_ID_PREFIX_ROW_GROUP + id;
const fillerNodesById = this.fillerNodesById ?? (this.fillerNodesById = /* @__PURE__ */ new Map());
let node = fillerNodesById.get(id);
if (node === void 0) {
node = new import_ag_grid_community192.RowNode(this.beans);
node.id = id;
node.key = key;
node.group = true;
node.leafGroup = false;
node.rowGroupIndex = null;
node.treeParent = treeParent;
fillerNodesById.set(id, node);
}
return node;
}
deselectHiddenNodes(updated) {
const selectionSvc = this.beans.selectionSvc;
const nodes = this.nodesToUnselect;
const source = "rowDataChanged";
if (nodes) {
this.nodesToUnselect = null;
selectionSvc?.setNodesSelected({ newValue: false, nodes, suppressFinishActions: true, source });
}
if (nodes || updated) {
selectionSvc?.updateGroupsFromChildrenSelections?.(source);
}
if (nodes) {
const selectedNodes = selectionSvc?.getSelectedNodes() ?? null;
this.eventSvc.dispatchEvent({ type: "selectionChanged", source, selectedNodes, serverSideState: null });
}
}
hideRow(row) {
if (row.isSelected()) {
(this.nodesToUnselect ?? (this.nodesToUnselect = [])).push(row);
}
row.parent = null;
row.group = false;
row.groupData = null;
row.treeParent = null;
row.treeNodeFlags = 0;
row.allLeafChildren = null;
row.childrenAfterGroup = import_ag_grid_community193._EmptyArray;
const sibling = row.sibling;
if (sibling) {
sibling.allLeafChildren = null;
sibling.childrenAfterGroup = import_ag_grid_community193._EmptyArray;
}
row.updateHasChildren();
if (row.rowIndex !== null) {
row.clearRowTopAndRowIndex();
}
}
checkGroupColsUpdated(afterColumnsChanged) {
this.groupColsChanged = false;
if (afterColumnsChanged || !this.groupColsIds) {
const cols = this.beans.showRowGroupCols?.getShowRowGroupCols() ?? import_ag_grid_community193._EmptyArray;
let groupColsIds = "";
for (let i = 0, len = cols.length; i < len; ++i) {
groupColsIds += cols[i].getId() + PATH_KEY_SEPARATOR;
}
if (this.groupColsIds !== groupColsIds) {
this.groupColsIds = groupColsIds;
this.groupColsChanged = true;
}
}
}
};
var compareSourceRowIndex = (a, b) => a.sourceRowIndex - b.sourceRowIndex;
// packages/ag-grid-enterprise/src/treeData/treeDataModule.ts
var SharedTreeDataModule = {
moduleName: "SharedTreeData",
version: VERSION,
dependsOn: [EnterpriseCoreModule, SharedAggregationModule, GroupColumnModule, StickyRowModule]
};
var TreeDataModule = {
moduleName: "TreeData",
version: VERSION,
beans: [ClientSideChildrenTreeNodeManager],
dynamicBeans: { treeGroupStrategy: TreeGroupStrategy },
rowModels: ["clientSide"],
dependsOn: [SharedTreeDataModule, AggregationModule, ClientSideRowModelHierarchyModule]
};
// packages/ag-grid-enterprise/src/serverSideRowModel/blocks/blockUtils.ts
var import_ag_grid_community194 = require("ag-grid-community");
var GROUP_MISSING_KEY_ID = "ag-Grid-MissingKey";
var BlockUtils = class extends import_ag_grid_community194.BeanStub {
constructor() {
super(...arguments);
this.beanName = "ssrmBlockUtils";
}
wireBeans(beans) {
this.valueSvc = beans.valueSvc;
this.showRowGroupCols = beans.showRowGroupCols;
this.nodeManager = beans.ssrmNodeManager;
this.expansionSvc = beans.expansionSvc;
this.serverSideRowModel = beans.rowModel;
this.storeFactory = beans.ssrmStoreFactory;
}
createRowNode(params) {
const rowNode = new import_ag_grid_community194.RowNode(this.beans);
const rowHeight = params.rowHeight != null ? params.rowHeight : (0, import_ag_grid_community194._getRowHeightAsNumber)(this.beans);
rowNode.setRowHeight(rowHeight);
rowNode.group = params.group;
rowNode.leafGroup = params.leafGroup;
rowNode.level = params.level;
rowNode.uiLevel = params.level;
rowNode.parent = params.parent;
rowNode.stub = true;
rowNode.__needsRefreshWhenVisible = false;
if (rowNode.group) {
rowNode.expanded = false;
rowNode.field = params.field;
rowNode.rowGroupColumn = params.rowGroupColumn;
rowNode.rowGroupIndex = params.level;
}
return rowNode;
}
destroyRowNode(rowNode, preserveStore = false) {
if (rowNode.childStore && !preserveStore) {
this.destroyBean(rowNode.childStore);
rowNode.childStore = null;
}
if (rowNode.sibling && !rowNode.footer) {
this.destroyRowNode(rowNode.sibling, false);
}
rowNode.clearRowTopAndRowIndex();
if (rowNode.id != null) {
this.nodeManager.removeNode(rowNode);
}
}
setTreeGroupInfo(rowNode) {
rowNode.updateHasChildren();
const getKeyFunc = this.gos.get("getServerSideGroupKey");
const hasChildren = rowNode.hasChildren();
if (hasChildren && getKeyFunc != null) {
rowNode.key = getKeyFunc(rowNode.data);
}
if (!hasChildren && rowNode.childStore != null) {
this.destroyBean(rowNode.childStore);
rowNode.childStore = null;
if (!rowNode.master) {
rowNode.expanded = false;
}
}
}
setRowGroupInfo(rowNode) {
rowNode.key = this.valueSvc.getValue(rowNode.rowGroupColumn, rowNode);
if (rowNode.key === null || rowNode.key === void 0) {
(0, import_ag_grid_community194._doOnce)(() => {
(0, import_ag_grid_community194._warn)(190, { rowGroupId: rowNode.rowGroupColumn?.getId(), data: rowNode.data });
}, "SSBlock-BadKey");
}
const isUnbalancedGroup = this.gos.get("groupAllowUnbalanced") && rowNode.key === "";
if (isUnbalancedGroup) {
const storeParams = this.serverSideRowModel.getParams();
rowNode.childStore = this.createBean(this.storeFactory.createStore(storeParams, rowNode));
}
const getGroupIncludeFooter = (0, import_ag_grid_community194._getGroupTotalRowCallback)(this.beans.gos);
const doesRowShowFooter = getGroupIncludeFooter({ node: rowNode });
if (doesRowShowFooter) {
_createRowNodeFooter(rowNode, this.beans);
if (rowNode.sibling) {
rowNode.sibling.uiLevel = rowNode.uiLevel + 1;
}
}
}
setMasterDetailInfo(rowNode) {
const isMasterFunc = this.gos.get("isRowMaster");
if (isMasterFunc != null) {
rowNode.master = isMasterFunc(rowNode.data);
} else {
rowNode.master = true;
}
}
updateDataIntoRowNode(rowNode, data) {
rowNode.updateData(data);
if (this.gos.get("treeData")) {
this.setTreeGroupInfo(rowNode);
this.setChildCountIntoRowNode(rowNode);
this.updateRowFooter(rowNode);
} else if (rowNode.group) {
this.setChildCountIntoRowNode(rowNode);
this.updateRowFooter(rowNode);
} else if (this.gos.get("masterDetail")) {
}
}
updateRowFooter(rowNode) {
if (rowNode.footer) {
return;
}
if (rowNode.group) {
const getGroupIncludeFooter = (0, import_ag_grid_community194._getGroupTotalRowCallback)(this.beans.gos);
const shouldRowShowFooter = getGroupIncludeFooter({ node: rowNode });
if (shouldRowShowFooter && !rowNode.sibling) {
_createRowNodeFooter(rowNode, this.beans);
return;
}
}
if (rowNode.sibling) {
_destroyRowNodeFooter(rowNode);
}
}
setDataIntoRowNode(rowNode, data, defaultId, cachedRowHeight) {
rowNode.stub = false;
const treeData = this.gos.get("treeData");
rowNode.setDataAndId(data, defaultId);
const group = rowNode.group;
if ((treeData || !group) && this.gos.get("masterDetail")) {
this.setMasterDetailInfo(rowNode);
}
if (treeData) {
this.setTreeGroupInfo(rowNode);
} else if (group) {
this.setRowGroupInfo(rowNode);
}
if (treeData || group) {
this.setGroupDataIntoRowNode(rowNode);
this.setChildCountIntoRowNode(rowNode);
}
if ((0, import_ag_grid_community194._exists)(data)) {
rowNode.setRowHeight((0, import_ag_grid_community194._getRowHeightForNode)(this.beans, rowNode, false, cachedRowHeight).height);
rowNode.sibling?.setRowHeight(
(0, import_ag_grid_community194._getRowHeightForNode)(this.beans, rowNode.sibling, false, cachedRowHeight).height
);
}
}
setChildCountIntoRowNode(rowNode) {
const getChildCount = this.gos.get("getChildCount");
if (getChildCount) {
rowNode.setAllChildrenCount(getChildCount(rowNode.data));
}
}
setGroupDataIntoRowNode(rowNode) {
rowNode.groupValue = rowNode.key;
const groupDisplayCols = this.showRowGroupCols?.getShowRowGroupCols() ?? [];
const usingTreeData = this.gos.get("treeData");
groupDisplayCols.forEach((col) => {
if (rowNode.groupData == null) {
rowNode.groupData = {};
}
if (usingTreeData) {
rowNode.groupData[col.getColId()] = rowNode.key;
} else if (col.isRowGroupDisplayed(rowNode.rowGroupColumn.getId())) {
const groupValue = this.valueSvc.getValue(rowNode.rowGroupColumn, rowNode);
rowNode.groupData[col.getColId()] = groupValue;
}
});
}
clearDisplayIndex(rowNode) {
rowNode.clearRowTopAndRowIndex();
const hasChildStore = rowNode.hasChildren() && !!rowNode.childStore;
if (hasChildStore) {
rowNode.childStore?.clearDisplayIndexes();
}
const hasDetailNode = rowNode.master && rowNode.detailNode;
if (hasDetailNode) {
rowNode.detailNode?.clearRowTopAndRowIndex();
}
}
setDisplayIndex(rowNode, displayIndexSeq, nextRowTop, uiLevel) {
const isUnbalancedGroup = this.gos.get("groupAllowUnbalanced") && rowNode.group && rowNode.key === "";
const isHiddenOpenGroup = this.gos.get("groupHideOpenParents") && rowNode.group && rowNode.expanded;
if (isHiddenOpenGroup || isUnbalancedGroup) {
rowNode.setRowIndex(null);
rowNode.setRowTop(null);
} else {
rowNode.setRowIndex(displayIndexSeq.value++);
rowNode.setRowTop(nextRowTop.value);
nextRowTop.value += rowNode.rowHeight;
}
rowNode.setUiLevel(uiLevel);
if (rowNode.footer) {
return;
}
const hasDetailRow = rowNode.master;
if (hasDetailRow) {
if (rowNode.expanded && rowNode.detailNode) {
rowNode.detailNode.setRowIndex(displayIndexSeq.value++);
rowNode.detailNode.setRowTop(nextRowTop.value);
nextRowTop.value += rowNode.detailNode.rowHeight;
} else if (rowNode.detailNode) {
rowNode.detailNode.clearRowTopAndRowIndex();
}
}
const hasChildStore = rowNode.hasChildren() && !!rowNode.childStore;
if (hasChildStore) {
const childStore = rowNode.childStore;
if (rowNode.expanded || isUnbalancedGroup) {
childStore.setDisplayIndexes(displayIndexSeq, nextRowTop, isUnbalancedGroup ? uiLevel : uiLevel + 1);
} else {
childStore.clearDisplayIndexes();
}
}
}
extractRowBounds(rowNode, index) {
const extractRowBounds = (currentRowNode) => ({
rowHeight: currentRowNode.rowHeight,
rowTop: currentRowNode.rowTop
});
if (rowNode.rowIndex === index) {
return extractRowBounds(rowNode);
}
if (rowNode.hasChildren() && rowNode.expanded && !!rowNode.childStore) {
const childStore = rowNode.childStore;
if (childStore.isDisplayIndexInStore(index)) {
return childStore.getRowBounds(index);
}
} else if (rowNode.master && rowNode.expanded && rowNode.detailNode) {
if (rowNode.detailNode.rowIndex === index) {
return extractRowBounds(rowNode.detailNode);
}
}
}
isPixelInNodeRange(node, pixel) {
if (!(0, import_ag_grid_community194._exists)(node.rowTop) || !(0, import_ag_grid_community194._exists)(node.rowHeight)) {
return false;
}
return pixel >= node.rowTop && pixel < node.rowTop + node.rowHeight;
}
getIndexAtPixel(rowNode, pixel) {
if (this.isPixelInNodeRange(rowNode, pixel)) {
return rowNode.rowIndex;
}
const expandedMasterRow = rowNode.master && rowNode.expanded;
const detailNode = rowNode.detailNode;
if (expandedMasterRow && detailNode && this.isPixelInNodeRange(detailNode, pixel)) {
return detailNode.rowIndex;
}
if (rowNode.hasChildren() && rowNode.expanded && !!rowNode.childStore) {
const childStore = rowNode.childStore;
if (childStore.isPixelInRange(pixel)) {
return childStore.getRowIndexAtPixel(pixel);
}
}
return null;
}
createNodeIdPrefix(parentRowNode) {
const parts = [];
let rowNode = parentRowNode;
while (rowNode && rowNode.level >= 0) {
if (rowNode.key === "") {
parts.push(GROUP_MISSING_KEY_ID);
} else {
parts.push(rowNode.key);
}
rowNode = rowNode.parent;
}
if (parts.length > 0) {
return parts.reverse().join("-");
}
return void 0;
}
checkOpenByDefault(rowNode) {
return this.expansionSvc?.checkOpenByDefault(rowNode);
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/listeners/expandListener.ts
var import_ag_grid_community195 = require("ag-grid-community");
var ExpandListener = class extends import_ag_grid_community195.BeanStub {
constructor() {
super(...arguments);
this.beanName = "ssrmExpandListener";
}
wireBeans(beans) {
this.serverSideRowModel = beans.rowModel;
this.storeFactory = beans.ssrmStoreFactory;
}
postConstruct() {
if (!(0, import_ag_grid_community195._isServerSideRowModel)(this.gos)) {
return;
}
this.addManagedEventListeners({ rowGroupOpened: this.onRowGroupOpened.bind(this) });
}
onRowGroupOpened(event) {
const rowNode = event.node;
if (rowNode.expanded) {
if (rowNode.master) {
this.createDetailNode(rowNode);
}
if ((0, import_ag_grid_community195._missing)(rowNode.childStore) && rowNode.hasChildren()) {
const storeParams = this.serverSideRowModel.getParams();
rowNode.childStore = this.createBean(this.storeFactory.createStore(storeParams, rowNode));
}
} else if (this.gos.get("purgeClosedRowNodes") && (0, import_ag_grid_community195._exists)(rowNode.childStore)) {
rowNode.childStore = this.destroyBean(rowNode.childStore);
}
this.eventSvc.dispatchEvent({ type: "storeUpdated" });
}
createDetailNode(masterNode) {
if ((0, import_ag_grid_community195._exists)(masterNode.detailNode)) {
return masterNode.detailNode;
}
const detailNode = new import_ag_grid_community195.RowNode(this.beans);
detailNode.detail = true;
detailNode.selectable = false;
detailNode.parent = masterNode;
if ((0, import_ag_grid_community195._exists)(masterNode.id)) {
detailNode.id = "detail_" + masterNode.id;
}
detailNode.data = masterNode.data;
detailNode.level = masterNode.level + 1;
const defaultDetailRowHeight = 200;
const rowHeight = (0, import_ag_grid_community195._getRowHeightForNode)(this.beans, detailNode).height;
detailNode.rowHeight = rowHeight ? rowHeight : defaultDetailRowHeight;
masterNode.detailNode = detailNode;
return detailNode;
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/listeners/filterListener.ts
var import_ag_grid_community196 = require("ag-grid-community");
var FilterListener = class extends import_ag_grid_community196.BeanStub {
constructor() {
super(...arguments);
this.beanName = "ssrmFilterListener";
}
wireBeans(beans) {
this.serverSideRowModel = beans.rowModel;
this.filterManager = beans.filterManager;
this.listenerUtils = beans.ssrmListenerUtils;
}
postConstruct() {
if (!(0, import_ag_grid_community196._isServerSideRowModel)(this.gos)) {
return;
}
this.addManagedEventListeners({
advancedFilterEnabledChanged: () => this.onFilterChanged(true),
filterChanged: () => this.onFilterChanged()
});
}
onFilterChanged(advancedFilterEnabledChanged) {
const storeParams = this.serverSideRowModel.getParams();
if (!storeParams) {
return;
}
const oldModel = storeParams.filterModel;
let newModel;
let changedColumns;
if (this.filterManager?.isAdvFilterEnabled()) {
newModel = this.filterManager.getAdvFilterModel();
const oldColumns = advancedFilterEnabledChanged ? Object.keys(oldModel ?? {}) : this.getAdvancedFilterColumns(oldModel);
const newColumns = this.getAdvancedFilterColumns(newModel);
oldColumns.forEach((column) => newColumns.add(column));
changedColumns = Array.from(newColumns);
} else {
newModel = this.filterManager?.getFilterModel() ?? {};
if (advancedFilterEnabledChanged) {
const oldColumns = this.getAdvancedFilterColumns(oldModel);
Object.keys(newModel).forEach((column) => oldColumns.add(column));
changedColumns = Array.from(oldColumns);
} else {
changedColumns = this.findChangedColumns(oldModel, newModel);
}
}
const valueColChanged = this.listenerUtils.isSortingWithValueColumn(changedColumns);
const secondaryColChanged = this.listenerUtils.isSortingWithSecondaryColumn(changedColumns);
const params = {
valueColChanged,
secondaryColChanged,
changedColumns
};
this.serverSideRowModel.refreshAfterFilter(newModel, params);
}
findChangedColumns(oldModel, newModel) {
const allColKeysMap = {};
Object.keys(oldModel).forEach((key) => allColKeysMap[key] = true);
Object.keys(newModel).forEach((key) => allColKeysMap[key] = true);
const res = [];
Object.keys(allColKeysMap).forEach((key) => {
const oldJson = JSON.stringify(oldModel[key]);
const newJson = JSON.stringify(newModel[key]);
const filterChanged = oldJson != newJson;
if (filterChanged) {
res.push(key);
}
});
return res;
}
getAdvancedFilterColumns(model) {
const columns = /* @__PURE__ */ new Set();
if (!model) {
return columns;
}
const processAdvancedFilterModel = (filterModel) => {
if (filterModel.filterType === "join") {
filterModel.conditions.forEach((condition) => processAdvancedFilterModel(condition));
} else {
columns.add(filterModel.colId);
}
};
processAdvancedFilterModel(model);
return columns;
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/listeners/listenerUtils.ts
var import_ag_grid_community197 = require("ag-grid-community");
var ListenerUtils = class extends import_ag_grid_community197.BeanStub {
constructor() {
super(...arguments);
this.beanName = "ssrmListenerUtils";
}
wireBeans(beans) {
this.pivotResultCols = beans.pivotResultCols;
this.valueColsSvc = beans.valueColsSvc;
}
isSortingWithValueColumn(changedColumnsInSort) {
const valueColIds = (this.valueColsSvc?.columns ?? []).map((col) => col.getColId());
for (let i = 0; i < changedColumnsInSort.length; i++) {
if (valueColIds.indexOf(changedColumnsInSort[i]) > -1) {
return true;
}
}
return false;
}
isSortingWithSecondaryColumn(changedColumnsInSort) {
const pivotResultCols = this.pivotResultCols?.getPivotResultCols();
if (!pivotResultCols) {
return false;
}
const secondaryColIds = pivotResultCols.list.map((col) => col.getColId());
for (let i = 0; i < changedColumnsInSort.length; i++) {
if (secondaryColIds.indexOf(changedColumnsInSort[i]) > -1) {
return true;
}
}
return false;
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/listeners/sortListener.ts
var import_ag_grid_community198 = require("ag-grid-community");
var SortListener = class extends import_ag_grid_community198.BeanStub {
constructor() {
super(...arguments);
this.beanName = "ssrmSortSvc";
}
wireBeans(beans) {
this.sortSvc = beans.sortSvc;
this.serverSideRowModel = beans.rowModel;
this.listenerUtils = beans.ssrmListenerUtils;
}
postConstruct() {
if (!(0, import_ag_grid_community198._isServerSideRowModel)(this.gos)) {
return;
}
this.addManagedEventListeners({ sortChanged: this.onSortChanged.bind(this) });
}
onSortChanged() {
const storeParams = this.serverSideRowModel.getParams();
if (!storeParams) {
return;
}
const newSortModel = this.sortSvc.getSortModel();
const oldSortModel = storeParams.sortModel;
const changedColumns = this.findChangedColumnsInSort(newSortModel, oldSortModel);
const valueColChanged = this.listenerUtils.isSortingWithValueColumn(changedColumns);
const secondaryColChanged = this.listenerUtils.isSortingWithSecondaryColumn(changedColumns);
const params = {
valueColChanged,
secondaryColChanged,
changedColumns
};
this.serverSideRowModel.refreshAfterSort(newSortModel, params);
}
// returns back all the cols that were effected by the sorting. eg if we were sorting by col A,
// and now we are sorting by col B, the list of impacted cols should be A and B. so if a cache
// is impacted by sorting on A or B then it needs to be refreshed. this includes where the cache
// was previously sorted by A and then the A sort now needs to be cleared.
findChangedColumnsInSort(newSortModel, oldSortModel) {
let allColsInBothSorts = [];
[newSortModel, oldSortModel].forEach((sortModel) => {
if (sortModel) {
const ids = sortModel.map((sm) => sm.colId);
allColsInBothSorts = allColsInBothSorts.concat(ids);
}
});
const differentSorts = (oldSortItem, newSortItem) => {
const oldSort = oldSortItem ? oldSortItem.sort : null;
const newSort = newSortItem ? newSortItem.sort : null;
return oldSort !== newSort;
};
const differentIndexes = (oldSortItem, newSortItem) => {
const oldIndex = oldSortItem ? oldSortModel.indexOf(oldSortItem) : -1;
const newIndex = newSortItem ? newSortModel.indexOf(newSortItem) : -1;
return oldIndex !== newIndex;
};
return allColsInBothSorts.filter((colId) => {
const oldSortItem = oldSortModel.find((sm) => sm.colId === colId);
const newSortItem = newSortModel.find((sm) => sm.colId === colId);
return differentSorts(oldSortItem, newSortItem) || differentIndexes(oldSortItem, newSortItem);
});
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/nodeManager.ts
var import_ag_grid_community199 = require("ag-grid-community");
var NodeManager = class extends import_ag_grid_community199.BeanStub {
constructor() {
super(...arguments);
this.beanName = "ssrmNodeManager";
this.rowNodes = /* @__PURE__ */ new Map();
}
addRowNode(rowNode) {
const id = rowNode.id;
if (this.rowNodes.has(id)) {
(0, import_ag_grid_community199._warn)(187, {
rowId: id,
firstData: this.rowNodes.get(id).data,
secondData: rowNode.data
});
}
this.rowNodes.set(id, rowNode);
}
removeNode(rowNode) {
const id = rowNode.id;
this.rowNodes.delete(id);
}
destroy() {
this.clear();
super.destroy();
}
clear() {
this.rowNodes.clear();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/serverSideRowModel.ts
var import_ag_grid_community200 = require("ag-grid-community");
var ServerSideRowModel = class extends import_ag_grid_community200.BeanStub {
constructor() {
super(...arguments);
this.beanName = "rowModel";
this.pauseStoreUpdateListening = false;
this.started = false;
this.managingPivotResultColumns = false;
this.onRowHeightChanged_debounced = (0, import_ag_grid_community200._debounce)(this, this.onRowHeightChanged.bind(this), 100);
}
wireBeans(beans) {
this.colModel = beans.colModel;
this.colNames = beans.colNames;
this.pivotResultCols = beans.pivotResultCols;
this.rowGroupColsSvc = beans.rowGroupColsSvc;
this.pivotColsSvc = beans.pivotColsSvc;
this.valueColsSvc = beans.valueColsSvc;
this.filterManager = beans.filterManager;
this.sortSvc = beans.sortSvc;
this.rowRenderer = beans.rowRenderer;
this.nodeManager = beans.ssrmNodeManager;
this.storeFactory = beans.ssrmStoreFactory;
this.pivotColDefSvc = beans.pivotColDefSvc;
}
// we don't implement as lazy row heights is not supported in this row model
ensureRowHeightsValid() {
return false;
}
start() {
this.started = true;
this.updateDatasource();
}
destroyDatasource() {
if (!this.datasource) {
return;
}
if (this.datasource.destroy) {
this.datasource.destroy();
}
this.rowRenderer.datasourceChanged();
this.datasource = void 0;
}
postConstruct() {
const resetListener = this.resetRootStore.bind(this);
this.addManagedEventListeners({
newColumnsLoaded: this.onColumnEverything.bind(this),
storeUpdated: this.onStoreUpdated.bind(this),
columnValueChanged: resetListener,
columnPivotChanged: resetListener,
columnRowGroupChanged: resetListener,
columnPivotModeChanged: resetListener
});
this.addManagedPropertyListeners(
[
/**
* Following properties omitted as they are likely to come with undesired side effects.
* 'getRowId', 'isRowMaster', 'getRowHeight', 'isServerSideGroup', 'getServerSideGroupKey',
* */
"masterDetail",
"treeData",
"removePivotHeaderRowWhenSingleValueColumn",
"cacheBlockSize"
],
resetListener
);
this.addManagedPropertyListeners(["groupAllowUnbalanced", "groupTotalRow"], () => this.onStoreUpdated());
this.addManagedPropertyListener("rowHeight", () => this.resetRowHeights());
this.verifyProps();
this.addManagedPropertyListener("serverSideDatasource", () => this.updateDatasource());
}
updateDatasource() {
const datasource = this.gos.get("serverSideDatasource");
if (datasource) {
this.setDatasource(datasource);
}
}
verifyProps() {
if ((0, import_ag_grid_community200._isRowSelection)(this.gos) && !this.gos.exists("getRowId")) {
(0, import_ag_grid_community200._warn)(188);
}
}
setDatasource(datasource) {
if (!this.started) {
return;
}
this.destroyDatasource();
this.datasource = datasource;
this.resetRootStore();
}
applyRowData(rowDataParams, startRow, route) {
const rootStore = this.getRootStore();
if (!rootStore) {
return;
}
const storeToExecuteOn = rootStore.getChildStore(route);
if (!storeToExecuteOn) {
return;
}
storeToExecuteOn.applyRowData(rowDataParams, startRow, rowDataParams.rowData.length);
}
isLastRowIndexKnown() {
const cache = this.getRootStore();
if (!cache) {
return false;
}
return cache.isLastRowIndexKnown();
}
onColumnEverything() {
if (!this.storeParams) {
this.resetRootStore();
return;
}
const rowGroupColumnVos = this.columnsToValueObjects(this.rowGroupColsSvc?.columns);
const valueColumnVos = this.columnsToValueObjects(this.valueColsSvc?.columns);
const pivotColumnVos = this.columnsToValueObjects(this.pivotColsSvc?.columns);
const areColsSame = (params) => {
const oldColsMap = {};
params.oldCols.forEach((col) => oldColsMap[col.id] = col);
const allColsUnchanged = params.newCols.every((col) => {
const equivalentCol = oldColsMap[col.id];
if (equivalentCol) {
delete oldColsMap[col.id];
}
return equivalentCol && equivalentCol.field === col.field && equivalentCol.aggFunc === col.aggFunc;
});
const missingCols = !params.allowRemovedColumns && !!Object.values(oldColsMap).length;
return allColsUnchanged && !missingCols;
};
const sortModelDifferent = !(0, import_ag_grid_community200._jsonEquals)(this.storeParams.sortModel, this.sortSvc?.getSortModel() ?? []);
const rowGroupDifferent = !areColsSame({
oldCols: this.storeParams.rowGroupCols,
newCols: rowGroupColumnVos
});
const pivotDifferent = !areColsSame({
oldCols: this.storeParams.pivotCols,
newCols: pivotColumnVos
});
const valuesDifferent = !!rowGroupColumnVos?.length && !areColsSame({
oldCols: this.storeParams.valueCols,
newCols: valueColumnVos,
allowRemovedColumns: true
});
const resetRequired = sortModelDifferent || rowGroupDifferent || pivotDifferent || valuesDifferent;
if (resetRequired) {
this.resetRootStore();
} else {
const newParams = this.createStoreParams();
this.storeParams.rowGroupCols = newParams.rowGroupCols;
this.storeParams.pivotCols = newParams.pivotCols;
this.storeParams.valueCols = newParams.valueCols;
}
}
destroyRootStore() {
if (!this.rootNode || !this.rootNode.childStore) {
return;
}
this.rootNode.childStore = this.destroyBean(this.rootNode.childStore);
this.nodeManager.clear();
}
refreshAfterSort(newSortModel, params) {
if (this.storeParams) {
this.storeParams.sortModel = newSortModel;
}
const rootStore = this.getRootStore();
if (!rootStore) {
return;
}
rootStore.refreshAfterSort(params);
this.onStoreUpdated();
}
generateSecondaryColumns(pivotFields) {
if (!this.pivotColDefSvc) {
this.gos.assertModuleRegistered("SharedPivot", 2);
return;
}
const pivotColumnGroupDefs = this.pivotColDefSvc.createColDefsFromFields(pivotFields);
this.managingPivotResultColumns = true;
this.pivotResultCols?.setPivotResultCols(pivotColumnGroupDefs, "rowModelUpdated");
}
resetRowHeights() {
const atLeastOne = this.resetRowHeightsForAllRowNodes();
const rootNodeHeight = (0, import_ag_grid_community200._getRowHeightForNode)(this.beans, this.rootNode);
this.rootNode.setRowHeight(rootNodeHeight.height, rootNodeHeight.estimated);
if (this.rootNode.sibling) {
const rootNodeSibling = (0, import_ag_grid_community200._getRowHeightForNode)(this.beans, this.rootNode.sibling);
this.rootNode.sibling.setRowHeight(rootNodeSibling.height, rootNodeSibling.estimated);
}
if (atLeastOne) {
this.onRowHeightChanged();
}
}
resetRowHeightsForAllRowNodes() {
let atLeastOne = false;
this.forEachNode((rowNode) => {
const rowHeightForNode = (0, import_ag_grid_community200._getRowHeightForNode)(this.beans, rowNode);
rowNode.setRowHeight(rowHeightForNode.height, rowHeightForNode.estimated);
const detailNode = rowNode.detailNode;
if (detailNode) {
const detailRowHeight = (0, import_ag_grid_community200._getRowHeightForNode)(this.beans, detailNode);
detailNode.setRowHeight(detailRowHeight.height, detailRowHeight.estimated);
}
if (rowNode.sibling) {
const siblingRowHeight = (0, import_ag_grid_community200._getRowHeightForNode)(this.beans, rowNode.sibling);
detailNode?.setRowHeight(siblingRowHeight.height, siblingRowHeight.estimated);
}
atLeastOne = true;
});
return atLeastOne;
}
resetRootStore() {
this.destroyRootStore();
this.rootNode = new import_ag_grid_community200.RowNode(this.beans);
this.rootNode.group = true;
this.rootNode.level = -1;
if (this.datasource) {
this.storeParams = this.createStoreParams();
this.rootNode.childStore = this.createBean(this.storeFactory.createStore(this.storeParams, this.rootNode));
this.updateRowIndexesAndBounds();
}
if (this.managingPivotResultColumns) {
this.pivotResultCols?.setPivotResultCols(null, "api");
this.managingPivotResultColumns = false;
}
this.dispatchModelUpdated(true);
}
columnsToValueObjects(columns = []) {
return columns.map(
(col) => ({
id: col.getId(),
aggFunc: col.getAggFunc(),
displayName: this.colNames.getDisplayNameForColumn(col, "model"),
field: col.getColDef().field
})
);
}
createStoreParams() {
const rowGroupColumnVos = this.columnsToValueObjects(this.rowGroupColsSvc?.columns);
const valueColumnVos = this.columnsToValueObjects(this.valueColsSvc?.columns);
const pivotColumnVos = this.columnsToValueObjects(this.pivotColsSvc?.columns);
const dynamicRowHeight = (0, import_ag_grid_community200._isGetRowHeightFunction)(this.gos);
const params = {
// the columns the user has grouped and aggregated by
valueCols: valueColumnVos,
rowGroupCols: rowGroupColumnVos,
pivotCols: pivotColumnVos,
pivotMode: this.colModel.isPivotMode(),
// sort and filter model
filterModel: this.filterManager?.isAdvFilterEnabled() ? this.filterManager?.getAdvFilterModel() : this.filterManager?.getFilterModel() ?? {},
sortModel: this.sortSvc?.getSortModel() ?? [],
datasource: this.datasource,
lastAccessedSequence: { value: 0 },
// blockSize: blockSize == null ? 100 : blockSize,
dynamicRowHeight
};
return params;
}
getParams() {
return this.storeParams;
}
dispatchModelUpdated(reset = false) {
this.eventSvc.dispatchEvent({
type: "modelUpdated",
animate: !reset,
keepRenderedRows: !reset,
newPage: false,
newData: false
});
}
onStoreUpdated() {
if (this.pauseStoreUpdateListening) {
return;
}
this.updateRowIndexesAndBounds();
this.dispatchModelUpdated();
}
onRowHeightChanged() {
this.updateRowIndexesAndBounds();
this.dispatchModelUpdated();
}
updateRowIndexesAndBounds() {
const rootStore = this.getRootStore();
if (!rootStore) {
return;
}
rootStore.setDisplayIndexes({ value: 0 }, { value: 0 }, 0);
}
retryLoads() {
const rootStore = this.getRootStore();
if (!rootStore) {
return;
}
rootStore.retryLoads();
this.onStoreUpdated();
}
getRow(index) {
const rootStore = this.getRootStore();
if (!rootStore) {
return void 0;
}
return rootStore.getRowUsingDisplayIndex(index);
}
/**
* Pauses the store, to prevent it updating the UI. This is used when doing batch updates to the store.
*/
setPaused(paused) {
this.pauseStoreUpdateListening = paused;
}
expandAll(value) {
this.pauseStoreUpdateListening = true;
this.forEachNode((node) => {
if (node.stub) {
return;
}
if (node.hasChildren()) {
node.setExpanded(value);
}
});
this.pauseStoreUpdateListening = false;
this.onStoreUpdated();
}
refreshAfterFilter(newFilterModel, params) {
if (this.storeParams) {
this.storeParams.filterModel = newFilterModel;
}
const rootStore = this.getRootStore();
if (!rootStore) {
return;
}
rootStore.refreshAfterFilter(params);
this.onStoreUpdated();
}
getRootStore() {
return this.rootNode?.childStore;
}
getRowCount() {
const rootStore = this.getRootStore();
if (!rootStore) {
return 0;
}
return rootStore.getDisplayIndexEnd();
}
getTopLevelRowCount() {
const rootStore = this.getRootStore();
if (!rootStore) {
return 1;
}
return rootStore.getRowCount();
}
getTopLevelRowDisplayedIndex(topLevelIndex) {
const rootStore = this.getRootStore();
if (!rootStore) {
return topLevelIndex;
}
return rootStore.getTopLevelRowDisplayedIndex(topLevelIndex);
}
getRowBounds(index) {
const rootStore = this.getRootStore();
if (!rootStore) {
const rowHeight = (0, import_ag_grid_community200._getRowHeightAsNumber)(this.beans);
return {
rowTop: 0,
rowHeight
};
}
return rootStore.getRowBounds(index);
}
getBlockStates() {
const root = this.getRootStore();
if (!root) {
return void 0;
}
const states = {};
root.forEachStoreDeep((store) => {
const blockStates = store.getBlockStates();
for (const block of Object.keys(blockStates)) {
states[block] = blockStates[block];
}
});
return states;
}
getRowIndexAtPixel(pixel) {
const rootStore = this.getRootStore();
if (pixel <= 0 || !rootStore) {
return 0;
}
return rootStore.getRowIndexAtPixel(pixel);
}
isEmpty() {
return false;
}
isRowsToRender() {
return this.getRootStore() != null && this.getRowCount() > 0;
}
getType() {
return "serverSide";
}
forEachNode(callback) {
const rootStore = this.getRootStore();
if (!rootStore) {
return;
}
rootStore.forEachNodeDeep(callback);
}
forEachDisplayedNode(callback) {
const wrappedCallback = (node, index) => {
if (node.stub || !node.displayed) {
return;
}
callback(node, index);
};
this.forEachNode(wrappedCallback);
}
forEachNodeAfterFilterAndSort(callback, includeFooterNodes = false) {
const rootStore = this.getRootStore();
if (!rootStore) {
return;
}
rootStore.forEachNodeDeepAfterFilterAndSort(callback, void 0, includeFooterNodes);
}
/** @returns false if store hasn't started */
executeOnStore(route, callback) {
if (!this.started) {
return false;
}
const rootStore = this.getRootStore();
if (!rootStore) {
return true;
}
const storeToExecuteOn = rootStore.getChildStore(route);
if (storeToExecuteOn) {
callback(storeToExecuteOn);
}
return true;
}
refreshStore(params = {}) {
const route = params.route ? params.route : [];
this.executeOnStore(route, (store) => store.refreshStore(params.purge == true));
}
getStoreState() {
const res = [];
const rootStore = this.getRootStore();
if (rootStore) {
rootStore.addStoreStates(res);
}
return res;
}
getNodesInRangeForSelection(firstInRange, lastInRange) {
const startIndex = firstInRange.rowIndex;
const endIndex = lastInRange.rowIndex;
if (startIndex === null && endIndex === null) {
return [];
}
if (endIndex === null) {
return firstInRange ? [firstInRange] : [];
}
if (startIndex === null) {
return [lastInRange];
}
const nodeRange = [];
const [firstIndex, lastIndex] = [startIndex, endIndex].sort((a, b) => a - b);
this.forEachNode((node) => {
const thisRowIndex = node.rowIndex;
if (thisRowIndex == null || node.stub) {
return;
}
if (thisRowIndex >= firstIndex && thisRowIndex <= lastIndex) {
nodeRange.push(node);
}
});
if (nodeRange.length !== lastIndex - firstIndex + 1) {
return null;
}
return nodeRange;
}
getRowNode(id) {
let result;
this.forEachNode((rowNode) => {
if (rowNode.id === id) {
result = rowNode;
}
if (rowNode.detailNode && rowNode.detailNode.id === id) {
result = rowNode.detailNode;
}
});
return result;
}
isRowPresent(rowNode) {
const foundRowNode = this.getRowNode(rowNode.id);
return !!foundRowNode;
}
setRowCount(rowCount, lastRowIndexKnown) {
const rootStore = this.getRootStore();
if (!rootStore) {
return;
}
rootStore.setRowCount(rowCount, lastRowIndexKnown);
}
destroy() {
this.destroyDatasource();
this.destroyRootStore();
super.destroy();
}
/**
* @deprecated v33.1
*/
onRowHeightChangedDebounced() {
this.onRowHeightChanged_debounced();
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/serverSideRowModelApi.ts
var import_ag_grid_community201 = require("ag-grid-community");
function getServerSideSelectionState(beans) {
return beans.selectionSvc?.getSelectionState() ?? null;
}
function setServerSideSelectionState(beans, state) {
beans.selectionSvc?.setSelectionState(state, "api");
}
function applyServerSideTransaction(beans, transaction) {
return beans.ssrmTxnManager?.applyTransaction(transaction);
}
function applyServerSideRowData(beans, params) {
const startRow = params.startRow ?? 0;
const route = params.route ?? [];
if (startRow < 0) {
(0, import_ag_grid_community201._warn)(189, { startRow });
return;
}
(0, import_ag_grid_community201._getServerSideRowModel)(beans)?.applyRowData(params.successParams, startRow, route);
}
function applyServerSideTransactionAsync(beans, transaction, callback) {
return beans.ssrmTxnManager?.applyTransactionAsync(transaction, callback);
}
function retryServerSideLoads(beans) {
(0, import_ag_grid_community201._getServerSideRowModel)(beans)?.retryLoads();
}
function flushServerSideAsyncTransactions(beans) {
return beans.ssrmTxnManager?.flushAsyncTransactions();
}
function refreshServerSide(beans, params) {
(0, import_ag_grid_community201._getServerSideRowModel)(beans)?.refreshStore(params);
}
function getServerSideGroupLevelState(beans) {
return (0, import_ag_grid_community201._getServerSideRowModel)(beans)?.getStoreState() ?? [];
}
// packages/ag-grid-enterprise/src/serverSideRowModel/services/serverSideExpansionService.ts
var ServerSideExpansionService = class extends BaseExpansionService {
constructor() {
super(...arguments);
this.beanName = "expansionSvc";
this.queuedRowIds = /* @__PURE__ */ new Set();
}
wireBeans(beans) {
this.serverSideRowModel = beans.rowModel;
}
postConstruct() {
this.addManagedEventListeners({
columnRowGroupChanged: () => {
this.queuedRowIds.clear();
}
});
}
checkOpenByDefault(rowNode) {
if (!rowNode.isExpandable()) {
return;
}
if (this.queuedRowIds.has(rowNode.id)) {
this.queuedRowIds.delete(rowNode.id);
rowNode.setExpanded(true);
return;
}
const userFunc = this.gos.getCallback("isServerSideGroupOpenByDefault");
if (!userFunc) {
return;
}
const params = {
data: rowNode.data,
rowNode
};
const userFuncRes = userFunc(params);
if (userFuncRes) {
rowNode.setExpanded(true);
}
}
expandRows(rowIdsToExpand, rowIdsToCollapse) {
const { serverSideRowModel, queuedRowIds } = this;
const processNodes = (rowIds, expanded) => {
for (const rowId of rowIds) {
const rowNode = serverSideRowModel.getRowNode(rowId);
if (rowNode) {
rowNode.setExpanded(expanded);
} else {
if (expanded) {
queuedRowIds.add(rowId);
} else {
queuedRowIds.delete(rowId);
}
}
}
};
processNodes(rowIdsToExpand, true);
if (!rowIdsToCollapse) {
return;
}
processNodes(rowIdsToCollapse, false);
}
expandAll(value) {
this.serverSideRowModel.expandAll(value);
this.beans.eventSvc.dispatchEvent({
type: "expandOrCollapseAll",
source: value ? "expandAll" : "collapseAll"
});
}
onGroupExpandedOrCollapsed() {
}
dispatchExpandedEvent(event) {
this.eventSvc.dispatchEvent(event);
this.beans.rowRenderer.refreshCells({ rowNodes: [event.node] });
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/services/serverSideSelectionService.ts
var import_ag_grid_community204 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/serverSideRowModel/services/selection/strategies/defaultStrategy.ts
var import_ag_grid_community202 = require("ag-grid-community");
var DefaultStrategy = class extends import_ag_grid_community202.BeanStub {
constructor(selectionCtx) {
super();
this.selectionCtx = selectionCtx;
this.selectedState = { selectAll: false, toggledNodes: /* @__PURE__ */ new Set() };
/**
* Whether select-all functionality has ever been used. Used only to print warnings in `getSelectedNodes` for users.
* We print a warning even if not currently selecting all because we want users to be aware of the potential
* for unexpected behaviour when these two features are used together.
*/
this.selectAllUsed = false;
/** This is to prevent regressions, default selectionSvc retains reference of selected nodes. */
this.selectedNodes = {};
}
getSelectedState() {
return {
selectAll: this.selectedState.selectAll,
toggledNodes: [...this.selectedState.toggledNodes]
};
}
setSelectedState(state) {
if (typeof state !== "object") {
(0, import_ag_grid_community202._error)(116);
return;
}
if (!("selectAll" in state)) {
(0, import_ag_grid_community202._error)(116);
return;
}
if (typeof state.selectAll !== "boolean") {
(0, import_ag_grid_community202._error)(117);
return;
}
if (!("toggledNodes" in state) || !Array.isArray(state.toggledNodes)) {
return (0, import_ag_grid_community202._warn)(197);
}
const newState = {
selectAll: state.selectAll,
toggledNodes: /* @__PURE__ */ new Set()
};
state.toggledNodes.forEach((key) => {
if (typeof key === "string") {
newState.toggledNodes.add(key);
} else {
(0, import_ag_grid_community202._warn)(196, { key });
}
});
const isSelectingMultipleRows = newState.selectAll || newState.toggledNodes.size > 1;
if ((0, import_ag_grid_community202._isUsingNewRowSelectionAPI)(this.gos) && !(0, import_ag_grid_community202._isMultiRowSelection)(this.gos) && isSelectingMultipleRows) {
(0, import_ag_grid_community202._warn)(130);
return;
}
this.selectedState = newState;
}
deleteSelectionStateFromParent(parentPath, removedNodeIds) {
if (this.selectedState.toggledNodes.size === 0) {
return false;
}
let anyNodesToggled = false;
removedNodeIds.forEach((id) => {
if (this.selectedState.toggledNodes.delete(id)) {
anyNodesToggled = true;
}
});
return anyNodesToggled;
}
setNodesSelected(params) {
const { nodes, clearSelection, newValue, source } = params;
if (nodes.length === 0)
return 0;
const onlyThisNode = clearSelection && newValue;
if (!(0, import_ag_grid_community202._isMultiRowSelection)(this.gos) || onlyThisNode) {
if (nodes.length > 1) {
(0, import_ag_grid_community202._error)(130);
return 0;
}
const rowNode = nodes[0];
const node = rowNode.footer ? rowNode.sibling : rowNode;
if (newValue && node.selectable) {
this.selectedNodes = { [node.id]: node };
this.selectedState = {
selectAll: false,
toggledNodes: /* @__PURE__ */ new Set([node.id])
};
} else {
this.selectedNodes = {};
this.selectedState = {
selectAll: false,
toggledNodes: /* @__PURE__ */ new Set()
};
}
return 1;
}
const updateNodeState = (rowNode, value = newValue) => {
const node = rowNode.footer ? rowNode.sibling : rowNode;
if (value && node.selectable) {
this.selectedNodes[node.id] = node;
} else {
delete this.selectedNodes[node.id];
}
const doesNodeConform = value === this.selectedState.selectAll;
if (doesNodeConform || !node.selectable) {
this.selectedState.toggledNodes.delete(node.id);
} else {
this.selectedState.toggledNodes.add(node.id);
}
};
nodes.forEach((node) => updateNodeState(node));
if (nodes.length === 1 && source === "api") {
this.selectionCtx.setRoot(nodes[0].footer ? nodes[0].sibling : nodes[0]);
}
return 1;
}
processNewRow(node) {
if (this.selectedNodes[node.id]) {
this.selectedNodes[node.id] = node;
}
}
isNodeSelected(node) {
const isToggled = this.selectedState.toggledNodes.has(node.id);
return this.selectedState.selectAll ? !isToggled : isToggled;
}
getSelectedNodes(nullWhenSelectAll = false, warnWhenSelectAll = true) {
const {
selectedState: { selectAll },
selectedNodes,
selectAllUsed
} = this;
if (warnWhenSelectAll && selectAllUsed) {
(0, import_ag_grid_community202._warn)(199);
}
return nullWhenSelectAll && selectAll ? null : Object.values(selectedNodes);
}
getSelectedRows() {
return (this.getSelectedNodes() ?? []).map((node) => node.data);
}
getSelectionCount() {
if (this.selectedState.selectAll) {
return -1;
}
return this.selectedState.toggledNodes.size;
}
isEmpty() {
return !this.selectedState.selectAll && !this.selectedState.toggledNodes?.size;
}
selectAllRowNodes() {
this.reset(true);
}
deselectAllRowNodes() {
this.reset(false);
}
reset(selectAll) {
this.selectedState = { selectAll, toggledNodes: /* @__PURE__ */ new Set() };
this.selectedNodes = {};
this.selectAllUsed || (this.selectAllUsed = selectAll);
}
getSelectAllState() {
if (this.selectedState.selectAll) {
if (this.selectedState.toggledNodes.size > 0) {
return null;
}
return true;
}
if (this.selectedState.toggledNodes.size > 0) {
return null;
}
return false;
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/services/selection/strategies/groupSelectsChildrenStrategy.ts
var import_ag_grid_community203 = require("ag-grid-community");
var GroupSelectsChildrenStrategy = class extends import_ag_grid_community203.BeanStub {
constructor(selectionCtx) {
super();
this.selectionCtx = selectionCtx;
this.selectedState = { selectAllChildren: false, toggledNodes: /* @__PURE__ */ new Map() };
}
wireBeans(beans) {
this.rowModel = beans.rowModel;
this.rowGroupColsSvc = beans.rowGroupColsSvc;
this.filterManager = beans.filterManager;
this.selectionSvc = beans.selectionSvc;
}
postConstruct() {
this.addManagedEventListeners({
// if model has updated, a store may now be fully loaded to clean up indeterminate states
modelUpdated: () => this.removeRedundantState(),
// when the grouping changes, the state no longer makes sense, so reset the state.
columnRowGroupChanged: () => this.selectionSvc.reset("rowGroupChanged")
});
}
getSelectedState() {
const { gos, rowGroupColsSvc, selectedState } = this;
const treeData = gos.get("treeData");
const recursivelySerializeState = (state, level, nodeId) => {
const normalisedState = {
nodeId
};
if (treeData || rowGroupColsSvc && level <= rowGroupColsSvc.columns.length) {
normalisedState.selectAllChildren = state.selectAllChildren;
}
if (state.toggledNodes.size) {
const toggledNodes = [];
state.toggledNodes.forEach((value, key) => {
const newState = recursivelySerializeState(value, level + 1, key);
toggledNodes.push(newState);
});
normalisedState.toggledNodes = toggledNodes;
}
return normalisedState;
};
return recursivelySerializeState(selectedState, 0);
}
setSelectedState(state) {
if ("selectAll" in state) {
(0, import_ag_grid_community203._error)(111);
return;
}
const recursivelyDeserializeState = (normalisedState, parentSelected) => {
if (typeof normalisedState !== "object") {
(0, import_ag_grid_community203._error)(243);
throw new Error();
}
if ("selectAllChildren" in normalisedState && typeof normalisedState.selectAllChildren !== "boolean") {
(0, import_ag_grid_community203._error)(244);
throw new Error();
}
if ("toggledNodes" in normalisedState) {
if (!Array.isArray(normalisedState.toggledNodes)) {
(0, import_ag_grid_community203._error)(245);
throw new Error();
}
const allHaveIds = normalisedState.toggledNodes.every(
(innerState) => typeof innerState === "object" && "nodeId" in innerState && typeof innerState.nodeId === "string"
);
if (!allHaveIds) {
(0, import_ag_grid_community203._error)(246);
throw new Error();
}
}
const isThisNodeSelected = normalisedState.selectAllChildren ?? !parentSelected;
const convertedChildren = normalisedState.toggledNodes?.map((innerState) => [
innerState.nodeId,
recursivelyDeserializeState(innerState, isThisNodeSelected)
]);
const doesRedundantStateExist = convertedChildren?.some(
([, innerState]) => isThisNodeSelected === innerState.selectAllChildren && innerState.toggledNodes.size === 0
);
if (doesRedundantStateExist) {
(0, import_ag_grid_community203._error)(247);
throw new Error();
}
return {
selectAllChildren: isThisNodeSelected,
toggledNodes: new Map(convertedChildren)
};
};
try {
this.selectedState = recursivelyDeserializeState(state, !!state.selectAllChildren);
} catch (e) {
}
}
deleteSelectionStateFromParent(parentRoute, removedNodeIds) {
let parentState = this.selectedState;
const remainingRoute = [...parentRoute];
while (parentState && remainingRoute.length) {
parentState = parentState.toggledNodes.get(remainingRoute.pop());
}
if (!parentState) {
return false;
}
let anyStateChanged = false;
removedNodeIds.forEach((id) => {
if (parentState?.toggledNodes.delete(id)) {
anyStateChanged = true;
}
});
if (anyStateChanged) {
this.removeRedundantState();
}
return anyStateChanged;
}
setNodesSelected({ nodes, newValue, clearSelection, source }) {
if (nodes.length === 0)
return 0;
const onlyThisNode = clearSelection && newValue;
if (!(0, import_ag_grid_community203._isMultiRowSelection)(this.gos) || onlyThisNode) {
if (nodes.length > 1) {
(0, import_ag_grid_community203._error)(130);
return 0;
}
this.deselectAllRowNodes();
}
nodes.forEach((rowNode) => {
const node = rowNode.footer ? rowNode.sibling : rowNode;
const idPathToNode = this.getRouteToNode(node);
this.recursivelySelectNode(idPathToNode, this.selectedState, newValue);
});
this.removeRedundantState();
if (nodes.length === 1 && source === "api") {
this.selectionCtx.setRoot(nodes[0].footer ? nodes[0].sibling : nodes[0]);
}
return 1;
}
isNodeSelected(node) {
const path = this.getRouteToNode(node);
return this.isNodePathSelected(path, this.selectedState);
}
isNodePathSelected([nextNode, ...nodes], state) {
if (nodes.length === 0) {
const isToggled = state.toggledNodes.has(nextNode.id);
if (nextNode.hasChildren()) {
const groupState = state.toggledNodes.get(nextNode.id);
if (groupState && groupState.toggledNodes.size) {
return void 0;
}
}
return state.selectAllChildren ? !isToggled : isToggled;
}
if (state.toggledNodes.has(nextNode.id)) {
const nextState = state.toggledNodes.get(nextNode.id);
if (nextState) {
return this.isNodePathSelected(nodes, nextState);
}
}
return state.selectAllChildren;
}
getRouteToNode(node) {
const pathToNode = [];
let tempNode = node;
while (tempNode.parent) {
pathToNode.push(tempNode);
tempNode = tempNode.parent;
}
return pathToNode.reverse();
}
removeRedundantState() {
if (this.filterManager?.isAnyFilterPresent()) {
return;
}
const forEachNodeStateDepthFirst = (state = this.selectedState, thisKey, parentState) => {
state.toggledNodes.forEach((value, key) => {
forEachNodeStateDepthFirst(value, key, state);
});
if (thisKey) {
const thisRow = this.rowModel.getRowNode(thisKey);
const thisRowStore = thisRow?.childStore;
const isStoreSizeKnown = thisRowStore?.isLastRowIndexKnown();
if (isStoreSizeKnown) {
const possibleAllNodesToggled = state.toggledNodes.size >= thisRowStore.getRowCount();
if (possibleAllNodesToggled) {
for (const childState of state.toggledNodes.entries()) {
const [key, value] = childState;
if (value.toggledNodes.size > 0) {
return;
}
const rowDoesNotExist = !this.rowModel.getRowNode(key);
if (rowDoesNotExist) {
return;
}
}
state.selectAllChildren = !state.selectAllChildren;
state.toggledNodes.clear();
}
}
}
const hasNoToggledRows = state.toggledNodes.size === 0;
const isIdenticalToParent = parentState?.selectAllChildren === state.selectAllChildren;
if (hasNoToggledRows && isIdenticalToParent) {
parentState?.toggledNodes.delete(thisKey);
}
};
forEachNodeStateDepthFirst();
}
recursivelySelectNode([nextNode, ...nodes], selectedState, newValue) {
if (!nextNode) {
return;
}
const isLastNode = !nodes.length;
if (isLastNode) {
const isNodeSelectable = nextNode.selectable;
const doesNodeConform = selectedState.selectAllChildren === newValue;
if (doesNodeConform || !isNodeSelectable) {
selectedState.toggledNodes.delete(nextNode.id);
return;
}
const newState = {
selectAllChildren: newValue,
toggledNodes: /* @__PURE__ */ new Map()
};
selectedState.toggledNodes.set(nextNode.id, newState);
return;
}
const doesStateAlreadyExist = selectedState.toggledNodes.has(nextNode.id);
const childState = selectedState.toggledNodes.get(nextNode.id) ?? {
selectAllChildren: selectedState.selectAllChildren,
toggledNodes: /* @__PURE__ */ new Map()
};
if (!doesStateAlreadyExist) {
selectedState.toggledNodes.set(nextNode.id, childState);
}
this.recursivelySelectNode(nodes, childState, newValue);
if (selectedState.selectAllChildren === childState.selectAllChildren && childState.toggledNodes.size === 0) {
selectedState.toggledNodes.delete(nextNode.id);
}
}
getSelectedNodes(nullWhenSelectAll = false) {
(0, import_ag_grid_community203._warn)(202);
if (this.selectedState.selectAllChildren && nullWhenSelectAll) {
return null;
}
const selectedNodes = [];
this.rowModel.forEachNode((node) => {
if (node.isSelected()) {
selectedNodes.push(node);
}
});
return selectedNodes;
}
processNewRow() {
}
getSelectedRows() {
return this.getSelectedNodes()?.map((node) => node.data) ?? [];
}
getSelectionCount() {
return -1;
}
isEmpty() {
return !this.selectedState.selectAllChildren && !this.selectedState.toggledNodes?.size;
}
selectAllRowNodes() {
this.reset(true);
}
deselectAllRowNodes() {
this.reset(false);
}
reset(selectAllChildren2) {
this.selectedState = { selectAllChildren: selectAllChildren2, toggledNodes: /* @__PURE__ */ new Map() };
}
getSelectAllState() {
if (this.selectedState.selectAllChildren) {
if (this.selectedState.toggledNodes.size > 0) {
return null;
}
return true;
}
if (this.selectedState.toggledNodes.size > 0) {
return null;
}
return false;
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/services/serverSideSelectionService.ts
var ServerSideSelectionService = class extends import_ag_grid_community204.BaseSelectionService {
constructor() {
super(...arguments);
this.beanName = "selectionSvc";
}
postConstruct() {
super.postConstruct();
this.addManagedPropertyListeners(["groupSelectsChildren", "rowSelection"], () => {
const groupSelectsChildren2 = (0, import_ag_grid_community204._getGroupSelectsDescendants)(this.gos);
const Strategy2 = groupSelectsChildren2 && this.selectionStrategy instanceof DefaultStrategy ? GroupSelectsChildrenStrategy : !groupSelectsChildren2 && this.selectionStrategy instanceof GroupSelectsChildrenStrategy ? DefaultStrategy : void 0;
if (Strategy2) {
this.destroyBean(this.selectionStrategy);
this.selectionStrategy = this.createManagedBean(new Strategy2(this.selectionCtx));
this.shotgunResetNodeSelectionState();
this.dispatchSelectionChanged("api");
}
});
this.addManagedPropertyListeners(["rowSelection"], () => {
const rowSelection = (0, import_ag_grid_community204._getRowSelectionMode)(this.gos);
if (rowSelection !== this.selectionMode) {
this.selectionMode = rowSelection;
this.deselectAllRowNodes({ source: "api" });
}
});
this.selectionMode = (0, import_ag_grid_community204._getRowSelectionMode)(this.gos);
const groupSelectsChildren = (0, import_ag_grid_community204._getGroupSelectsDescendants)(this.gos);
const Strategy = !groupSelectsChildren ? DefaultStrategy : GroupSelectsChildrenStrategy;
this.selectionStrategy = this.createManagedBean(new Strategy(this.selectionCtx));
}
handleSelectionEvent(event, rowNode, source) {
if (this.isRowSelectionBlocked(rowNode))
return 0;
let updatedRows = 0;
const selection = this.inferNodeSelections(rowNode, event.shiftKey, event.metaKey || event.ctrlKey, source);
if (selection == null) {
return 0;
}
this.selectionCtx.selectAll = false;
if ("select" in selection) {
if (selection.reset) {
this.selectionStrategy.deselectAllRowNodes({ source: "api" });
} else {
this.selectionStrategy.setNodesSelected({ nodes: selection.deselect, newValue: false, source });
}
updatedRows = this.selectionStrategy.setNodesSelected({ nodes: selection.select, newValue: true, source });
} else {
updatedRows = this.selectionStrategy.setNodesSelected({
nodes: [selection.node],
newValue: selection.newValue,
clearSelection: selection.clearSelection,
event,
source
});
}
this.shotgunResetNodeSelectionState(source);
this.dispatchSelectionChanged(source);
return updatedRows;
}
getSelectionState() {
return this.selectionStrategy.getSelectedState();
}
setSelectionState(state, source) {
if (!(0, import_ag_grid_community204._isRowSelection)(this.gos)) {
if (state) {
(0, import_ag_grid_community204._warn)(132);
}
return;
}
if (Array.isArray(state)) {
return;
}
if (state) {
this.selectionStrategy.setSelectedState(state);
this.shotgunResetNodeSelectionState();
this.dispatchSelectionChanged(source);
} else {
this.deselectAllRowNodes({ source });
}
}
setNodesSelected(params) {
if (!(0, import_ag_grid_community204._isRowSelection)(this.gos) && params.newValue) {
(0, import_ag_grid_community204._warn)(132);
return 0;
}
const { nodes, ...otherParams } = params;
if (nodes.length > 1 && this.selectionMode !== "multiRow") {
(0, import_ag_grid_community204._warn)(130);
return 0;
}
const adjustedParams = {
nodes: nodes.filter((node) => node.selectable),
...otherParams
};
if (!adjustedParams.nodes.length) {
return 0;
}
const changedNodes = this.selectionStrategy.setNodesSelected(adjustedParams);
this.shotgunResetNodeSelectionState(adjustedParams.source);
this.dispatchSelectionChanged(adjustedParams.source);
return changedNodes;
}
/**
* Deletes the selection state for a set of nodes, for use after deleting nodes via
* transaction. As this is designed for transactions, all nodes should belong to the same group.
*/
deleteSelectionStateFromParent(storeRoute, removedNodeIds) {
const stateChanged = this.selectionStrategy.deleteSelectionStateFromParent(storeRoute, removedNodeIds);
if (!stateChanged) {
return;
}
this.shotgunResetNodeSelectionState();
this.dispatchSelectionChanged("api");
}
shotgunResetNodeSelectionState(source) {
this.beans.rowModel.forEachNode((node) => {
if (node.stub) {
return;
}
const isNodeSelected = this.selectionStrategy.isNodeSelected(node);
if (isNodeSelected !== node.isSelected()) {
this.selectRowNode(node, isNodeSelected, void 0, source);
}
});
}
getSelectedNodes() {
return this.selectionStrategy.getSelectedNodes() ?? [];
}
getSelectedRows() {
return this.selectionStrategy.getSelectedRows();
}
getSelectionCount() {
return this.selectionStrategy.getSelectionCount();
}
syncInRowNode(rowNode) {
this.selectionStrategy.processNewRow(rowNode);
const isNodeSelected = this.selectionStrategy.isNodeSelected(rowNode);
if (isNodeSelected != false && !rowNode.selectable) {
this.selectionStrategy.setNodesSelected({
nodes: [rowNode],
newValue: false,
source: "api"
});
this.shotgunResetNodeSelectionState();
this.dispatchSelectionChanged("api");
return;
}
rowNode.__selected = isNodeSelected;
}
reset() {
this.selectionStrategy.deselectAllRowNodes({ source: "api" });
this.selectionCtx.reset();
}
isEmpty() {
return this.selectionStrategy.isEmpty();
}
hasNodesToSelect() {
return true;
}
selectAllRowNodes(params) {
if (!(0, import_ag_grid_community204._isRowSelection)(this.gos)) {
(0, import_ag_grid_community204._warn)(132);
return;
}
validateSelectionParameters(params);
if ((0, import_ag_grid_community204._isUsingNewRowSelectionAPI)(this.gos) && !(0, import_ag_grid_community204._isMultiRowSelection)(this.gos)) {
return (0, import_ag_grid_community204._warn)(130);
}
this.selectionStrategy.selectAllRowNodes(params);
this.selectionCtx.selectAll = true;
this.beans.rowModel.forEachNode((node) => {
if (node.stub) {
return;
}
this.selectRowNode(node, true, void 0, params.source);
});
this.dispatchSelectionChanged(params.source);
}
deselectAllRowNodes(params) {
validateSelectionParameters(params);
this.selectionStrategy.deselectAllRowNodes(params);
this.selectionCtx.selectAll = false;
this.beans.rowModel.forEachNode((node) => {
if (node.stub) {
return;
}
this.selectRowNode(node, false, void 0, params.source);
});
this.dispatchSelectionChanged(params.source);
}
getSelectAllState(selectAll) {
return this.selectionStrategy.getSelectAllState(selectAll);
}
// used by CSRM
getBestCostNodeSelection() {
return (0, import_ag_grid_community204._warn)(194, { method: "getBestCostNodeSelection" });
}
/**
* Updates the selectable state for a node by invoking isRowSelectable callback.
* If the node is not selectable, it will be deselected.
*
* Callers:
* - property isRowSelectable changed
* - after grouping / treeData
*/
updateSelectable() {
if (!(0, import_ag_grid_community204._isRowSelection)(this.gos)) {
return;
}
const nodesToDeselect = [];
this.beans.rowModel.forEachNode((node) => {
const rowSelectable = this.updateRowSelectable(node, true);
if (!rowSelectable && node.isSelected()) {
nodesToDeselect.push(node);
}
});
if (nodesToDeselect.length) {
this.setNodesSelected({
nodes: nodesToDeselect,
newValue: false,
source: "selectableChanged"
});
}
}
dispatchSelectionChanged(source) {
this.eventSvc.dispatchEvent({
type: "selectionChanged",
source,
selectedNodes: this.selectionStrategy instanceof GroupSelectsChildrenStrategy ? null : this.selectionStrategy.getSelectedNodes(true, false),
serverSideState: this.getSelectionState()
});
}
updateSelectableAfterGrouping() {
return (0, import_ag_grid_community204._error)(194, { method: "updateSelectableAfterGrouping" });
}
refreshMasterNodeState() {
}
setDetailSelectionState() {
return;
}
};
function validateSelectionParameters({ selectAll }) {
if (selectAll === "filtered" || selectAll === "currentPage") {
(0, import_ag_grid_community204._warn)(195, { justCurrentPage: selectAll === "currentPage" });
}
}
// packages/ag-grid-enterprise/src/serverSideRowModel/services/ssrmRowChildrenService.ts
var import_ag_grid_community205 = require("ag-grid-community");
var SsrmRowChildrenService = class extends import_ag_grid_community205.BeanStub {
constructor() {
super(...arguments);
this.beanName = "rowChildrenSvc";
}
getHasChildrenValue(rowNode) {
const isTreeData = this.gos.get("treeData");
const isGroupFunc = this.gos.get("isServerSideGroup");
return !rowNode.stub && !rowNode.footer && (isTreeData ? !!isGroupFunc && isGroupFunc(rowNode.data) : !!rowNode.group);
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/stores/lazy/lazyBlockLoadingService.ts
var import_ag_grid_community206 = require("ag-grid-community");
var LazyBlockLoadingService = class extends import_ag_grid_community206.BeanStub {
constructor() {
super(...arguments);
this.beanName = "lazyBlockLoadingSvc";
this.outboundRequests = 0;
// a map of caches to loading nodes
this.cacheLoadingNodesMap = /* @__PURE__ */ new Map();
// if a check is queued to happen this cycle
this.isCheckQueued = false;
// this is cached for blockLoadDebounce
this.nextBlockToLoad = void 0;
}
wireBeans(beans) {
this.rowRenderer = beans.rowRenderer;
this.rowModel = beans.rowModel;
}
postConstruct() {
this.maxOutboundRequests = (0, import_ag_grid_community206._getMaxConcurrentDatasourceRequests)(this.gos);
}
subscribe(cache) {
this.cacheLoadingNodesMap.set(cache, /* @__PURE__ */ new Set());
}
unsubscribe(cache) {
this.cacheLoadingNodesMap.delete(cache);
}
/**
* Queues a microtask to check if any blocks need to be loaded.
*/
queueLoadCheck() {
if (this.isCheckQueued) {
return;
}
this.isCheckQueued = true;
setTimeout(() => {
this.queueLoadAction();
this.isCheckQueued = false;
});
}
onLoadComplete() {
this.outboundRequests -= 1;
this.queueLoadCheck();
}
hasAvailableLoadBandwidth() {
if (this.maxOutboundRequests === void 0) {
return true;
}
return this.outboundRequests < this.maxOutboundRequests;
}
queueLoadAction() {
const nextBlockToLoad = this.getBlockToLoad();
if (!nextBlockToLoad) {
return;
}
const isSameBlock = this.nextBlockToLoad && this.nextBlockToLoad.cache === nextBlockToLoad.cache && this.nextBlockToLoad.index === nextBlockToLoad.index;
if (isSameBlock) {
return;
}
if (!this.nextBlockToLoad || !isSameBlock) {
this.nextBlockToLoad = nextBlockToLoad;
window.clearTimeout(this.loaderTimeout);
const startRow = Number(this.nextBlockToLoad.index);
const cache = this.nextBlockToLoad.cache;
const endRow = nextBlockToLoad.index + nextBlockToLoad.cache.getBlockSize();
this.loaderTimeout = window.setTimeout(() => {
if (!cache.isAlive()) {
return;
}
this.loaderTimeout = void 0;
this.attemptLoad(cache, startRow, endRow);
this.nextBlockToLoad = void 0;
}, this.gos.get("blockLoadDebounceMillis"));
}
}
attemptLoad(cache, start, end) {
const hasBandwidth = this.hasAvailableLoadBandwidth();
if (!hasBandwidth) {
return;
}
this.executeLoad(cache, start, end);
this.queueLoadCheck();
}
executeLoad(cache, startRow, endRow) {
const ssrmParams = cache.getSsrmParams();
const request = {
startRow,
endRow,
rowGroupCols: ssrmParams.rowGroupCols,
valueCols: ssrmParams.valueCols,
pivotCols: ssrmParams.pivotCols,
pivotMode: ssrmParams.pivotMode,
groupKeys: cache.store.getParentNode().getRoute() ?? [],
filterModel: ssrmParams.filterModel,
sortModel: ssrmParams.sortModel
};
const loadingNodes = this.cacheLoadingNodesMap.get(cache);
const removeNodesFromLoadingMap = () => {
for (let i = 0; i < endRow - startRow; i++) {
loadingNodes.delete(startRow + i);
}
};
const addNodesToLoadingMap = () => {
for (let i = 0; i < endRow - startRow; i++) {
loadingNodes.add(startRow + i);
}
};
const success = (params2) => {
this.onLoadComplete();
cache.onLoadSuccess(startRow, endRow - startRow, params2);
removeNodesFromLoadingMap();
};
const fail = () => {
this.onLoadComplete();
cache.onLoadFailed(startRow, endRow - startRow);
removeNodesFromLoadingMap();
};
const params = (0, import_ag_grid_community206._addGridCommonParams)(this.gos, {
request,
success,
fail,
parentNode: cache.store.getParentNode()
});
addNodesToLoadingMap();
this.outboundRequests += 1;
cache.getSsrmParams().datasource?.getRows(params);
}
getBlockToLoad() {
const firstRowInViewport = this.rowRenderer.firstRenderedRow;
const lastRowInViewport = this.rowRenderer.lastRenderedRow;
for (let i = firstRowInViewport; i <= lastRowInViewport; i++) {
const row = this.rowModel.getRow(i);
if (!row) {
continue;
}
const store = row.parent?.childStore;
if (!store) {
continue;
}
const cache = store.getCache();
const lazyNode = cache.getNodes().getBy("node", row);
if (!lazyNode) {
continue;
}
const loadingNodes = this.cacheLoadingNodesMap.get(cache);
if (loadingNodes?.has(lazyNode.index)) {
continue;
}
if (row.__needsRefreshWhenVisible || row.stub && !row.failedLoad) {
return {
cache,
index: cache.getBlockStartIndex(lazyNode.index)
};
}
}
let cacheToRefresh = null;
let nodeToRefresh = null;
let nodeToRefreshDist = Number.MAX_SAFE_INTEGER;
for (const cache of this.cacheLoadingNodesMap.keys()) {
const nodesToRefresh = cache.getNodesToRefresh();
nodesToRefresh.forEach((node) => {
if (node.rowIndex == null) {
nodeToRefresh = node;
cacheToRefresh = cache;
return;
}
const lazyNode = cache.getNodes().getBy("node", node);
if (!lazyNode) {
return;
}
const loadingNodes = this.cacheLoadingNodesMap.get(cache);
if (loadingNodes?.has(lazyNode.index)) {
return;
}
const distToViewportTop = Math.abs(firstRowInViewport - node.rowIndex);
const distToViewportBottom = Math.abs(node.rowIndex - lastRowInViewport);
if (distToViewportTop < nodeToRefreshDist) {
nodeToRefresh = node;
nodeToRefreshDist = distToViewportTop;
cacheToRefresh = cache;
}
if (distToViewportBottom < nodeToRefreshDist) {
nodeToRefresh = node;
nodeToRefreshDist = distToViewportBottom;
cacheToRefresh = cache;
}
});
}
if (!cacheToRefresh) {
return void 0;
}
const lazyCache = cacheToRefresh;
const lazyIndex = lazyCache.getNodes().getBy("node", nodeToRefresh)?.index;
return lazyIndex == null ? void 0 : {
cache: lazyCache,
index: lazyCache.getBlockStartIndex(lazyIndex)
};
}
isRowLoading(cache, index) {
return this.cacheLoadingNodesMap.get(cache)?.has(index) ?? false;
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/stores/storeFactory.ts
var import_ag_grid_community209 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/serverSideRowModel/stores/lazy/lazyStore.ts
var import_ag_grid_community208 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/serverSideRowModel/stores/lazy/lazyCache.ts
var import_ag_grid_community207 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/serverSideRowModel/stores/lazy/multiIndexMap.ts
var MultiIndexMap = class {
constructor(...indexes) {
this.indexes = indexes;
this.maps = new Map(this.indexes.map((index) => [index, /* @__PURE__ */ new Map()]));
}
getSize() {
return this.maps.get(this.indexes[0]).size;
}
getBy(index, key) {
const map = this.maps.get(index);
return map.get(key);
}
set(item) {
this.indexes.forEach((index) => {
const map = this.maps.get(index);
map.set(item[index], item);
});
}
delete(item) {
this.indexes.forEach((index) => {
const map = this.maps.get(index);
map.delete(item[index]);
});
}
clear() {
this.maps.forEach((map) => map.clear());
}
getIterator(index) {
const map = this.maps.get(index);
return map.values();
}
forEach(callback) {
const iterator = this.getIterator(this.indexes[0]);
let pointer;
while (pointer = iterator.next()) {
if (pointer.done)
break;
callback(pointer.value);
}
}
find(callback) {
const iterator = this.getIterator(this.indexes[0]);
let pointer;
while (pointer = iterator.next()) {
if (pointer.done)
break;
if (callback(pointer.value)) {
return pointer.value;
}
}
}
filter(predicate) {
const iterator = this.getIterator(this.indexes[0]);
let pointer;
const result = [];
while (pointer = iterator.next()) {
if (pointer.done)
break;
if (predicate(pointer.value)) {
result.push(pointer.value);
}
}
return result;
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/stores/lazy/lazyCache.ts
var DEFAULT_BLOCK_SIZE = 100;
var LazyCache = class extends import_ag_grid_community207.BeanStub {
constructor(store, numberOfRows, isLastRowKnown, storeParams) {
super();
/**
* Indicates whether this is still the live dataset for this store (used for ignoring old requests after purge)
*/
this.live = true;
/**
* A cache of removed group nodes, this is retained for preserving group
* state when the node moves in and out of the cache. Generally caused by
* rows moving blocks.
*/
this.removedNodeCache = /* @__PURE__ */ new Map();
this.store = store;
this.numberOfRows = numberOfRows;
this.isLastRowKnown = isLastRowKnown;
this.storeParams = storeParams;
}
wireBeans(beans) {
this.rowRenderer = beans.rowRenderer;
this.blockUtils = beans.ssrmBlockUtils;
this.focusSvc = beans.focusSvc;
this.nodeManager = beans.ssrmNodeManager;
this.serverSideRowModel = beans.rowModel;
this.rowNodeSorter = beans.rowNodeSorter;
this.sortSvc = beans.sortSvc;
this.lazyBlockLoadingSvc = beans.lazyBlockLoadingSvc;
this.colModel = beans.colModel;
}
postConstruct() {
this.lazyBlockLoadingSvc.subscribe(this);
this.nodeMap = new MultiIndexMap("index", "id", "node");
this.nodeDisplayIndexMap = /* @__PURE__ */ new Map();
this.nodesToRefresh = /* @__PURE__ */ new Set();
this.defaultNodeIdPrefix = this.blockUtils.createNodeIdPrefix(this.store.getParentNode());
this.getRowIdFunc = (0, import_ag_grid_community207._getRowIdCallback)(this.gos);
this.isMasterDetail = this.gos.get("masterDetail");
}
destroy() {
this.lazyBlockLoadingSvc.unsubscribe(this);
this.numberOfRows = 0;
this.nodeMap.forEach((node) => this.blockUtils.destroyRowNode(node.node));
this.nodeMap.clear();
this.nodeDisplayIndexMap.clear();
this.nodesToRefresh.clear();
this.live = false;
super.destroy();
}
/**
* Get the row node for a specific display index from this store
* @param displayIndex the display index of the node to find
* @returns undefined if the node is not in the store bounds, otherwise will always return a node
*/
getRowByDisplayIndex(displayIndex) {
if (!this.store.isDisplayIndexInStore(displayIndex)) {
return void 0;
}
const node = this.nodeDisplayIndexMap.get(displayIndex);
if (node) {
if (node.stub || node.__needsRefreshWhenVisible) {
this.lazyBlockLoadingSvc.queueLoadCheck();
}
return node;
}
const hideOpenGroups = this.gos.get("groupHideOpenParents") || this.gos.get("groupAllowUnbalanced");
if (hideOpenGroups) {
const nextParent = this.nodeMap.find(
(lazyNode) => !!lazyNode.node.childStore?.isDisplayIndexInStore(displayIndex)
);
if (nextParent) {
return nextParent.node.childStore?.getRowUsingDisplayIndex(displayIndex);
}
}
if (displayIndex === this.store.getDisplayIndexStart()) {
return this.createStubNode(0, displayIndex);
}
const contiguouslyPreviousNode = this.nodeDisplayIndexMap.get(displayIndex - 1);
if (contiguouslyPreviousNode) {
if (this.isMasterDetail && contiguouslyPreviousNode.master && contiguouslyPreviousNode.expanded) {
return contiguouslyPreviousNode.detailNode;
}
if (contiguouslyPreviousNode.expanded && contiguouslyPreviousNode.childStore?.isDisplayIndexInStore(displayIndex)) {
return contiguouslyPreviousNode.childStore?.getRowUsingDisplayIndex(
displayIndex
);
}
const lazyCacheNode = this.nodeMap.getBy("node", contiguouslyPreviousNode);
return this.createStubNode(lazyCacheNode.index + 1, displayIndex);
}
const adjacentNodes = this.getSurroundingNodesByDisplayIndex(displayIndex);
if (adjacentNodes == null) {
const storeIndexFromEndIndex2 = this.store.getRowCount() - (this.store.getDisplayIndexEnd() - displayIndex);
return this.createStubNode(storeIndexFromEndIndex2, displayIndex);
}
const { previousNode, nextNode } = adjacentNodes;
if (previousNode && previousNode.node.expanded && previousNode.node.childStore?.isDisplayIndexInStore(displayIndex)) {
return previousNode.node.childStore?.getRowUsingDisplayIndex(displayIndex);
}
if (nextNode) {
const displayIndexDiff = nextNode.node.rowIndex - displayIndex;
const newStoreIndex = nextNode.index - displayIndexDiff;
return this.createStubNode(newStoreIndex, displayIndex);
}
const storeIndexFromEndIndex = this.store.getRowCount() - (this.store.getDisplayIndexEnd() - displayIndex);
return this.createStubNode(storeIndexFromEndIndex, displayIndex);
}
/**
* Used for creating and positioning a stub node without firing a store updated event
*/
createStubNode(storeIndex, displayIndex) {
const rowBounds = this.store.getRowBounds(displayIndex);
const newNode = this.createRowAtIndex(storeIndex, null, (node) => {
node.setRowIndex(displayIndex);
node.setRowTop(rowBounds.rowTop);
this.nodeDisplayIndexMap.set(displayIndex, node);
});
if (storeIndex === 0 && this.gos.get("groupHideOpenParents")) {
const parentGroupData = this.store.getParentNode().groupData;
if (parentGroupData) {
for (const key of Object.keys(parentGroupData)) {
setRowNodeGroupValue(newNode, this.colModel, key, parentGroupData[key]);
}
}
}
this.lazyBlockLoadingSvc.queueLoadCheck();
return newNode;
}
/**
* @param index The row index relative to this store
* @returns A rowNode at the given store index
*/
getRowByStoreIndex(index) {
return this.nodeMap.getBy("index", index)?.node;
}
/**
* Given a number of rows, skips through the given sequence & row top reference (using default row height)
* @param numberOfRowsToSkip number of rows to skip over in the given sequence
* @param displayIndexSeq the sequence in which to skip
* @param nextRowTop the row top reference in which to skip
*/
skipDisplayIndexes(numberOfRowsToSkip, displayIndexSeq, nextRowTop) {
if (numberOfRowsToSkip === 0) {
return;
}
const defaultRowHeight = (0, import_ag_grid_community207._getRowHeightAsNumber)(this.beans);
displayIndexSeq.value += numberOfRowsToSkip;
nextRowTop.value += numberOfRowsToSkip * defaultRowHeight;
}
/**
* @param displayIndexSeq the number sequence for generating the display index of each row
* @param nextRowTop an object containing the next row top value intended to be modified by ref per row
*/
setDisplayIndexes(displayIndexSeq, nextRowTop, uiLevel) {
this.nodeDisplayIndexMap.clear();
const orderedMap = {};
this.nodeMap.forEach((lazyNode) => {
orderedMap[lazyNode.index] = lazyNode.node;
});
let lastIndex = -1;
for (const stringIndex of Object.keys(orderedMap)) {
const node = orderedMap[stringIndex];
const numericIndex = Number(stringIndex);
const numberOfRowsToSkip2 = numericIndex - 1 - lastIndex;
this.skipDisplayIndexes(numberOfRowsToSkip2, displayIndexSeq, nextRowTop);
const isFirstChild = numericIndex === 0;
node.setFirstChild(isFirstChild);
if (isFirstChild && this.gos.get("groupHideOpenParents")) {
const parentGroupData = this.store.getParentNode().groupData;
if (parentGroupData) {
for (const key of Object.keys(parentGroupData)) {
setRowNodeGroupValue(node, this.colModel, key, isFirstChild ? parentGroupData[key] : void 0);
}
}
}
this.blockUtils.setDisplayIndex(node, displayIndexSeq, nextRowTop, uiLevel);
if (node.rowIndex != null) {
this.nodeDisplayIndexMap.set(node.rowIndex, node);
}
lastIndex = numericIndex;
}
const numberOfRowsToSkip = this.numberOfRows - 1 - lastIndex;
this.skipDisplayIndexes(numberOfRowsToSkip, displayIndexSeq, nextRowTop);
this.purgeExcessRows();
}
getRowCount() {
return this.numberOfRows;
}
setRowCount(rowCount, isLastRowIndexKnown) {
this.numberOfRows = rowCount;
if (isLastRowIndexKnown != null) {
this.isLastRowKnown = isLastRowIndexKnown;
if (isLastRowIndexKnown === false) {
this.numberOfRows += 1;
}
}
this.fireStoreUpdatedEvent();
}
getNodes() {
return this.nodeMap;
}
getNodeCachedByDisplayIndex(displayIndex) {
return this.nodeDisplayIndexMap.get(displayIndex) ?? null;
}
getNodesToRefresh() {
return this.nodesToRefresh;
}
/**
* @returns the previous and next loaded row nodes surrounding the given display index
*/
getSurroundingNodesByDisplayIndex(displayIndex) {
let nextNode;
let previousNode;
this.nodeMap.forEach((lazyNode) => {
if (displayIndex > lazyNode.node.rowIndex) {
if (previousNode == null || previousNode.node.rowIndex < lazyNode.node.rowIndex) {
previousNode = lazyNode;
}
return;
}
if (nextNode == null || nextNode.node.rowIndex > lazyNode.node.rowIndex) {
nextNode = lazyNode;
return;
}
});
if (!previousNode && !nextNode)
return null;
return { previousNode, nextNode };
}
/**
* Get or calculate the display index for a given store index
* @param storeIndex the rows index within this store
* @returns the rows visible display index relative to the grid
*/
getDisplayIndexFromStoreIndex(storeIndex) {
const nodeAtIndex = this.nodeMap.getBy("index", storeIndex);
if (nodeAtIndex) {
return nodeAtIndex.node.rowIndex;
}
let nextNode;
let previousNode;
this.nodeMap.forEach((lazyNode) => {
if (storeIndex > lazyNode.index) {
if (previousNode == null || previousNode.index < lazyNode.index) {
previousNode = lazyNode;
}
return;
}
if (nextNode == null || nextNode.index > lazyNode.index) {
nextNode = lazyNode;
return;
}
});
if (!nextNode) {
return this.store.getDisplayIndexEnd() - (this.numberOfRows - storeIndex);
}
if (!previousNode) {
return this.store.getDisplayIndexStart() + storeIndex;
}
const storeIndexDiff = storeIndex - previousNode.index;
const previousDisplayIndex = previousNode.node.childStore?.getDisplayIndexEnd() ?? previousNode.node.rowIndex;
return previousDisplayIndex + storeIndexDiff;
}
/**
* Creates a new row and inserts it at the given index
* @param atStoreIndex the node index relative to this store
* @param data the data object to populate the node with
* @returns the new row node
*/
createRowAtIndex(atStoreIndex, data, createNodeCallback) {
const lazyNode = this.nodeMap.getBy("index", atStoreIndex);
if (lazyNode) {
const { node } = lazyNode;
node.__needsRefreshWhenVisible = false;
if (this.doesNodeMatch(data, node)) {
this.blockUtils.updateDataIntoRowNode(node, data);
this.nodesToRefresh.delete(node);
return node;
}
if (this.getRowIdFunc == null && node.hasChildren() && node.expanded) {
this.nodesToRefresh.delete(node);
return node;
}
this.destroyRowAtIndex(atStoreIndex);
}
if (data && this.getRowIdFunc != null) {
const id = this.getRowId(data);
const deletedNode = id && this.removedNodeCache?.get(id);
if (deletedNode) {
this.removedNodeCache?.delete(id);
this.blockUtils.updateDataIntoRowNode(deletedNode, data);
this.nodeMap.set({
id: deletedNode.id,
node: deletedNode,
index: atStoreIndex
});
this.nodesToRefresh.delete(deletedNode);
deletedNode.__needsRefreshWhenVisible = false;
return deletedNode;
}
const lazyNode2 = this.nodeMap.getBy("id", id);
if (lazyNode2) {
this.nodeMap.delete(lazyNode2);
const { node, index } = lazyNode2;
this.blockUtils.updateDataIntoRowNode(node, data);
this.nodeMap.set({
id: node.id,
node,
index: atStoreIndex
});
this.nodesToRefresh.delete(node);
node.__needsRefreshWhenVisible = false;
if (this.getBlockStartIndex(index) === this.getBlockStartIndex(atStoreIndex)) {
return node;
}
this.markBlockForVerify(index);
return node;
}
}
const newNode = this.blockUtils.createRowNode(this.store.getRowDetails());
if (data != null) {
const defaultId = this.getPrefixedId(this.store.getIdSequence().value++);
this.blockUtils.setDataIntoRowNode(newNode, data, defaultId, void 0);
this.serverSideRowModel.setPaused(true);
this.blockUtils.checkOpenByDefault(newNode);
this.serverSideRowModel.setPaused(false);
this.nodeManager.addRowNode(newNode);
}
this.nodeMap.set({
id: newNode.id,
node: newNode,
index: atStoreIndex
});
if (createNodeCallback) {
createNodeCallback(newNode);
}
return newNode;
}
getBlockStates() {
const blockCounts = {};
const blockStates = {};
this.nodeMap.forEach(({ node, index }) => {
const blockStart = this.getBlockStartIndex(index);
if (!node.stub && !node.failedLoad) {
blockCounts[blockStart] = (blockCounts[blockStart] ?? 0) + 1;
}
let rowState = "loaded";
if (node.failedLoad) {
rowState = "failed";
} else if (this.lazyBlockLoadingSvc.isRowLoading(this, blockStart)) {
rowState = "loading";
} else if (this.nodesToRefresh.has(node) || node.stub) {
rowState = "needsLoading";
}
if (!blockStates[blockStart]) {
blockStates[blockStart] = /* @__PURE__ */ new Set();
}
blockStates[blockStart].add(rowState);
});
const statePriorityMap = {
loading: 4,
failed: 3,
needsLoading: 2,
loaded: 1
};
const blockPrefix = this.blockUtils.createNodeIdPrefix(this.store.getParentNode());
const results = {};
for (const blockStart of Object.keys(blockStates)) {
const sortedStates = [...blockStates[blockStart]].sort(
(a, b) => (statePriorityMap[a] ?? 0) - (statePriorityMap[b] ?? 0)
);
const priorityState = sortedStates[0];
const blockNumber = Number(blockStart) / this.getBlockSize();
const blockId = blockPrefix ? `${blockPrefix}-${blockNumber}` : String(blockNumber);
results[blockId] = {
blockNumber,
startRow: Number(blockStart),
endRow: Number(blockStart) + this.getBlockSize(),
pageStatus: priorityState,
loadedRowCount: blockCounts[blockStart] ?? 0
};
}
return results;
}
destroyRowAtIndex(atStoreIndex) {
const lazyNode = this.nodeMap.getBy("index", atStoreIndex);
if (!lazyNode) {
return;
}
this.nodeMap.delete(lazyNode);
this.nodeDisplayIndexMap.delete(lazyNode.node.rowIndex);
if (this.nodesToRefresh.size > 0) {
this.removedNodeCache.set(lazyNode.node.id, lazyNode.node);
} else {
this.blockUtils.destroyRowNode(lazyNode.node);
}
this.nodesToRefresh.delete(lazyNode.node);
}
getSsrmParams() {
return this.store.getSsrmParams();
}
/**
* @param id the base id to be prefixed
* @returns a node id with prefix if required
*/
getPrefixedId(id) {
if (this.defaultNodeIdPrefix) {
return this.defaultNodeIdPrefix + "-" + id;
} else {
return id.toString();
}
}
markBlockForVerify(rowIndex) {
const [start, end] = this.getBlockBounds(rowIndex);
const lazyNodesInRange = this.nodeMap.filter((lazyNode) => lazyNode.index >= start && lazyNode.index < end);
lazyNodesInRange.forEach(({ node }) => {
node.__needsRefreshWhenVisible = true;
});
}
doesNodeMatch(data, node) {
if (node.stub) {
return false;
}
const id = this.getRowId(data);
return id === null ? node.data === data : node.id === id;
}
/**
* Deletes any stub nodes not within the given range
*/
purgeStubsOutsideOfViewport() {
const { firstRenderedRow, lastRenderedRow } = this.rowRenderer;
const firstRowBlockStart = this.getBlockStartIndex(firstRenderedRow);
const [, lastRowBlockEnd] = this.getBlockBounds(lastRenderedRow);
this.nodeMap.forEach((lazyNode) => {
if (this.lazyBlockLoadingSvc.isRowLoading(this, lazyNode.index) || lazyNode.node.failedLoad) {
return;
}
if (lazyNode.node.stub && (lazyNode.index < firstRowBlockStart || lazyNode.index > lastRowBlockEnd)) {
this.destroyRowAtIndex(lazyNode.index);
}
});
}
getBlocksDistanceFromRow(nodes, otherDisplayIndex) {
const blockDistanceToMiddle = {};
nodes.forEach(({ node, index }) => {
const [blockStart, blockEnd] = this.getBlockBounds(index);
if (blockStart in blockDistanceToMiddle) {
return;
}
const distStart = Math.abs(node.rowIndex - otherDisplayIndex);
let distEnd;
const lastLazyNode = this.nodeMap.getBy("index", [blockEnd - 1]);
if (lastLazyNode)
distEnd = Math.abs(lastLazyNode.node.rowIndex - otherDisplayIndex);
const farthest = distEnd == null || distStart < distEnd ? distStart : distEnd;
blockDistanceToMiddle[blockStart] = farthest;
});
return Object.entries(blockDistanceToMiddle);
}
purgeExcessRows() {
this.purgeStubsOutsideOfViewport();
if (this.store.getDisplayIndexEnd() == null || this.storeParams.maxBlocksInCache == null) {
return;
}
const { firstRenderedRow, lastRenderedRow } = this.rowRenderer;
const allLoadedBlocks = /* @__PURE__ */ new Set();
const blocksInViewport = /* @__PURE__ */ new Set();
this.nodeMap.forEach(({ index, node }) => {
const blockStart = this.getBlockStartIndex(index);
allLoadedBlocks.add(blockStart);
const isInViewport = node.rowIndex >= firstRenderedRow && node.rowIndex <= lastRenderedRow;
if (isInViewport) {
blocksInViewport.add(blockStart);
}
});
const numberOfBlocksToRetain = Math.max(blocksInViewport.size, this.storeParams.maxBlocksInCache ?? 0);
const loadedBlockCount = allLoadedBlocks.size;
const blocksToRemove = loadedBlockCount - numberOfBlocksToRetain;
if (blocksToRemove <= 0) {
return;
}
let firstRowBlockStart = Number.MAX_SAFE_INTEGER;
let lastRowBlockStart = Number.MIN_SAFE_INTEGER;
blocksInViewport.forEach((blockStart) => {
if (firstRowBlockStart > blockStart) {
firstRowBlockStart = blockStart;
}
if (lastRowBlockStart < blockStart) {
lastRowBlockStart = blockStart;
}
});
const disposableNodes = this.nodeMap.filter(({ node, index }) => {
const rowBlockStart = this.getBlockStartIndex(index);
const rowBlockInViewport = rowBlockStart >= firstRowBlockStart && rowBlockStart <= lastRowBlockStart;
return !rowBlockInViewport && !this.isNodeCached(node);
});
if (disposableNodes.length === 0) {
return;
}
const midViewportRow = firstRenderedRow + (lastRenderedRow - firstRenderedRow) / 2;
const blockDistanceArray = this.getBlocksDistanceFromRow(disposableNodes, midViewportRow);
const blockSize = this.getBlockSize();
blockDistanceArray.sort((a, b) => Math.sign(b[1] - a[1]));
for (let i = 0; i < Math.min(blocksToRemove, blockDistanceArray.length); i++) {
const blockStart = Number(blockDistanceArray[i][0]);
for (let x = blockStart; x < blockStart + blockSize; x++) {
const lazyNode = this.nodeMap.getBy("index", x);
if (!lazyNode || this.isNodeCached(lazyNode.node)) {
continue;
}
this.destroyRowAtIndex(x);
}
}
}
isNodeFocused(node) {
const focusedCell = this.focusSvc.getFocusCellToUseAfterRefresh();
if (!focusedCell) {
return false;
}
if (focusedCell.rowPinned != null) {
return false;
}
const hasFocus = focusedCell.rowIndex === node.rowIndex;
return hasFocus;
}
isNodeCached(node) {
const isUnbalancedNode = this.gos.get("groupAllowUnbalanced") && node.key === "";
return node.isExpandable() && node.expanded || this.isNodeFocused(node) || isUnbalancedNode;
}
extractDuplicateIds(rows) {
if (this.getRowIdFunc == null) {
return [];
}
const newIds = /* @__PURE__ */ new Set();
const duplicates = /* @__PURE__ */ new Set();
rows.forEach((data) => {
const id = this.getRowId(data);
if (newIds.has(id)) {
duplicates.add(id);
return;
}
newIds.add(id);
});
return [...duplicates];
}
onLoadSuccess(firstRowIndex, numberOfRowsExpected, response) {
if (!this.live)
return;
const info = response.groupLevelInfo;
this.store.setStoreInfo(info);
if (this.getRowIdFunc != null) {
const duplicates = this.extractDuplicateIds(response.rowData);
if (duplicates.length > 0) {
const duplicateIdText = duplicates.join(", ");
(0, import_ag_grid_community207._warn)(205, { duplicateIdText });
this.onLoadFailed(firstRowIndex, numberOfRowsExpected);
return;
}
}
if (response.pivotResultFields) {
this.serverSideRowModel.generateSecondaryColumns(response.pivotResultFields);
}
const wasRefreshing = this.nodesToRefresh.size > 0;
response.rowData.forEach((data, responseRowIndex) => {
const rowIndex = firstRowIndex + responseRowIndex;
const nodeFromCache = this.nodeMap.getBy("index", rowIndex);
if (nodeFromCache?.node?.stub) {
this.createRowAtIndex(rowIndex, data);
return;
}
if (nodeFromCache && this.doesNodeMatch(data, nodeFromCache.node)) {
this.blockUtils.updateDataIntoRowNode(nodeFromCache.node, data);
this.nodesToRefresh.delete(nodeFromCache.node);
nodeFromCache.node.__needsRefreshWhenVisible = false;
return;
}
this.createRowAtIndex(rowIndex, data);
});
if (response.rowCount != void 0 && response.rowCount !== -1) {
this.numberOfRows = response.rowCount;
this.isLastRowKnown = true;
} else if (numberOfRowsExpected > response.rowData.length) {
this.numberOfRows = firstRowIndex + response.rowData.length;
this.isLastRowKnown = true;
} else if (!this.isLastRowKnown) {
const lastInferredRow = firstRowIndex + response.rowData.length + 1;
if (lastInferredRow > this.numberOfRows) {
this.numberOfRows = lastInferredRow;
}
}
if (this.isLastRowKnown) {
const lazyNodesAfterStoreEnd = this.nodeMap.filter((lazyNode) => lazyNode.index >= this.numberOfRows);
lazyNodesAfterStoreEnd.forEach((lazyNode) => this.destroyRowAtIndex(lazyNode.index));
}
this.fireStoreUpdatedEvent();
const finishedRefreshing = this.nodesToRefresh.size === 0;
if (wasRefreshing && finishedRefreshing) {
this.fireRefreshFinishedEvent();
}
}
fireRefreshFinishedEvent() {
const finishedRefreshing = this.nodesToRefresh.size === 0;
if (!finishedRefreshing) {
return;
}
this.removedNodeCache.forEach((node) => {
this.blockUtils.destroyRowNode(node);
});
this.removedNodeCache = /* @__PURE__ */ new Map();
this.store.fireRefreshFinishedEvent();
}
/**
* @returns true if all rows are loaded
*/
isStoreFullyLoaded() {
const knowsSize = this.isLastRowKnown;
const hasCorrectRowCount = this.nodeMap.getSize() === this.numberOfRows;
if (!knowsSize || !hasCorrectRowCount) {
return;
}
if (this.nodesToRefresh.size > 0) {
return;
}
let index = -1;
const firstOutOfPlaceNode = this.nodeMap.find((lazyNode) => {
index += 1;
if (lazyNode.index !== index) {
return true;
}
if (lazyNode.node.__needsRefreshWhenVisible) {
return true;
}
if (lazyNode.node.stub) {
return true;
}
return false;
});
return firstOutOfPlaceNode == null;
}
isLastRowIndexKnown() {
return this.isLastRowKnown;
}
onLoadFailed(firstRowIndex, numberOfRowsExpected) {
if (!this.live)
return;
const wasRefreshing = this.nodesToRefresh.size > 0;
for (let i = firstRowIndex; i < firstRowIndex + numberOfRowsExpected && i < this.getRowCount(); i++) {
let { node } = this.nodeMap.getBy("index", i) ?? {};
if (node) {
this.nodesToRefresh.delete(node);
}
if (!node || !node.stub) {
if (node && !node.stub) {
this.destroyRowAtIndex(i);
}
node = this.createRowAtIndex(i);
}
node.__needsRefreshWhenVisible = false;
node.failedLoad = true;
}
const finishedRefreshing = this.nodesToRefresh.size === 0;
if (wasRefreshing && finishedRefreshing) {
this.fireRefreshFinishedEvent();
}
this.fireStoreUpdatedEvent();
}
markNodesForRefresh() {
this.nodeMap.forEach((lazyNode) => {
if (lazyNode.node.stub && !lazyNode.node.failedLoad) {
return;
}
this.nodesToRefresh.add(lazyNode.node);
});
this.lazyBlockLoadingSvc.queueLoadCheck();
if (this.isLastRowKnown && this.numberOfRows === 0) {
this.numberOfRows = 1;
this.isLastRowKnown = false;
this.fireStoreUpdatedEvent();
}
}
isNodeInCache(id) {
return !!this.nodeMap.getBy("id", id);
}
// gets called 1) row count changed 2) cache purged 3) items inserted
fireStoreUpdatedEvent() {
if (!this.live) {
return;
}
this.store.fireStoreUpdatedEvent();
}
getRowId(data) {
if (this.getRowIdFunc == null) {
return null;
}
const { level } = this.store.getRowDetails();
const parentKeys = this.store.getParentNode().getRoute() ?? [];
return this.getRowIdFunc({
data,
parentKeys: parentKeys.length > 0 ? parentKeys : void 0,
level
});
}
getOrderedNodeMap() {
const obj = {};
this.nodeMap.forEach((node) => obj[node.index] = node);
return obj;
}
clearDisplayIndexes() {
this.nodeDisplayIndexMap.clear();
}
/**
* Client side sorting
*/
clientSideSortRows() {
const sortOptions = this.sortSvc?.getSortOptions() ?? [];
const isAnySort = sortOptions.some((opt) => opt.sort != null);
if (!isAnySort || !this.rowNodeSorter) {
return;
}
const allNodes = new Array(this.nodeMap.getSize());
this.nodeMap.forEach((lazyNode) => allNodes[lazyNode.index] = lazyNode.node);
this.nodeMap.clear();
const sortedNodes = this.rowNodeSorter.doFullSort(allNodes, sortOptions);
sortedNodes.forEach((node, index) => {
this.nodeMap.set({
id: node.id,
node,
index
});
});
}
/**
* Transaction Support here
*/
updateRowNodes(updates) {
const updatedNodes = [];
updates.forEach((data) => {
const id = this.getRowId(data);
const lazyNode = this.nodeMap.getBy("id", id);
if (lazyNode) {
this.blockUtils.updateDataIntoRowNode(lazyNode.node, data);
updatedNodes.push(lazyNode.node);
}
});
return updatedNodes;
}
insertRowNodes(inserts, indexToAdd) {
const realRowCount = this.store.getRowCount() - (this.store.getParentNode().sibling ? 1 : 0);
const addIndex = indexToAdd == null && this.isLastRowKnown ? realRowCount : indexToAdd;
if (addIndex == null || realRowCount < addIndex) {
return [];
}
const uniqueInsertsMap = {};
inserts.forEach((data) => {
const dataId = this.getRowId(data);
if (dataId && this.isNodeInCache(dataId)) {
return;
}
uniqueInsertsMap[dataId] = data;
});
const uniqueInserts = Object.values(uniqueInsertsMap);
const numberOfInserts = uniqueInserts.length;
if (numberOfInserts === 0) {
return [];
}
const nodesToMove = this.nodeMap.filter((node) => node.index >= addIndex);
nodesToMove.forEach((lazyNode) => this.nodeMap.delete(lazyNode));
nodesToMove.forEach((lazyNode) => {
this.nodeMap.set({
node: lazyNode.node,
index: lazyNode.index + numberOfInserts,
id: lazyNode.id
});
});
this.numberOfRows += numberOfInserts;
return uniqueInserts.map(
(data, uniqueInsertOffset) => this.createRowAtIndex(addIndex + uniqueInsertOffset, data)
);
}
removeRowNodes(idsToRemove) {
const removedNodes = [];
const nodesToVerify = [];
let deletedNodeCount = 0;
const remainingIdsToRemove = [...idsToRemove];
const allNodes = this.getOrderedNodeMap();
let contiguousIndex = -1;
for (const stringIndex of Object.keys(allNodes)) {
contiguousIndex += 1;
const node = allNodes[stringIndex];
const matchIndex = remainingIdsToRemove.findIndex((idToRemove) => idToRemove === node.id);
if (matchIndex !== -1) {
remainingIdsToRemove.splice(matchIndex, 1);
this.destroyRowAtIndex(Number(stringIndex));
removedNodes.push(node.node);
deletedNodeCount += 1;
continue;
}
if (deletedNodeCount === 0) {
continue;
}
const numericStoreIndex = Number(stringIndex);
if (contiguousIndex !== numericStoreIndex) {
nodesToVerify.push(node.node);
}
this.nodeMap.delete(node);
this.nodeMap.set({
id: node.id,
node: node.node,
index: numericStoreIndex - deletedNodeCount
});
}
this.numberOfRows -= this.isLastRowIndexKnown() ? idsToRemove.length : deletedNodeCount;
if (remainingIdsToRemove.length > 0 && nodesToVerify.length > 0) {
nodesToVerify.forEach((node) => node.__needsRefreshWhenVisible = true);
this.lazyBlockLoadingSvc.queueLoadCheck();
}
return removedNodes;
}
/**
* Return the block size configured for this cache
*/
getBlockSize() {
return this.storeParams.cacheBlockSize || DEFAULT_BLOCK_SIZE;
}
/**
* Get the start index of the loading block for a given index
*/
getBlockStartIndex(storeIndex) {
const blockSize = this.getBlockSize();
return storeIndex - storeIndex % blockSize;
}
/**
* Get the start and end index of a block, given a row store index
*/
getBlockBounds(storeIndex) {
const startOfBlock = this.getBlockStartIndex(storeIndex);
const blockSize = this.getBlockSize();
return [startOfBlock, startOfBlock + blockSize];
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/stores/lazy/lazyStore.ts
var LazyStore = class extends import_ag_grid_community208.BeanStub {
constructor(ssrmParams, storeParams, parentRowNode) {
super();
this.idSequence = { value: 0 };
this.ssrmParams = ssrmParams;
this.parentRowNode = parentRowNode;
this.storeParams = storeParams;
this.level = parentRowNode.level + 1;
this.group = ssrmParams.rowGroupCols ? this.level < ssrmParams.rowGroupCols.length : false;
this.leafGroup = ssrmParams.rowGroupCols ? this.level === ssrmParams.rowGroupCols.length - 1 : false;
this.info = {};
}
wireBeans(beans) {
this.blockUtils = beans.ssrmBlockUtils;
this.storeUtils = beans.ssrmStoreUtils;
this.selectionSvc = beans.selectionSvc;
this.rowGroupColsSvc = beans.rowGroupColsSvc;
}
postConstruct() {
let numberOfRows = 1;
if (this.level === 0) {
numberOfRows = this.storeUtils.getServerSideInitialRowCount() ?? 1;
this.eventSvc.dispatchEventOnce({
type: "rowCountReady"
});
}
this.cache = this.createManagedBean(new LazyCache(this, numberOfRows, false, this.storeParams));
const usingTreeData = this.gos.get("treeData");
if (!usingTreeData && this.group && this.rowGroupColsSvc) {
const groupColVo = this.ssrmParams.rowGroupCols[this.level];
this.groupField = groupColVo.field;
this.rowGroupColumn = this.rowGroupColsSvc.columns[this.level];
}
}
destroy() {
this.displayIndexStart = void 0;
this.displayIndexEnd = void 0;
this.destroyBean(this.cache);
super.destroy();
}
/**
* Given a server response, ingest the rows outside of the data source lifecycle.
*
* @param rowDataParams the server response containing the rows to ingest
* @param startRow the index to start ingesting rows
* @param expectedRows the expected number of rows in the response (used to determine if the last row index is known)
*/
applyRowData(rowDataParams, startRow, expectedRows) {
this.cache.onLoadSuccess(startRow, expectedRows, rowDataParams);
}
/**
* Applies a given transaction to the data set within this store
*
* @param transaction an object containing delta instructions determining the changes to apply to this store
* @returns an object determining the status of this transaction and effected nodes
*/
applyTransaction(transaction) {
const idFunc = (0, import_ag_grid_community208._getRowIdCallback)(this.gos);
if (!idFunc) {
(0, import_ag_grid_community208._warn)(206);
return {
status: import_ag_grid_community208.ServerSideTransactionResultStatus.Cancelled
};
}
const applyCallback = this.gos.getCallback("isApplyServerSideTransaction");
if (applyCallback) {
const params = {
transaction,
parentNode: this.parentRowNode,
groupLevelInfo: this.info
};
const apply = applyCallback(params);
if (!apply) {
return { status: import_ag_grid_community208.ServerSideTransactionResultStatus.Cancelled };
}
}
const allRowsLoaded = this.cache.isStoreFullyLoaded();
let updatedNodes = void 0;
if (transaction.update?.length) {
updatedNodes = this.cache.updateRowNodes(transaction.update);
}
let insertedNodes = void 0;
if (transaction.add?.length) {
let addIndex = transaction.addIndex;
if (addIndex != null && addIndex < 0) {
addIndex = void 0;
}
insertedNodes = this.cache.insertRowNodes(transaction.add, addIndex);
}
let removedNodes = void 0;
if (transaction.remove?.length) {
const allIdsToRemove = transaction.remove.map(
(data) => idFunc({ level: this.level, parentKeys: this.parentRowNode.getRoute() ?? [], data })
);
const allUniqueIdsToRemove = [...new Set(allIdsToRemove)];
removedNodes = this.cache.removeRowNodes(allUniqueIdsToRemove);
}
const isClientSideSortingEnabled = this.gos.get("serverSideEnableClientSideSort");
const isUpdateOrAdd = updatedNodes?.length || insertedNodes?.length;
const isClientSideSort = allRowsLoaded && isClientSideSortingEnabled;
if (isClientSideSort && isUpdateOrAdd) {
this.cache.clientSideSortRows();
}
this.updateSelectionAfterTransaction(updatedNodes, removedNodes);
return {
status: import_ag_grid_community208.ServerSideTransactionResultStatus.Applied,
update: updatedNodes,
add: insertedNodes,
remove: removedNodes
};
}
updateSelectionAfterTransaction(updatedNodes, removedNodes) {
if (!this.selectionSvc) {
return;
}
const nodesToDeselect = [];
updatedNodes?.forEach((node) => {
if (node.isSelected() && !node.selectable) {
nodesToDeselect.push(node);
}
});
removedNodes?.forEach((node) => {
if (node.isSelected()) {
nodesToDeselect.push(node);
}
});
if (nodesToDeselect.length) {
this.selectionSvc.setNodesSelected({
newValue: false,
clearSelection: false,
nodes: nodesToDeselect,
source: "rowDataChanged"
});
}
}
/**
* Clear the display indexes, used for fading rows out when stores are not being destroyed
*/
clearDisplayIndexes() {
this.displayIndexStart = void 0;
this.displayIndexEnd = void 0;
this.cache.getNodes().forEach((lazyNode) => this.blockUtils.clearDisplayIndex(lazyNode.node));
if (this.parentRowNode.sibling) {
this.blockUtils.clearDisplayIndex(this.parentRowNode.sibling);
}
this.cache.clearDisplayIndexes();
}
/**
* @returns an index representing the last sequentially displayed row in the grid for this store
*/
getDisplayIndexStart() {
return this.displayIndexStart;
}
/**
* @returns the index representing one after the last sequentially displayed row in the grid for this store
*/
getDisplayIndexEnd() {
return this.displayIndexEnd;
}
/**
* @returns the virtual size of this store
*/
getRowCount() {
if (this.parentRowNode.sibling) {
return this.cache.getRowCount() + 1;
}
return this.cache.getRowCount();
}
/**
* Sets the current row count of the store, and whether the last row index is known
*/
setRowCount(rowCount, isLastRowIndexKnown) {
this.cache.setRowCount(rowCount, isLastRowIndexKnown);
}
/**
* Given a display index, returns whether that row is within this store or a child store of this store
*
* @param displayIndex the visible index of a row
* @returns whether or not the row exists within this store
*/
isDisplayIndexInStore(displayIndex) {
if (this.cache.getRowCount() === 0)
return false;
return this.displayIndexStart <= displayIndex && displayIndex < this.getDisplayIndexEnd();
}
/**
* Recursively sets up the display indexes and top position of every node belonging to this store.
*
* Called after a row height changes, or a store updated event.
*
* @param displayIndexSeq the number sequence for generating the display index of each row
* @param nextRowTop an object containing the next row top value intended to be modified by ref per row
*/
setDisplayIndexes(displayIndexSeq, nextRowTop, uiLevel) {
this.displayIndexStart = displayIndexSeq.value;
this.topPx = nextRowTop.value;
const footerNode = this.parentRowNode.level > -1 && (0, import_ag_grid_community208._getGroupTotalRowCallback)(this.gos)({ node: this.parentRowNode });
if (!footerNode) {
_destroyRowNodeFooter(this.parentRowNode);
}
if (footerNode === "top") {
_createRowNodeFooter(this.parentRowNode, this.beans);
this.blockUtils.setDisplayIndex(this.parentRowNode.sibling, displayIndexSeq, nextRowTop, uiLevel);
}
this.cache.setDisplayIndexes(displayIndexSeq, nextRowTop, uiLevel);
if (footerNode === "bottom") {
_createRowNodeFooter(this.parentRowNode, this.beans);
this.blockUtils.setDisplayIndex(this.parentRowNode.sibling, displayIndexSeq, nextRowTop, uiLevel);
}
this.displayIndexEnd = displayIndexSeq.value;
this.heightPx = nextRowTop.value - this.topPx;
}
/**
* Recursively applies a provided function to every node
*
* For the purpose of exclusively server side filtered stores, this is the same as getNodes().forEachDeepAfterFilterAndSort
*/
forEachStoreDeep(callback, sequence = { value: 0 }) {
callback(this, sequence.value++);
this.cache.getNodes().forEach((lazyNode) => {
const childCache = lazyNode.node.childStore;
if (childCache) {
childCache.forEachStoreDeep(callback, sequence);
}
});
}
/**
* Recursively applies a provided function to every node
*
* For the purpose of exclusively server side filtered stores, this is the same as getNodes().forEachDeepAfterFilterAndSort
*/
forEachNodeDeep(callback, sequence = { value: 0 }) {
this.cache.getNodes().forEach((lazyNode) => {
callback(lazyNode.node, sequence.value++);
const childCache = lazyNode.node.childStore;
if (childCache) {
childCache.forEachNodeDeep(callback, sequence);
}
});
}
/**
* Recursively applies a provided function to every node
*
* For the purpose of exclusively server side filtered stores, this is the same as getNodes().forEachDeep
*/
forEachNodeDeepAfterFilterAndSort(callback, sequence = { value: 0 }, includeFooterNodes = false) {
const footerNode = this.parentRowNode.level > -1 && (0, import_ag_grid_community208._getGroupTotalRowCallback)(this.gos)({ node: this.parentRowNode });
if (footerNode === "top") {
callback(this.parentRowNode.sibling, sequence.value++);
}
const orderedNodes = this.cache.getOrderedNodeMap();
for (const lazyNode of Object.values(orderedNodes)) {
callback(lazyNode.node, sequence.value++);
const childCache = lazyNode.node.childStore;
if (childCache) {
childCache.forEachNodeDeepAfterFilterAndSort(callback, sequence, includeFooterNodes);
}
}
if (footerNode === "bottom") {
callback(this.parentRowNode.sibling, sequence.value++);
}
}
/**
* Removes the failed status from all nodes, and marks them as stub to encourage reloading
*/
retryLoads() {
this.cache.getNodes().forEach(({ node }) => {
if (node.failedLoad) {
node.failedLoad = false;
node.__needsRefreshWhenVisible = true;
node.stub = true;
}
});
this.forEachChildStoreShallow((store) => store.retryLoads());
this.fireStoreUpdatedEvent();
}
/**
* Given a display index, returns the row at that location.
*
* @param displayRowIndex the displayed index within the grid to search for
* @returns the row node if the display index falls within the store, if it didn't exist this will create a new stub to return
*/
getRowUsingDisplayIndex(displayRowIndex) {
if (this.parentRowNode.sibling && displayRowIndex === this.parentRowNode.sibling.rowIndex) {
return this.parentRowNode.sibling;
}
return this.cache.getRowByDisplayIndex(displayRowIndex);
}
/**
* Given a display index, returns the row top and height for the row at that index.
*
* @param displayIndex the display index of the node
* @returns an object containing the rowTop and rowHeight of the node at the given displayIndex
*/
getRowBounds(displayIndex) {
if (!this.isDisplayIndexInStore(displayIndex)) {
return null;
}
const thisNode = this.cache.getNodeCachedByDisplayIndex(displayIndex);
if (thisNode) {
const boundsFromRow = this.blockUtils.extractRowBounds(thisNode, displayIndex);
if (boundsFromRow) {
return boundsFromRow;
}
}
const { previousNode, nextNode } = this.cache.getSurroundingNodesByDisplayIndex(displayIndex) ?? {};
if (previousNode) {
const boundsFromRow = this.blockUtils.extractRowBounds(previousNode.node, displayIndex);
if (boundsFromRow != null) {
return boundsFromRow;
}
}
const defaultRowHeight = (0, import_ag_grid_community208._getRowHeightAsNumber)(this.beans);
if (nextNode) {
const numberOfRowDiff2 = (nextNode.node.rowIndex - displayIndex) * defaultRowHeight;
return {
rowTop: nextNode.node.rowTop - numberOfRowDiff2,
rowHeight: defaultRowHeight
};
}
const lastTop = this.topPx + this.heightPx;
const numberOfRowDiff = (this.getDisplayIndexEnd() - displayIndex) * defaultRowHeight;
return {
rowTop: lastTop - numberOfRowDiff,
rowHeight: defaultRowHeight
};
}
/**
* Given a vertical pixel, determines whether this store contains a row at that pixel
*
* @param pixel a vertical pixel position from the grid
* @returns whether that pixel points to a virtual space belonging to this store
*/
isPixelInRange(pixel) {
return pixel >= this.topPx && pixel < this.topPx + this.heightPx;
}
/**
* Given a vertical pixel, returns the row existing at that pixel location
*
* @param pixel a vertical pixel position from the grid
* @returns the display index at the given pixel location
*/
getRowIndexAtPixel(pixel) {
if (pixel < this.topPx) {
return this.getDisplayIndexStart();
}
if (pixel >= this.topPx + this.heightPx) {
return this.getDisplayIndexEnd() - 1;
}
if (this.parentRowNode.sibling && pixel > this.parentRowNode.sibling.rowTop && pixel < this.parentRowNode.sibling.rowTop + this.parentRowNode.sibling.rowHeight) {
return this.parentRowNode.sibling.rowIndex;
}
let distToPreviousNodeTop = Number.MAX_SAFE_INTEGER;
let previousNode = null;
let distToNextNodeTop = Number.MAX_SAFE_INTEGER;
let nextNode = null;
this.cache.getNodes().forEach(({ node }) => {
const distBetween = Math.abs(pixel - node.rowTop);
if (node.rowTop < pixel) {
if (distBetween < distToPreviousNodeTop) {
distToPreviousNodeTop = distBetween;
previousNode = node;
}
return;
}
if (distBetween < distToNextNodeTop) {
distToNextNodeTop = distBetween;
nextNode = node;
}
});
previousNode = previousNode;
nextNode = nextNode;
if (previousNode) {
const indexOfRow = this.blockUtils.getIndexAtPixel(previousNode, pixel);
if (indexOfRow != null) {
return indexOfRow;
}
}
const defaultRowHeight = (0, import_ag_grid_community208._getRowHeightAsNumber)(this.beans);
if (nextNode) {
const nextTop2 = nextNode.rowTop;
const numberOfRowDiff2 = Math.ceil((nextTop2 - pixel) / defaultRowHeight);
return nextNode.rowIndex - numberOfRowDiff2;
}
const nextTop = this.topPx + this.heightPx;
const numberOfRowDiff = Math.floor((nextTop - pixel) / defaultRowHeight);
return this.getDisplayIndexEnd() - numberOfRowDiff;
}
/**
* Given a path of group keys, returns the child store for that group.
*
* @param keys the grouping path to the desired store
* @returns the child store for the given keys, or null if not found
*/
getChildStore(keys) {
return this.storeUtils.getChildStore(keys, this, (key) => {
const lazyNode = this.cache.getNodes().find((lazyNode2) => lazyNode2.node.key == key);
if (!lazyNode) {
return null;
}
return lazyNode.node;
});
}
/**
* Executes a provided callback on each child store belonging to this store
*
* @param cb the callback to execute
*/
forEachChildStoreShallow(cb) {
this.cache.getNodes().forEach(({ node }) => {
if (node.childStore) {
cb(node.childStore);
}
});
}
/**
* Executes after a change to sorting, determines recursively whether this store or a child requires refreshed.
*
* If a purge refresh occurs, the row count is preserved.
*
* @param params a set of properties pertaining to the sort changes
*/
refreshAfterSort(params) {
const serverSortsAllLevels = this.storeUtils.isServerSideSortAllLevels();
if (serverSortsAllLevels || this.storeUtils.isServerRefreshNeeded(this.parentRowNode, this.ssrmParams.rowGroupCols, params)) {
const allRowsLoaded = this.cache.isStoreFullyLoaded();
const isClientSideSortingEnabled = this.gos.get("serverSideEnableClientSideSort");
const isClientSideSort = allRowsLoaded && isClientSideSortingEnabled;
if (!isClientSideSort) {
const oldCount = this.cache.getRowCount();
const lastKnown = this.cache.isLastRowIndexKnown();
this.destroyBean(this.cache);
this.cache = this.createManagedBean(new LazyCache(this, oldCount, lastKnown, this.storeParams));
return;
}
this.cache.clientSideSortRows();
}
this.forEachChildStoreShallow((store) => store.refreshAfterSort(params));
}
/**
* Executes after a change to filtering, determines recursively whether this store or a child requires refreshed.
*
* If a refresh occurs, the row count is reset.
*
* @param params a set of properties pertaining to the filter changes
*/
refreshAfterFilter(params) {
const serverFiltersAllLevels = !this.storeUtils.isServerSideOnlyRefreshFilteredGroups();
if (serverFiltersAllLevels || this.storeUtils.isServerRefreshNeeded(this.parentRowNode, this.ssrmParams.rowGroupCols, params)) {
this.refreshStore(true);
return;
}
this.forEachChildStoreShallow((store) => store.refreshAfterFilter(params));
}
/**
* Marks all existing nodes as requiring reloaded, and triggers a load check
*
* @param purge whether to remove all nodes and data in favour of stub nodes
*/
refreshStore(purge) {
if (purge) {
this.destroyBean(this.cache);
this.cache = this.createManagedBean(new LazyCache(this, 1, false, this.storeParams));
this.fireStoreUpdatedEvent();
return;
}
this.cache.markNodesForRefresh();
}
/**
* Used for pagination, given a local/store index, returns the display index of that row
*
* @param topLevelIndex the store index of a row
* @returns the display index for the given store index
*/
getTopLevelRowDisplayedIndex(topLevelIndex) {
const displayIndex = this.cache.getDisplayIndexFromStoreIndex(topLevelIndex);
return displayIndex ?? topLevelIndex;
}
/**
* Used for pagination to determine if the last page is known, and for aria to determine if the last grid row is known
*
* @returns whether the last index of this store is known, or if lazy loading still required
*/
isLastRowIndexKnown() {
return this.cache.isLastRowIndexKnown();
}
/**
* Used by the selection service to select a range of nodes
*
* @param firstInRange the first node in the range to find
* @param lastInRange the last node in the range to find
* @returns a range of nodes between firstInRange and lastInRange inclusive
*/
getRowNodesInRange(firstInRange, lastInRange) {
return this.cache.getNodes().filter(({ node }) => {
return node.rowIndex >= firstInRange.rowIndex && node.rowIndex <= lastInRange.rowIndex;
}).map(({ node }) => node);
}
/**
* Mutates a given array to add this stores state, and recursively add all the children store states.
*
* @param result a mutable results array
*/
addStoreStates(result) {
result.push({
route: this.parentRowNode.getRoute() ?? [],
rowCount: this.getRowCount(),
lastRowIndexKnown: this.isLastRowIndexKnown(),
info: this.info,
maxBlocksInCache: this.storeParams.maxBlocksInCache,
cacheBlockSize: this.storeParams.cacheBlockSize
});
this.forEachChildStoreShallow((childStore) => childStore.addStoreStates(result));
}
getIdSequence() {
return this.idSequence;
}
getParentNode() {
return this.parentRowNode;
}
getRowDetails() {
return {
field: this.groupField,
group: this.group,
leafGroup: this.leafGroup,
level: this.level,
parent: this.parentRowNode,
rowGroupColumn: this.rowGroupColumn
};
}
getSsrmParams() {
return this.ssrmParams;
}
setStoreInfo(info) {
if (info) {
Object.assign(this.info, info);
}
}
// gets called 1) row count changed 2) cache purged
fireStoreUpdatedEvent() {
this.eventSvc.dispatchEvent({
type: "storeUpdated"
});
}
// gets called when row data updated, and no more refreshing needed
fireRefreshFinishedEvent() {
this.eventSvc.dispatchEvent({
type: "storeRefreshed",
route: this.parentRowNode.getRoute()
});
}
getBlockStates() {
return this.cache.getBlockStates();
}
getStoreBounds() {
return {
topPx: this.topPx,
heightPx: this.heightPx
};
}
getCache() {
return this.cache;
}
getFirstNode() {
const firstNode = this.cache.getNodes().getBy("index", 0);
return firstNode?.node ?? null;
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/stores/storeFactory.ts
var StoreFactory = class extends import_ag_grid_community209.BeanStub {
constructor() {
super(...arguments);
this.beanName = "ssrmStoreFactory";
}
wireBeans(beans) {
this.colModel = beans.colModel;
this.rowGroupColsSvc = beans.rowGroupColsSvc;
this.pivotColsSvc = beans.pivotColsSvc;
this.rowAutoHeight = beans.rowAutoHeight;
}
createStore(ssrmParams, parentNode) {
const storeParams = this.getStoreParams(ssrmParams, parentNode);
return new LazyStore(ssrmParams, storeParams, parentNode);
}
getStoreParams(ssrmParams, parentNode) {
const userStoreParams = this.getLevelSpecificParams(parentNode);
const cacheBlockSize = this.getBlockSize(userStoreParams);
const maxBlocksInCache = this.getMaxBlocksInCache(ssrmParams, userStoreParams);
const storeParams = {
cacheBlockSize,
maxBlocksInCache
};
return storeParams;
}
getMaxBlocksInCache(ssrmParams, userStoreParams) {
const maxBlocksInCache = userStoreParams && userStoreParams.maxBlocksInCache != null ? userStoreParams.maxBlocksInCache : this.gos.get("maxBlocksInCache");
const maxBlocksActive = maxBlocksInCache != null && maxBlocksInCache >= 0;
if (!maxBlocksActive) {
return;
}
if (ssrmParams.dynamicRowHeight) {
(0, import_ag_grid_community209._warn)(203);
return;
}
if (this.rowAutoHeight?.active) {
(0, import_ag_grid_community209._warn)(204);
return void 0;
}
return maxBlocksInCache;
}
getBlockSize(userStoreParams) {
const blockSize = userStoreParams && userStoreParams.cacheBlockSize != null ? userStoreParams.cacheBlockSize : this.gos.get("cacheBlockSize");
if (blockSize != null && blockSize > 0) {
return blockSize;
} else {
return 100;
}
}
getLevelSpecificParams(parentNode) {
const callback = this.gos.getCallback("getServerSideGroupLevelParams");
if (!callback) {
return void 0;
}
const params = {
level: parentNode.level + 1,
parentRowNode: parentNode.level >= 0 ? parentNode : void 0,
rowGroupColumns: this.rowGroupColsSvc?.columns ?? [],
pivotColumns: this.pivotColsSvc?.columns ?? [],
pivotMode: this.colModel.isPivotMode()
};
const res = callback(params);
return res;
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/stores/storeUtils.ts
var import_ag_grid_community210 = require("ag-grid-community");
var StoreUtils = class extends import_ag_grid_community210.BeanStub {
constructor() {
super(...arguments);
this.beanName = "ssrmStoreUtils";
}
wireBeans(beans) {
this.colModel = beans.colModel;
this.serverSideRowModel = beans.rowModel;
this.storeFactory = beans.ssrmStoreFactory;
}
getChildStore(keys, currentCache, findNodeFunc) {
if (!keys?.length) {
return currentCache;
}
const nextKey = keys[0];
const nextNode = findNodeFunc(nextKey);
if (nextNode) {
if (keys.length === 1 && !nextNode.childStore) {
const storeParams = this.serverSideRowModel.getParams();
nextNode.childStore = this.createBean(this.storeFactory.createStore(storeParams, nextNode));
}
const keyListForNextLevel = keys.slice(1, keys.length);
const nextStore = nextNode.childStore;
return nextStore ? nextStore.getChildStore(keyListForNextLevel) : null;
}
return null;
}
isServerRefreshNeeded(parentRowNode, rowGroupCols, params) {
if (params.valueColChanged || params.secondaryColChanged) {
return true;
}
const level = parentRowNode.level + 1;
const grouping = level < rowGroupCols.length;
const leafNodes = !grouping;
if (leafNodes) {
return true;
}
const colIdThisGroup = rowGroupCols[level].id;
const actionOnThisGroup = params.changedColumns.indexOf(colIdThisGroup) > -1;
if (actionOnThisGroup) {
return true;
}
const allCols = this.colModel.getCols();
const affectedGroupCols = allCols.filter((col) => col.getColDef().showRowGroup && params.changedColumns.includes(col.getId())).map((col) => col.getColDef().showRowGroup).some((group) => group === true || group === colIdThisGroup);
return affectedGroupCols;
}
getServerSideInitialRowCount() {
return this.gos.get("serverSideInitialRowCount");
}
isServerSideSortAllLevels() {
return this.gos.get("serverSideSortAllLevels") && (0, import_ag_grid_community210._isServerSideRowModel)(this.gos);
}
isServerSideOnlyRefreshFilteredGroups() {
return this.gos.get("serverSideOnlyRefreshFilteredGroups") && (0, import_ag_grid_community210._isServerSideRowModel)(this.gos);
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/transactionManager.ts
var import_ag_grid_community211 = require("ag-grid-community");
var TransactionManager = class extends import_ag_grid_community211.BeanStub {
constructor() {
super(...arguments);
this.beanName = "ssrmTxnManager";
this.asyncTransactions = [];
}
wireBeans(beans) {
this.valueCache = beans.valueCache;
this.serverSideRowModel = beans.rowModel;
this.selectionSvc = beans.selectionSvc;
}
postConstruct() {
if (!(0, import_ag_grid_community211._isServerSideRowModel)(this.gos)) {
return;
}
}
applyTransactionAsync(transaction, callback) {
if (this.asyncTransactionsTimeout == null) {
this.scheduleExecuteAsync();
}
this.asyncTransactions.push({ transaction, callback });
}
scheduleExecuteAsync() {
const waitMillis = this.gos.get("asyncTransactionWaitMillis");
this.asyncTransactionsTimeout = window.setTimeout(() => {
this.executeAsyncTransactions();
}, waitMillis);
}
executeAsyncTransactions() {
if (!this.asyncTransactions) {
return;
}
const resultFuncs = [];
const resultsForEvent = [];
const transactionsToRetry = [];
let atLeastOneTransactionApplied = false;
this.asyncTransactions.forEach((txWrapper) => {
let result;
const hasStarted = this.serverSideRowModel.executeOnStore(txWrapper.transaction.route, (cache) => {
result = cache.applyTransaction(txWrapper.transaction);
});
if (!hasStarted) {
result = { status: import_ag_grid_community211.ServerSideTransactionResultStatus.StoreNotStarted };
} else if (result == void 0) {
result = { status: import_ag_grid_community211.ServerSideTransactionResultStatus.StoreNotFound };
}
resultsForEvent.push(result);
const retryTransaction = result.status == import_ag_grid_community211.ServerSideTransactionResultStatus.StoreLoading;
if (retryTransaction) {
transactionsToRetry.push(txWrapper);
return;
}
if (txWrapper.callback) {
resultFuncs.push(() => txWrapper.callback(result));
}
if (result.status === import_ag_grid_community211.ServerSideTransactionResultStatus.Applied) {
atLeastOneTransactionApplied = true;
}
});
if (resultFuncs.length > 0) {
window.setTimeout(() => {
resultFuncs.forEach((func) => func());
}, 0);
}
this.asyncTransactionsTimeout = void 0;
this.asyncTransactions = transactionsToRetry;
if (atLeastOneTransactionApplied) {
this.valueCache?.onDataChanged();
this.eventSvc.dispatchEvent({ type: "storeUpdated" });
}
if (resultsForEvent.length > 0) {
this.eventSvc.dispatchEvent({
type: "asyncTransactionsFlushed",
results: resultsForEvent
});
}
}
flushAsyncTransactions() {
if (this.asyncTransactionsTimeout != null) {
clearTimeout(this.asyncTransactionsTimeout);
}
this.executeAsyncTransactions();
}
applyTransaction(transaction) {
let res;
const hasStarted = this.serverSideRowModel.executeOnStore(transaction.route, (store) => {
res = store.applyTransaction(transaction);
});
if (!hasStarted) {
return { status: import_ag_grid_community211.ServerSideTransactionResultStatus.StoreNotStarted };
} else if (res) {
this.valueCache?.onDataChanged();
if (res.remove && this.selectionSvc) {
const removedRowIds = res.remove.map((row) => row.id);
this.selectionSvc.deleteSelectionStateFromParent(transaction.route || [], removedRowIds);
}
this.eventSvc.dispatchEvent({ type: "storeUpdated" });
return res;
} else {
return { status: import_ag_grid_community211.ServerSideTransactionResultStatus.StoreNotFound };
}
}
};
// packages/ag-grid-enterprise/src/serverSideRowModel/serverSideRowModelModule.ts
var ServerSideRowModelModule = {
moduleName: "ServerSideRowModel",
version: VERSION,
rowModels: ["serverSide"],
beans: [
ServerSideRowModel,
ExpandListener,
StoreUtils,
BlockUtils,
NodeManager,
TransactionManager,
FilterListener,
StoreFactory,
ListenerUtils,
ServerSideSelectionService,
LazyBlockLoadingService,
SsrmRowChildrenService,
ServerSideExpansionService,
SortListener
],
dependsOn: [
EnterpriseCoreModule,
import_ag_grid_community212._SortModule,
import_ag_grid_community212._SharedRowSelectionModule,
SharedPivotModule,
SharedTreeDataModule,
LoadingCellRendererModule
]
};
var ServerSideRowModelApiModule = {
moduleName: "ServerSideRowModelApi",
version: VERSION,
apiFunctions: {
getServerSideSelectionState,
setServerSideSelectionState,
applyServerSideTransaction,
applyServerSideTransactionAsync,
applyServerSideRowData,
retryServerSideLoads,
flushServerSideAsyncTransactions,
refreshServerSide,
getServerSideGroupLevelState
},
dependsOn: [EnterpriseCoreModule, import_ag_grid_community212._CsrmSsrmSharedApiModule, import_ag_grid_community212._SsrmInfiniteSharedApiModule]
};
// packages/ag-grid-enterprise/src/sparkline/sparklinesModule.ts
var import_ag_grid_community214 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/sparkline/sparkline.css-GENERATED.ts
var sparklineCSS = (
/*css*/
`.ag-sparkline-wrapper{height:100%;line-height:normal;position:absolute;top:0;width:100%}`
);
// packages/ag-grid-enterprise/src/sparkline/sparklineCellRenderer.ts
var import_ag_grid_community213 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/sparkline/sparklinesUtils.ts
var WrappedFunctionMarker = Symbol("WrappedFunctionMarker");
var wrapFn = (fn, wrapperFn) => {
if (fn[WrappedFunctionMarker]) {
return fn;
}
const wrapped = (...args) => wrapperFn(fn, ...args);
wrapped[WrappedFunctionMarker] = WrappedFunctionMarker;
return wrapped;
};
// packages/ag-grid-enterprise/src/sparkline/sparklineCellRenderer.ts
function tooltipRendererWithXValue(params) {
return { content: `${params.xValue} ${params.yValue}` };
}
function tooltipRenderer(params) {
return { content: `${params.yValue}` };
}
var SparklineCellRenderer = class extends import_ag_grid_community213.Component {
constructor() {
super({
tag: "div",
cls: "ag-sparkline-wrapper",
children: [{ tag: "span", ref: "eSparkline" }]
});
this.eSparkline = import_ag_grid_community213.RefPlaceholder;
this.cachedWidth = 0;
this.cachedHeight = 0;
this.dataRef = [];
this.processedData = [];
}
postConstruct() {
this.env = this.beans.environment;
this.addManagedPropertyListeners(
["chartThemeOverrides", "chartThemes", "styleNonce"],
() => this.refresh(this.params)
);
}
createListener(batch = true) {
return () => this.updateSize(this.params?.column?.getActualWidth() ?? 0, (this.params?.node.rowHeight ?? 0) - 2, batch);
}
initGridObserver() {
const batchListener = this.createListener();
const listener = this.createListener(false);
const column = this.params?.column;
const rowNode = this.params?.node;
column.__addEventListener("columnStateUpdated", batchListener);
rowNode.__addEventListener("heightChanged", batchListener);
this.addDestroyFunc(() => {
column.__removeEventListener("columnStateUpdated", batchListener);
rowNode.__removeEventListener("heightChanged", batchListener);
});
listener();
}
updateSize(newWidth, newHeight, batch = true) {
newWidth -= this.env.getCellPadding();
if (newWidth !== this.cachedWidth || newHeight !== this.cachedHeight) {
this.cachedWidth = newWidth;
this.cachedHeight = newHeight;
const refresh = this.refresh.bind(this);
if (batch) {
(0, import_ag_grid_community213._batchCall)(() => this.isAlive() && refresh());
} else {
refresh();
}
}
}
init(params) {
this.params = params;
this.initGridObserver();
}
refresh(params = this.params) {
var _a;
this.params = params;
const width = this.cachedWidth;
const height = this.cachedHeight;
const styleNonce = this.gos.get("styleNonce");
if (!this.sparklineInstance && params && width > 0 && height > 0) {
this.sparklineOptions = {
container: this.eSparkline,
width,
height,
...params.sparklineOptions,
...styleNonce ? { styleNonce } : {},
data: this.processData(params.value)
};
(_a = this.sparklineOptions).type ?? (_a.type = "line");
if (this.sparklineOptions.tooltip?.renderer) {
this.wrapTooltipRenderer();
} else {
const renderer = this.getDefaultTooltipRenderer();
this.sparklineOptions.tooltip = {
...this.sparklineOptions.tooltip,
renderer
};
}
const theme = this.sparklineOptions?.theme;
if (this.sparklineOptions.type === "bar" && this.sparklineOptions.itemStyler) {
this.wrapItemStyler(this.sparklineOptions);
} else if (theme?.overrides?.bar?.series?.itemStyler) {
this.wrapItemStyler(theme.overrides.bar.series);
}
this.sparklineInstance = params.createSparkline(this.sparklineOptions);
return true;
} else if (this.sparklineInstance) {
this.sparklineInstance.update({
...this.sparklineOptions,
data: this.processData(params?.value),
width,
height,
...styleNonce ? { styleNonce } : {}
});
return true;
}
return false;
}
processData(data = []) {
if (data.length === 0) {
return data;
}
if (this.dataRef !== data) {
this.dataRef = data;
this.processedData = Array.isArray(data[0]) ? data.filter((item) => item != null) : data;
}
return this.processedData;
}
createContext() {
return {
data: this.params?.data,
cellData: this.params?.value
};
}
getDefaultTooltipRenderer(userRendererResult) {
const userTitle = userRendererResult?.title;
const xKeyProvided = this.sparklineOptions.xKey;
const tupleData = Array.isArray(this.sparklineOptions.data?.[0]);
const showXValue = !userTitle && (xKeyProvided || tupleData);
return showXValue ? tooltipRendererWithXValue : tooltipRenderer;
}
wrapItemStyler(container) {
container.itemStyler = wrapFn(container.itemStyler, (fn, stylerParams) => {
return fn({
...stylerParams,
context: this.createContext()
});
});
}
wrapTooltipRenderer() {
this.sparklineOptions.tooltip = {
...this.sparklineOptions.tooltip,
renderer: wrapFn(this.sparklineOptions.tooltip.renderer, (fn, tooltipParams) => {
const userRendererResult = fn({
...tooltipParams,
context: this.createContext()
});
if (typeof userRendererResult === "string") {
return userRendererResult;
}
return {
...this.getDefaultTooltipRenderer(userRendererResult)(tooltipParams),
...userRendererResult
};
})
};
}
destroy() {
super.destroy();
this.sparklineInstance?.destroy();
}
};
// packages/ag-grid-enterprise/src/sparkline/sparklinesModule.ts
var moduleName = "Sparklines";
var SparklinesModule = {
moduleName,
version: VERSION,
dependsOn: [EnterpriseCoreModule],
validate: () => {
return {
isValid: false,
message: (0, import_ag_grid_community214._preInitErrMsg)(258)
};
},
with: (params) => {
params.setup();
return {
moduleName,
version: VERSION,
dependsOn: [EnterpriseCoreModule],
css: [sparklineCSS],
userComponents: {
agSparklineCellRenderer: {
classImp: SparklineCellRenderer,
/** Default params for provided components */
params: { createSparkline: params.createSparkline }
}
},
validate: () => {
return { isValid: true };
}
};
}
};
// packages/ag-grid-enterprise/src/find/find.css-GENERATED.ts
var findCSS = (
/*css*/
`.ag-find-cell{display:block;overflow:hidden;text-overflow:ellipsis}.ag-find-match{background-color:var(--ag-find-match-background-color);color:var(--ag-find-match-color)}.ag-find-active-match{background-color:var(--ag-find-active-match-background-color);color:var(--ag-find-active-match-color)}`
);
// packages/ag-grid-enterprise/src/find/findApi.ts
function findNext(beans) {
beans.findSvc?.next();
}
function findPrevious(beans) {
beans.findSvc?.previous();
}
function findGetTotalMatches(beans) {
return beans.findSvc?.totalMatches ?? 0;
}
function findGoTo(beans, match, force) {
beans.findSvc?.goTo(match, force);
}
function findClearActive(beans) {
beans.findSvc?.clearActive();
}
function findGetActiveMatch(beans) {
return beans.findSvc?.activeMatch;
}
function findGetNumMatches(beans, params) {
const { node, column } = params;
return beans.findSvc?.getNumMatches(node, column) ?? 0;
}
function findGetParts(beans, params) {
return beans.findSvc?.getParts(params) ?? [];
}
function findRefresh(beans) {
return beans.findSvc?.refresh(true);
}
// packages/ag-grid-enterprise/src/find/findCellRenderer.ts
var import_ag_grid_community215 = require("ag-grid-community");
var FindCellRendererElement = { tag: "span", cls: "ag-find-cell" };
var FindCellRenderer = class extends import_ag_grid_community215.Component {
constructor() {
super(FindCellRendererElement);
}
init(params) {
this.refresh(params);
}
refresh(params) {
const { node, column } = params;
const { findSvc, valueSvc } = this.beans;
const { value, valueFormatted } = valueSvc.getValueForDisplay(column, node, true);
const displayValue = valueFormatted ?? value ?? "";
const eGui = this.getGui();
(0, import_ag_grid_community215._clearElement)(eGui);
const parts = findSvc?.getParts({ value: displayValue, node, column: column ?? null });
if (!parts) {
eGui.textContent = (0, import_ag_grid_community215._toString)(displayValue) ?? "";
eGui.classList.remove("ag-find-cell-active-match");
return true;
}
let hasActiveMatch = false;
for (const { value: value2, match, activeMatch } of parts) {
const content = (0, import_ag_grid_community215._toString)(value2) ?? "";
if (match) {
const element = (0, import_ag_grid_community215._createElement)({ tag: "mark", cls: "ag-find-match" });
element.textContent = content;
if (activeMatch) {
element.classList.add("ag-find-active-match");
hasActiveMatch = true;
}
eGui.appendChild(element);
} else {
eGui.appendChild(document.createTextNode(content));
}
}
eGui.classList.toggle("ag-find-cell-active-match", hasActiveMatch);
return true;
}
};
// packages/ag-grid-enterprise/src/find/findService.ts
var import_ag_grid_community216 = require("ag-grid-community");
function defaultCaseFormat(value) {
return value?.toLocaleLowerCase();
}
function getMatchesForValue(findSearchValue, caseFormat, valueToFind) {
const finalValue = caseFormat((0, import_ag_grid_community216._toString)(valueToFind));
let numMatches = 0;
if (finalValue?.length) {
let index = -1;
while (true) {
index = finalValue.indexOf(findSearchValue, index + 1);
if (index != -1) {
numMatches++;
} else {
break;
}
}
}
return numMatches;
}
var FindService = class extends import_ag_grid_community216.BeanStub {
constructor() {
super(...arguments);
this.beanName = "findSvc";
/**
* Is find currently active (e.g. non-empty search value).
* Used for performance when checking matches (part of cell rendering)
*/
this.active = false;
/** pinned top matches */
this.topMatches = /* @__PURE__ */ new Map();
/** same nodes as keys in `topMatches`, but kept separate for performance when moving backwards and forwards through the matches */
this.topNodes = [];
/** total number of matches in pinned top */
this.topNumMatches = 0;
this.centerMatches = /* @__PURE__ */ new Map();
this.centerNodes = [];
this.centerNumMatches = 0;
this.bottomMatches = /* @__PURE__ */ new Map();
this.bottomNodes = [];
/** switches based on grid options */
this.caseFormat = defaultCaseFormat;
/** whether to scroll to active match after a refresh */
this.scrollOnRefresh = false;
this.totalMatches = 0;
}
postConstruct() {
if (!(0, import_ag_grid_community216._isClientSideRowModel)(this.gos)) {
return;
}
const refreshAndWipeActive = this.refresh.bind(this, false);
const refreshAndKeepActive = this.refresh.bind(this, true);
const refreshAndKeepActiveDebounced = (0, import_ag_grid_community216._debounce)(
this,
() => {
if (this.isAlive()) {
refreshAndKeepActive();
}
},
0
);
this.refreshDebounced = refreshAndKeepActiveDebounced;
this.addManagedPropertyListener("findSearchValue", refreshAndWipeActive);
this.addManagedPropertyListener("findOptions", ({ currentValue, previousValue }) => {
if (!(0, import_ag_grid_community216._jsonEquals)(currentValue, previousValue)) {
refreshAndWipeActive();
}
});
this.addManagedPropertyListeners(["groupSuppressBlankHeader", "showOpenedGroup"], refreshAndKeepActive);
this.addManagedEventListeners({
modelUpdated: refreshAndKeepActive,
displayedColumnsChanged: refreshAndKeepActive,
pinnedRowDataChanged: refreshAndKeepActive,
cellValueChanged: refreshAndKeepActiveDebounced,
rowNodeDataChanged: refreshAndKeepActiveDebounced
});
const rowSpanSvc = this.beans.rowSpanSvc;
if (rowSpanSvc) {
this.addManagedListeners(rowSpanSvc, { spannedCellsUpdated: refreshAndKeepActiveDebounced });
}
refreshAndWipeActive();
}
next() {
this.findAcrossContainers(false, ["top", null, "bottom"], 1, 1);
}
previous() {
this.findAcrossContainers(true, ["bottom", null, "top"], this.totalMatches, -1);
}
goTo(match, force) {
if (!force && match === this.activeMatch?.numOverall) {
return;
}
const { topMatches, topNumMatches, centerMatches, centerNumMatches, bottomMatches } = this;
if (match <= topNumMatches) {
this.goToInContainer(topMatches, match, 0);
return;
}
if (match <= centerNumMatches) {
this.goToInContainer(centerMatches, match, topNumMatches);
return;
}
this.goToInContainer(bottomMatches, match, topNumMatches + centerNumMatches);
}
clearActive() {
if (this.activeMatch) {
this.setActive(void 0);
}
}
// called by cell ctrl, so needs to be performant
isMatch(node, column) {
return this.active && !!this.getMatches(node.rowPinned).get(node)?.some(([colToCheck]) => colToCheck === column);
}
getNumMatches(node, column) {
return this.getMatches(node.rowPinned).get(node)?.find(([colToCheck]) => colToCheck === column)?.[1] ?? 0;
}
/**
* Get detail for cell renderer. Splits up the cell value into strings depending on
* whether they don't match, match, or are the active match
*/
getParts(params) {
const { value, node, column, precedingNumMatches } = params;
const findSearchValue = this.findSearchValue;
const stringValue = (0, import_ag_grid_community216._toString)(value) ?? "";
if ((0, import_ag_grid_community216._missing)(findSearchValue)) {
return [{ value: stringValue }];
}
const valueToFind = this.caseFormat(stringValue) ?? "";
const activeMatchNum = this.getActiveMatchNum(node, column) - (precedingNumMatches ?? 0);
let lastIndex = 0;
let currentMatchNum = 0;
const findTextLength = findSearchValue.length;
const parts = [];
while (true) {
const index = valueToFind.indexOf(findSearchValue, lastIndex);
if (index != -1) {
currentMatchNum++;
if (index > lastIndex) {
parts.push({ value: stringValue.slice(lastIndex, index) });
}
const endIndex = index + findTextLength;
parts.push({
value: stringValue.slice(index, endIndex),
match: true,
activeMatch: currentMatchNum === activeMatchNum
});
lastIndex = endIndex;
} else {
if (lastIndex < stringValue.length) {
parts.push({
value: stringValue.slice(lastIndex)
});
}
return parts;
}
}
}
// when a detail grid is created, we need to sync the matches
registerDetailGrid(node, api) {
const gos = this.gos;
if (!(0, import_ag_grid_community216._isClientSideRowModel)(gos)) {
return;
}
const isSearchDetail = () => gos.get("findOptions")?.searchDetail;
const compareMatchesAndRefresh = (newNumMatches) => {
const nodeMatch = this.centerMatches.get(node)?.[0];
const oldNumMatches = nodeMatch?.[1] ?? 0;
if (newNumMatches !== oldNumMatches) {
this.refreshDebounced();
}
};
api.addEventListener("findChanged", (event) => {
if (api.isDestroyed() || !this.isAlive() || !this.active || !isSearchDetail()) {
return;
}
compareMatchesAndRefresh(event.totalMatches);
});
api.addEventListener("gridPreDestroyed", () => {
if (!this.isAlive() || !this.active || !isSearchDetail()) {
return;
}
const masterNode = node.parent;
const findSearchValue = this.findSearchValue;
if (!masterNode || !findSearchValue) {
return;
}
const numMatches = gos.get("detailCellRendererParams")?.getFindMatches?.({
node: masterNode,
data: masterNode.data,
findSearchValue: gos.get("findSearchValue"),
updateMatches: this.refreshDebounced,
getMatchesForValue: (value) => getMatchesForValue(findSearchValue, this.caseFormat, value)
}) ?? 0;
compareMatchesAndRefresh(numMatches);
});
if (isSearchDetail()) {
api.setGridOption("findSearchValue", gos.get("findSearchValue"));
}
}
// updates all the matches
refresh(maintainActive) {
const rowNodesToRefresh = /* @__PURE__ */ new Set([...this.topNodes, ...this.centerNodes, ...this.bottomNodes]);
this.topNodes = [];
this.centerNodes = [];
this.bottomNodes = [];
const {
topNodes,
topMatches,
centerMatches,
centerNodes,
bottomNodes,
bottomMatches,
beans: {
gos,
visibleCols,
rowModel,
valueSvc,
pinnedRowModel,
pagination,
rowSpanSvc,
masterDetailSvc,
colModel
},
findSearchValue: oldFindSearchValue
} = this;
const findOptions = gos.get("findOptions");
const caseFormat = findOptions?.caseSensitive ? (value) => value ?? void 0 : defaultCaseFormat;
this.caseFormat = caseFormat;
const providedFindSearchValue = gos.get("findSearchValue");
const findSearchValue = caseFormat(providedFindSearchValue?.trim());
this.findSearchValue = findSearchValue;
topMatches.clear();
centerMatches.clear();
bottomMatches.clear();
const oldActiveMatch = maintainActive ? this.activeMatch : void 0;
this.activeMatch = void 0;
const checkMasterDetail = gos.get("masterDetail") && findOptions?.searchDetail && masterDetailSvc;
if ((0, import_ag_grid_community216._missing)(findSearchValue)) {
this.active = false;
this.topNumMatches = 0;
this.centerNumMatches = 0;
this.totalMatches = 0;
this.refreshRows(rowNodesToRefresh);
if (checkMasterDetail) {
const store = masterDetailSvc.store;
for (const detailId of Object.keys(store)) {
store[detailId]?.api?.findClearActive();
}
}
if (!(0, import_ag_grid_community216._missing)(oldFindSearchValue)) {
this.dispatchFindChanged();
}
return;
}
const allCols = visibleCols.allCols;
const isFullWidthCellFunc = gos.getCallback("isFullWidthRow");
const detailCellRendererParams = gos.get("detailCellRendererParams");
const fullWidthCellRendererParams = gos.get("fullWidthCellRendererParams");
const groupRowRendererParams = gos.get("groupRowRendererParams");
const flattenDetails = _getFlattenDetails(gos);
const pivotMode = colModel.isPivotMode();
let containerNumMatches = 0;
let matches;
let rowNodes;
let checkCurrentPage = false;
const addMatches = (node, column, numMatches, skipRefresh) => {
if (!numMatches) {
return;
}
let rowMatches = matches.get(node);
if (!rowMatches) {
rowMatches = [];
matches.set(node, rowMatches);
rowNodes.push(node);
if (!skipRefresh) {
rowNodesToRefresh.add(node);
}
}
rowMatches.push([column, numMatches]);
containerNumMatches += numMatches;
};
const findMatchesForRow = (node) => {
if (checkCurrentPage) {
let rowIndex = node.rowIndex;
let nodeToCheck = node.parent;
while (rowIndex == null && nodeToCheck) {
rowIndex = nodeToCheck.rowIndex;
nodeToCheck = nodeToCheck.parent;
}
if (rowIndex == null || !pagination.isRowInPage(rowIndex)) {
return;
}
}
const isParent = node.hasChildren();
if (!_shouldRowBeRendered(
flattenDetails,
node,
isParent,
pivotMode,
_isRemovedSingleChildrenGroup(flattenDetails, node, isParent),
_isRemovedLowestSingleChildrenGroup(flattenDetails, node, isParent)
)) {
return;
}
const data = node.data;
if (isFullWidthCellFunc?.({ rowNode: node })) {
if (fullWidthCellRendererParams) {
const numMatches = fullWidthCellRendererParams.getFindMatches?.({
node,
data,
findSearchValue: providedFindSearchValue,
updateMatches: this.refreshDebounced,
getMatchesForValue: (value) => getMatchesForValue(findSearchValue, caseFormat, value)
}) ?? 0;
addMatches(node, null, numMatches);
}
return;
}
if ((0, import_ag_grid_community216._isFullWidthGroupRow)(gos, node, pivotMode)) {
let valueToFind;
const getFindText = groupRowRendererParams?.getFindText;
if (getFindText) {
const value = valueSvc.getValueForDisplay(void 0, node).value;
valueToFind = getFindText(
(0, import_ag_grid_community216._addGridCommonParams)(gos, {
value,
node,
data,
column: null,
colDef: null,
getValueFormatted: () => {
const { valueFormatted } = valueSvc.getValueForDisplay(void 0, node, true);
return valueFormatted;
}
})
);
} else {
const { value, valueFormatted } = valueSvc.getValueForDisplay(void 0, node, true);
valueToFind = valueFormatted ?? value;
}
const numMatches = getMatchesForValue(findSearchValue, caseFormat, valueToFind);
addMatches(node, null, numMatches);
return;
}
const nodeWillBeHiddenByOpenParent = node.level > 0 && gos.get("groupHideOpenParents") && node.parent?.getFirstChild() === node && !node.parent?.expanded;
for (const column of allCols) {
if ((0, import_ag_grid_community216.isSpecialCol)(column)) {
continue;
}
const cellSpan = rowSpanSvc?.getCellSpan(column, node);
if (cellSpan && cellSpan.firstNode !== node) {
continue;
}
if (column.colDef.showRowGroup && nodeWillBeHiddenByOpenParent) {
continue;
}
let valueToFind;
const colDef = column.colDef;
const getFindText = colDef.getFindText;
if (getFindText) {
const value = valueSvc.getValueForDisplay(column, node).value;
valueToFind = getFindText(
(0, import_ag_grid_community216._addGridCommonParams)(gos, {
value,
node,
data,
column,
colDef,
getValueFormatted: () => {
const { valueFormatted } = valueSvc.getValueForDisplay(column, node, true);
return valueFormatted;
}
})
);
} else {
const { value, valueFormatted } = valueSvc.getValueForDisplay(column, node, true);
valueToFind = valueFormatted ?? value;
}
const numMatches = getMatchesForValue(findSearchValue, caseFormat, valueToFind);
addMatches(node, column, numMatches);
}
if (node.master && checkMasterDetail) {
const detailNode = node.detailNode;
if (detailNode) {
const detailApi = detailNode.detailGridInfo?.api;
if (detailApi) {
detailApi.setGridOption("findSearchValue", providedFindSearchValue);
const numMatches = detailApi.findGetTotalMatches();
addMatches(detailNode, null, numMatches);
return;
}
}
if (detailCellRendererParams) {
const numMatches = detailCellRendererParams.getFindMatches?.({
node,
data,
findSearchValue: providedFindSearchValue,
updateMatches: this.refreshDebounced,
getMatchesForValue: (value) => getMatchesForValue(findSearchValue, caseFormat, value)
}) ?? 0;
addMatches(
detailNode ?? { parent: node, dummy: true },
null,
numMatches,
!detailNode
// if dummy detail node, don't refresh
);
}
}
};
matches = topMatches;
rowNodes = topNodes;
pinnedRowModel?.forEachPinnedRow("top", findMatchesForRow);
this.topNumMatches = containerNumMatches;
let totalMatches = containerNumMatches;
matches = centerMatches;
rowNodes = centerNodes;
containerNumMatches = 0;
checkCurrentPage = !!pagination && !!findOptions?.currentPageOnly;
rowModel.forEachNodeAfterFilterAndSort(findMatchesForRow, true);
this.centerNumMatches = containerNumMatches;
totalMatches += containerNumMatches;
matches = bottomMatches;
rowNodes = bottomNodes;
containerNumMatches = 0;
checkCurrentPage = false;
pinnedRowModel?.forEachPinnedRow("bottom", findMatchesForRow);
totalMatches += containerNumMatches;
this.totalMatches = totalMatches;
this.active = true;
this.refreshRows(rowNodesToRefresh);
if (oldActiveMatch) {
this.resetActiveMatch(oldActiveMatch);
}
this.dispatchFindChanged();
}
// update the active match back to what it was previously if possible. e.g. row index might have changed
resetActiveMatch(oldActiveMatch) {
const { column, numInMatch } = oldActiveMatch;
let node = oldActiveMatch.node;
if (node.dummy) {
const detailNode = node.parent?.detailNode;
if (!detailNode) {
return;
}
node = detailNode;
}
const rowPinned = node.rowPinned ?? null;
const stillValid = this.getMatches(rowPinned)?.get(node)?.some(([columnToCheck, numMatches]) => columnToCheck === column && numMatches >= numInMatch);
if (!stillValid) {
return;
}
let numOverall = 0;
if (rowPinned == null) {
numOverall = this.topNumMatches;
} else if (rowPinned === "bottom") {
numOverall = this.topNumMatches + this.centerNumMatches;
}
const updateNumInMatches = () => {
const matches = this.getMatches(rowPinned);
for (const nodeToCheck of matches.keys()) {
const matchingNode = nodeToCheck === node;
const cols = matches.get(nodeToCheck);
for (const [columnToCheck, numMatches] of cols) {
if (matchingNode && columnToCheck === column) {
numOverall += numInMatch;
return;
}
numOverall += numMatches;
}
}
};
updateNumInMatches();
const activeMatch = {
...oldActiveMatch,
node,
numOverall
};
this.activeMatch = activeMatch;
this.refreshRows(/* @__PURE__ */ new Set([node]), column == null ? void 0 : /* @__PURE__ */ new Set([column]));
if (this.scrollOnRefresh) {
this.scrollOnRefresh = false;
this.scrollToActive(activeMatch);
}
this.setDetailActive(activeMatch);
}
refreshRows(rowNodes, columns) {
if (!rowNodes.size) {
return;
}
this.beans.rowRenderer.refreshCells({
rowNodes: [...rowNodes],
columns: columns ? [...columns] : void 0,
force: true,
suppressFlash: true
});
}
// go to the next/previous match across all containers
findAcrossContainers(backwards, containers, startNum, increment) {
if (!this.totalMatches) {
this.setActive();
return;
}
const activeMatch = this.activeMatch;
let containersToFind = containers;
if (activeMatch) {
const { column, node, numInMatch, numOverall } = activeMatch;
const rowPinned = node.rowPinned ?? null;
const nextOverallNum = numOverall + increment;
const matchInContainer = this.findInContainer(
rowPinned,
backwards,
nextOverallNum,
node,
column,
numInMatch
);
if (matchInContainer) {
return;
}
const activeContainerIndex = containers.indexOf(rowPinned);
const containerLength = containers.length;
const containersAfter = containers.slice(activeContainerIndex + 1, containerLength);
if (containersAfter.some(
(containerRowPinned) => this.findInContainer(containerRowPinned, backwards, nextOverallNum)
)) {
return;
}
containersToFind = containers.slice(0, activeContainerIndex + 1);
}
containersToFind.some((containerRowPinned) => this.findInContainer(containerRowPinned, backwards, startNum));
}
// go to the next/previous match within a container
findInContainer(rowPinned, backwards, nextOverallNum, currentNode, currentColumn, currentNumInMatch) {
const matches = this.getMatches(rowPinned);
const rowNodes = this.getRowNodes(rowPinned);
const direction = backwards ? -1 : 1;
if (currentNode != null) {
const currentIndexRowMatches = matches.get(currentNode);
const colArrayIndex = currentIndexRowMatches?.findIndex(([column]) => column === currentColumn);
if (colArrayIndex != null && colArrayIndex != -1) {
const [column, numMatches] = currentIndexRowMatches[colArrayIndex];
if (backwards ? currentNumInMatch > 1 : currentNumInMatch < numMatches) {
this.setActive({
column,
node: currentNode,
numInMatch: currentNumInMatch + direction,
numOverall: nextOverallNum
});
return true;
}
}
const nextMatch2 = colArrayIndex != null && colArrayIndex != -1 ? currentIndexRowMatches?.[colArrayIndex + direction] : void 0;
if (nextMatch2) {
const [column, numMatches] = nextMatch2;
this.setActive({
column,
node: currentNode,
numInMatch: backwards ? numMatches : 1,
numOverall: nextOverallNum
});
return true;
}
}
let nextNode;
if (currentNode == null) {
nextNode = rowNodes[backwards ? rowNodes.length - 1 : 0];
} else {
const rowArrayIndex = rowNodes.findIndex((node) => node === currentNode);
nextNode = rowNodes[rowArrayIndex + direction];
}
if (nextNode == null) {
return false;
}
const nextIndexRowMatches = matches.get(nextNode);
const nextMatch = nextIndexRowMatches?.[backwards ? nextIndexRowMatches.length - 1 : 0];
if (nextMatch) {
const [column, numMatches] = nextMatch;
this.setActive({
column,
node: nextNode,
numInMatch: backwards ? numMatches : 1,
numOverall: nextOverallNum
});
return true;
}
return false;
}
dispatchFindChanged() {
const { eventSvc, activeMatch, totalMatches, findSearchValue } = this;
eventSvc.dispatchEvent({
type: "findChanged",
activeMatch,
totalMatches,
findSearchValue
});
}
setActive(activeMatch) {
if (activeMatch && activeMatch.node.rowIndex == null) {
const node = activeMatch.node;
let parent = node.footer ? node.sibling : node.parent;
while (parent && parent.level !== -1) {
parent.expanded = true;
parent = parent.parent;
}
this.activeMatch = activeMatch;
this.scrollOnRefresh = true;
this.beans.expansionSvc?.onGroupExpandedOrCollapsed();
return;
}
const oldActiveMatch = this.activeMatch;
this.activeMatch = activeMatch;
this.refreshAndScrollToActive(activeMatch, oldActiveMatch);
if (activeMatch) {
this.setDetailActive(activeMatch);
}
this.dispatchFindChanged();
}
setDetailActive({ node, numInMatch }) {
if (node.detail) {
node.detailGridInfo?.api?.findGoTo(numInMatch);
}
}
refreshAndScrollToActive(activeMatch, oldActiveMatch) {
if (activeMatch || oldActiveMatch) {
const nodes = /* @__PURE__ */ new Set();
const columns = /* @__PURE__ */ new Set();
let skipColumns = false;
const addMatch = (match) => {
if (!match) {
return;
}
const { node, column } = match;
nodes.add(node);
if (column == null) {
skipColumns = true;
} else {
columns.add(column);
}
};
addMatch(activeMatch);
addMatch(oldActiveMatch);
this.refreshRows(nodes, skipColumns ? void 0 : columns);
}
if (activeMatch) {
this.scrollToActive(activeMatch);
}
}
scrollToActive({ node: { rowPinned, rowIndex }, column }) {
const { ctrlsSvc, pagination, gos } = this.beans;
const scrollFeature = ctrlsSvc.getScrollFeature();
if (rowPinned == null && rowIndex != null) {
if (pagination && !gos.get("findOptions")?.currentPageOnly && !pagination.isRowInPage(rowIndex)) {
pagination.goToPageWithIndex(rowIndex);
}
scrollFeature.ensureIndexVisible(rowIndex);
}
scrollFeature.ensureColumnVisible(column);
}
// search for the specified overall `match` number with the provided container, and set it to be active
goToInContainer(matches, match, startNum) {
let currentMatch = startNum;
for (const node of matches.keys()) {
const cols = matches.get(node);
for (const [column, numMatches] of cols) {
if (match <= currentMatch + numMatches) {
this.setActive({
column,
node,
numInMatch: match - currentMatch,
numOverall: match
});
return;
}
currentMatch += numMatches;
}
}
}
getMatches(rowPinned) {
if (rowPinned === "top") {
return this.topMatches;
} else if (rowPinned === "bottom") {
return this.bottomMatches;
} else {
return this.centerMatches;
}
}
getRowNodes(rowPinned) {
if (rowPinned === "top") {
return this.topNodes;
} else if (rowPinned === "bottom") {
return this.bottomNodes;
} else {
return this.centerNodes;
}
}
getActiveMatchNum(node, column) {
const activeMatch = this.activeMatch;
return activeMatch != null && activeMatch.node === node && activeMatch.column === column ? activeMatch.numInMatch : 0;
}
destroy() {
this.topMatches.clear();
this.topNodes.length = 0;
this.centerMatches.clear();
this.centerNodes.length = 0;
this.bottomMatches.clear();
this.bottomNodes.length = 0;
this.activeMatch = void 0;
super.destroy();
}
};
// packages/ag-grid-enterprise/src/find/findModule.ts
var FindCoreModule = {
moduleName: "FindCore",
version: VERSION,
rowModels: ["clientSide"],
beans: [FindService],
userComponents: {
agFindCellRenderer: FindCellRenderer
},
css: [findCSS]
};
var FindModule = {
moduleName: "Find",
version: VERSION,
apiFunctions: {
findGetTotalMatches,
findGoTo,
findNext,
findPrevious,
findGetActiveMatch,
findGetNumMatches,
findGetParts,
findClearActive,
findRefresh
},
dependsOn: [FindCoreModule]
};
// packages/ag-grid-enterprise/src/batch-edit/batchEditModule.ts
var import_ag_grid_community218 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/batch-edit/batchEditApi.ts
var import_ag_grid_community217 = require("ag-grid-community");
function startBatchEdit({ editSvc, gos, rowModel }) {
if (!editSvc?.isBatchEditing()) {
if (!(0, import_ag_grid_community217._isClientSideRowModel)(gos, rowModel)) {
(0, import_ag_grid_community217._warn)(289, { rowModelType: gos.get("rowModelType") });
return;
}
editSvc?.setBatchEditing(true);
}
}
function cancelBatchEdit({ editSvc }) {
if (!editSvc?.isBatchEditing()) {
return;
}
editSvc?.stopEditing(void 0, { cancel: true, source: "api" });
editSvc?.setBatchEditing(false);
}
function commitBatchEdit({ editSvc }) {
if (!editSvc?.isBatchEditing()) {
return;
}
editSvc?.stopEditing(void 0, { source: "api" });
editSvc?.setBatchEditing(false);
}
function isBatchEditing(beans) {
return beans.editSvc?.isBatchEditing() ?? false;
}
// packages/ag-grid-enterprise/src/batch-edit/batchEditModule.ts
var BatchEditModule = {
moduleName: "BatchEdit",
version: VERSION,
beans: [],
apiFunctions: {
isBatchEditing,
startBatchEdit,
cancelBatchEdit,
commitBatchEdit
},
dependsOn: [import_ag_grid_community218._EditCoreModule, EnterpriseCoreModule],
css: []
};
// packages/ag-grid-enterprise/src/charts/integratedChartsModule.ts
var import_ag_grid_community291 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/agChartsExports.ts
var import_ag_grid_community219 = require("ag-grid-community");
var AgChartsExports = class extends import_ag_grid_community219.BeanStub {
constructor(params) {
super();
this.beanName = "agChartsExports";
this.isEnterprise = false;
this.create = params.create;
this._Theme = params._Theme;
this._Scene = params._Scene;
this.isEnterprise = params.isEnterprise;
this._Util = params._Util;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/enterpriseChartProxyFactory.ts
var import_ag_grid_community226 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/utils/integration.ts
function deproxy(chartOrProxy) {
if (chartOrProxy.chart != null) {
return chartOrProxy.chart;
}
return chartOrProxy;
}
// packages/ag-grid-enterprise/src/charts/chartComp/utils/object.ts
var SKIP_JS_BUILTINS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
function get(source, expression, defaultValue) {
if (source == null) {
return defaultValue;
}
const keys = expression.split(".");
let objectToRead = source;
while (keys.length > 1) {
objectToRead = objectToRead[keys.shift()];
if (objectToRead == null) {
return defaultValue;
}
}
const value = objectToRead[keys[0]];
return value != null ? value : defaultValue;
}
function set(target, expression, value) {
if (target == null) {
return;
}
const keys = expression.split(".");
let objectToUpdate = target;
keys.filter((key) => !SKIP_JS_BUILTINS.has(key)).forEach((key, i) => {
if (!objectToUpdate[key]) {
objectToUpdate[key] = {};
}
if (i < keys.length - 1) {
objectToUpdate = objectToUpdate[key];
}
});
objectToUpdate[keys[keys.length - 1]] = value;
}
// packages/ag-grid-enterprise/src/charts/chartComp/utils/seriesTypeMapper.ts
var CHART_TYPE_TO_SERIES_TYPE = {
column: "bar",
groupedColumn: "bar",
stackedColumn: "bar",
normalizedColumn: "bar",
bar: "bar",
groupedBar: "bar",
stackedBar: "bar",
normalizedBar: "bar",
line: "line",
stackedLine: "line",
normalizedLine: "line",
scatter: "scatter",
bubble: "bubble",
pie: "pie",
donut: "donut",
doughnut: "donut",
area: "area",
stackedArea: "area",
normalizedArea: "area",
histogram: "histogram",
radarLine: "radar-line",
radarArea: "radar-area",
nightingale: "nightingale",
radialColumn: "radial-column",
radialBar: "radial-bar",
sunburst: "sunburst",
rangeBar: "range-bar",
rangeArea: "range-area",
boxPlot: "box-plot",
treemap: "treemap",
heatmap: "heatmap",
waterfall: "waterfall",
funnel: "funnel",
coneFunnel: "cone-funnel",
pyramid: "pyramid"
};
var COMBO_CHART_TYPES = /* @__PURE__ */ new Set(["columnLineCombo", "areaColumnCombo", "customCombo"]);
var SERIES_GROUP_TYPES = ["grouped", "stacked", "normalized"];
var SERIES_TYPES = {
area: {
isCartesian: true,
canInvert: true
},
bar: {
isCartesian: true,
canInvert: true
},
histogram: {
isCartesian: true
},
line: {
isCartesian: true,
canInvert: true
},
pie: {
isPie: true
},
donut: {
isPie: true,
canInvert: true
},
scatter: {
isCartesian: true
},
bubble: {
isCartesian: true
},
"radial-column": {
isPolar: true,
isEnterprise: true,
isRadial: true,
canInvert: true
},
"radial-bar": {
isPolar: true,
isEnterprise: true,
isRadial: true,
canInvert: true
},
"radar-line": {
isPolar: true,
isEnterprise: true,
canInvert: true
},
"radar-area": {
isPolar: true,
isEnterprise: true,
canInvert: true
},
nightingale: {
isPolar: true,
isEnterprise: true,
canInvert: true
},
"range-bar": {
isCartesian: true,
isEnterprise: true,
canSwitchDirection: true
},
"range-area": {
isCartesian: true,
isEnterprise: true
},
"box-plot": {
isCartesian: true,
isEnterprise: true,
canSwitchDirection: true
},
treemap: {
isEnterprise: true,
isHierarchical: true
},
sunburst: {
isEnterprise: true,
isHierarchical: true
},
heatmap: {
isCartesian: true,
isEnterprise: true
},
waterfall: {
isCartesian: true,
isEnterprise: true,
canSwitchDirection: true
},
funnel: {
isCartesian: true,
isEnterprise: true,
canSwitchDirection: true
},
"cone-funnel": {
isCartesian: true,
isEnterprise: true,
canSwitchDirection: true
},
pyramid: {
isCartesian: true,
isEnterprise: true,
canSwitchDirection: true
}
};
function isSeriesType(seriesType) {
return !!SERIES_TYPES[seriesType];
}
function isComboChart(chartType) {
return COMBO_CHART_TYPES.has(chartType);
}
function doesSeriesHaveProperty(seriesType, prop) {
return !!SERIES_TYPES[seriesType]?.[prop];
}
function isEnterpriseChartType(chartType) {
return doesSeriesHaveProperty(getSeriesType(chartType), "isEnterprise");
}
var stackedChartTypes = /* @__PURE__ */ new Set(["stackedColumn", "normalizedColumn", "stackedBar", "normalizedBar"]);
function isStacked(chartType) {
return stackedChartTypes.has(chartType);
}
function isCartesian(seriesType) {
return doesSeriesHaveProperty(seriesType, "isCartesian");
}
function isFunnel(seriesType) {
return seriesType === "funnel" || seriesType === "cone-funnel" || seriesType === "pyramid";
}
function isPolar(seriesType) {
return doesSeriesHaveProperty(seriesType, "isPolar");
}
function isRadial(seriesType) {
return doesSeriesHaveProperty(seriesType, "isRadial");
}
function isHierarchical(seriesType) {
return doesSeriesHaveProperty(seriesType, "isHierarchical");
}
function getCanonicalChartType(chartType) {
return chartType === "doughnut" ? "donut" : chartType;
}
function getSeriesTypeIfExists(chartType) {
return CHART_TYPE_TO_SERIES_TYPE[chartType];
}
function getSeriesType(chartType) {
return getSeriesTypeIfExists(chartType) ?? "line";
}
function isPieChartSeries(seriesType) {
return doesSeriesHaveProperty(seriesType, "isPie");
}
function canOnlyHaveSingleSeries(chartType) {
return chartType === "pie" || chartType === "waterfall" || chartType === "histogram" || chartType === "funnel" || chartType === "coneFunnel" || chartType === "pyramid";
}
function getMaxNumCategories(chartType) {
return isHierarchical(getSeriesType(chartType)) ? void 0 : 1;
}
function getMaxNumSeries(chartType) {
if (isHierarchical(getSeriesType(chartType))) {
return 2;
} else if (canOnlyHaveSingleSeries(chartType)) {
return 1;
} else {
return void 0;
}
}
function supportsInvertedCategorySeries(chartType) {
return !isComboChart(chartType) && doesSeriesHaveProperty(getSeriesType(chartType), "canInvert");
}
function canSwitchDirection(chartType) {
return doesSeriesHaveProperty(getSeriesType(chartType), "canSwitchDirection");
}
function getFullChartNameTranslationKey(chartType) {
switch (chartType) {
case "groupedColumn":
case "stackedColumn":
case "normalizedColumn":
case "groupedBar":
case "stackedBar":
case "normalizedBar":
case "stackedLine":
case "normalizedLine":
case "stackedArea":
case "normalizedArea":
return `${chartType}Full`;
case "doughnut":
return "donut";
case "areaColumnCombo":
return "AreaColumnCombo";
default:
return chartType;
}
}
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/chartTheme.ts
var import_ag_grid_community220 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/utils/axisTypeMapper.ts
var ALL_AXIS_TYPES = ["number", "category", "grouped-category", "log", "time"];
function getLegacyAxisType(chartType) {
switch (chartType) {
case "bar":
case "stackedBar":
case "normalizedBar":
return ["number", "category"];
case "groupedBar":
return ["number", "grouped-category"];
case "column":
case "stackedColumn":
case "normalizedColumn":
case "line":
case "stackedLine":
case "normalizedLine":
case "area":
case "stackedArea":
case "normalizedArea":
case "histogram":
return ["category", "number"];
case "groupedColumn":
return ["grouped-category", "number"];
case "scatter":
case "bubble":
return ["number", "number"];
default:
return void 0;
}
}
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/chartTheme.ts
function createAgChartTheme(chartProxyParams, proxy, isEnterprise, chartThemeDefaults, updatedOverrides) {
const { chartOptionsToRestore, chartPaletteToRestore, chartThemeToRestore, agChartsExports } = chartProxyParams;
const themeName = getSelectedTheme(chartProxyParams);
const stockTheme = isStockTheme(themeName, agChartsExports._Theme);
const rootTheme = stockTheme ? { baseTheme: themeName } : lookupCustomChartTheme(chartProxyParams, themeName) ?? {};
const gridOptionsThemeOverrides = chartProxyParams.getGridOptionsChartThemeOverrides();
const apiThemeOverrides = chartProxyParams.apiChartThemeOverrides;
const standaloneChartType = getSeriesType(chartProxyParams.chartType);
const crossFilteringOverrides = chartProxyParams.crossFiltering ? createCrossFilterThemeOverrides(proxy, chartProxyParams, standaloneChartType) : void 0;
const isTitleEnabled = () => {
const isTitleEnabled2 = (obj) => {
if (!obj) {
return false;
}
return Object.keys(obj).some((key) => get(obj[key], "title.enabled", false));
};
return isTitleEnabled2(gridOptionsThemeOverrides) || isTitleEnabled2(apiThemeOverrides);
};
const overrides = [
stockTheme ? inbuiltStockThemeOverrides(chartProxyParams, isEnterprise, isTitleEnabled()) : void 0,
pieAndDonutOverrides(),
chartThemeDefaults,
crossFilteringOverrides,
gridOptionsThemeOverrides,
apiThemeOverrides,
{ ...chartOptionsToRestore ?? {} },
updatedOverrides
];
const theme = overrides.filter((v) => !!v).reduce(
(r, n) => ({
baseTheme: r,
overrides: n
}),
rootTheme
);
if (chartPaletteToRestore && themeName === chartThemeToRestore) {
const rootThemePalette = chartProxyParams.agChartsExports._Theme.getChartTheme(rootTheme).palette;
if (!isIdenticalPalette(chartPaletteToRestore, rootThemePalette)) {
theme.palette = chartPaletteToRestore;
}
}
return theme;
}
function isIdenticalPalette(paletteA, paletteB) {
const arrayCompare = (arrA, arrB) => {
if (arrA === arrB)
return true;
if (arrA?.length !== arrB?.length)
return false;
return arrA?.every((v, i) => v === arrB?.[i]) ?? false;
};
return arrayCompare(paletteA.fills, paletteB.fills) && arrayCompare(paletteA.strokes, paletteB.strokes);
}
function isStockTheme(themeName, theme) {
return Object.keys(theme.themes).includes(themeName);
}
function createCrossFilterThemeOverrides(proxy, chartProxyParams, seriesType) {
const legend = {
listeners: {
legendItemClick: (e) => {
const chart = proxy.getChart();
const eligibleSeriesIds = [e.seriesId, `${e.seriesId}-filtered-out`];
chart.series.filter((s) => eligibleSeriesIds.includes(s.id)).forEach((s) => s.toggleSeriesItem(void 0, "category", e.itemId, void 0));
}
}
};
const common = {
tooltip: {
delay: 500
},
legend,
listeners: {
click: (e) => chartProxyParams.crossFilterCallback(e, true)
}
};
if (seriesType === "pie" || seriesType === "donut") {
return {
[seriesType]: {
series: {
fills: {
$if: [
{ $eq: [{ $value: "$index" }, 0] },
{
$map: [
{ $mix: [{ $value: "$1" }, { $ref: "backgroundColor" }, 0.7] },
{ $palette: "fills" }
]
},
{ $palette: "fills" }
]
},
strokes: {
$if: [
{ $eq: [{ $value: "$index" }, 0] },
{
$map: [
{ $mix: [{ $value: "$1" }, { $ref: "backgroundColor" }, 0.7] },
{ $palette: "strokes" }
]
},
{ $palette: "strokes" }
]
}
},
...common
}
};
}
const fill = {};
if (seriesType !== "line") {
fill.fill = {
$if: [
{ $isEven: [{ $value: "$index" }] },
{ $palette: "fill" },
{
$mix: [
{
$path: ["../$prevIndex/fill", { $palette: "fill" }]
},
{ $ref: "backgroundColor" },
0.7
]
}
]
};
}
return {
[seriesType]: {
series: {
stroke: {
$if: [
{ $isEven: [{ $value: "$index" }] },
{ $palette: "stroke" },
{
$mix: [
{
$path: ["../$prevIndex/fill", { $palette: "stroke" }]
},
{ $ref: "backgroundColor" },
0.7
]
}
]
},
...fill
},
...common
}
};
}
var STATIC_INBUILT_STOCK_THEME_AXES_OVERRIDES = ALL_AXIS_TYPES.reduce(
(r, n) => ({ ...r, [n]: { title: { _enabledFromTheme: true } } }),
{}
);
function inbuiltStockThemeOverrides(params, isEnterprise, titleEnabled) {
const extraPadding = params.getExtraPaddingDirections();
return {
common: {
...isEnterprise ? { animation: { duration: 500 } } : void 0,
axes: STATIC_INBUILT_STOCK_THEME_AXES_OVERRIDES,
padding: {
// don't add extra padding when a title is present!
top: !titleEnabled && extraPadding.includes("top") ? 40 : 20,
right: extraPadding.includes("right") ? 30 : 20,
bottom: extraPadding.includes("bottom") ? 40 : 20,
left: extraPadding.includes("left") ? 30 : 20
}
}
};
}
function pieAndDonutOverrides() {
return {
pie: {
series: {
title: { _enabledFromTheme: true },
calloutLabel: { _enabledFromTheme: true },
sectorLabel: {
enabled: false,
_enabledFromTheme: true
}
}
},
donut: {
series: {
title: { _enabledFromTheme: true },
calloutLabel: { _enabledFromTheme: true },
sectorLabel: {
enabled: false,
_enabledFromTheme: true
}
}
}
};
}
function getSelectedTheme(chartProxyParams) {
let chartThemeName = chartProxyParams.getChartThemeName();
const availableThemes = chartProxyParams.getChartThemes();
if (!availableThemes.includes(chartThemeName)) {
chartThemeName = availableThemes[0];
}
return chartThemeName;
}
function lookupCustomChartTheme(chartProxyParams, name) {
const { customChartThemes } = chartProxyParams;
const customChartTheme = customChartThemes && customChartThemes[name];
if (!customChartTheme) {
(0, import_ag_grid_community220._warn)(140, { name });
}
return customChartTheme;
}
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/chartProxy.ts
var ChartProxy = class {
constructor(chartProxyParams) {
this.chartProxyParams = chartProxyParams;
this.clearThemeOverrides = false;
this.agChartsExports = chartProxyParams.agChartsExports;
this.chart = chartProxyParams.chartInstance;
this.chartType = chartProxyParams.chartType;
this.crossFiltering = chartProxyParams.crossFiltering;
this.crossFilterCallback = chartProxyParams.crossFilterCallback;
this.standaloneChartType = getSeriesType(this.chartType);
if (this.chart == null) {
this.chart = chartProxyParams.agChartsExports.create(this.getCommonChartOptions());
} else {
this.clearThemeOverrides = true;
}
}
crossFilteringReset() {
}
update(params) {
this.getChartRef().update(this.getUpdateOptions(params, this.getCommonChartOptions(params.updatedOverrides)));
}
updateThemeOverrides(themeOverrides) {
this.getChartRef().updateDelta({ theme: { overrides: themeOverrides } });
}
getChart() {
return deproxy(this.chart);
}
getChartRef() {
return this.chart;
}
downloadChart(dimensions, fileName, fileFormat) {
const { chart } = this;
const rawChart = deproxy(chart);
const imageFileName = fileName || rawChart.title.node.getPlainText();
const { width, height } = dimensions || {};
chart.download({ width, height, fileName: imageFileName, fileFormat });
}
getChartImageDataURL(type) {
return this.getChart().getCanvasDataURL(type);
}
getChartOptions() {
return this.chart.getOptions();
}
getChartThemeOverrides() {
const chartOptionsTheme = this.getChartOptions().theme;
return chartOptionsTheme.overrides ?? {};
}
getChartPalette() {
return this.agChartsExports._Theme.getChartTheme(this.getChartOptions().theme).palette;
}
setPaired(paired) {
const seriesType = getSeriesType(this.chartProxyParams.chartType);
this.chart.updateDelta({ theme: { overrides: { [seriesType]: { paired } } } });
}
isPaired() {
const seriesType = getSeriesType(this.chartProxyParams.chartType);
return get(this.getChartThemeOverrides(), `${seriesType}.paired`, true);
}
lookupCustomChartTheme(themeName) {
return lookupCustomChartTheme(this.chartProxyParams, themeName);
}
getSeriesGroupType() {
return void 0;
}
transformCategoryData(data, categoryKey) {
return data.map((d, index) => {
const value = d[categoryKey];
const valueString = value && value.toString ? value.toString() : "";
const datum = { ...d };
datum[categoryKey] = { id: index, value, toString: () => valueString };
return datum;
});
}
getCommonChartOptions(updatedOverrides) {
const existingOptions = this.clearThemeOverrides ? {} : this.chart?.getOptions() ?? {};
const formattingPanelOverrides = this.chart != null ? this.getActiveFormattingPanelOverrides() : void 0;
this.clearThemeOverrides = false;
const styleNonce = this.chartProxyParams.styleNonce;
const theme = createAgChartTheme(
this.chartProxyParams,
this,
this.agChartsExports.isEnterprise,
this.getChartThemeDefaults(),
updatedOverrides ?? formattingPanelOverrides
);
const newOptions = {
...existingOptions,
mode: "integrated",
...styleNonce ? { styleNonce } : {}
};
if (this.chartProxyParams.suppressFieldDotNotation !== void 0) {
newOptions.suppressFieldDotNotation = this.chartProxyParams.suppressFieldDotNotation;
}
newOptions.theme = theme;
newOptions.container = this.chartProxyParams.parentElement;
return newOptions;
}
getChartThemeDefaults() {
const seriesOverrides = this.getSeriesChartThemeDefaults();
const seriesChartOptions = seriesOverrides ? {
[this.standaloneChartType]: seriesOverrides
} : {};
const crosshair = {
enabled: true,
snap: true,
label: {
enabled: false
}
};
const common = this.agChartsExports.isEnterprise ? {
zoom: {
enabled: true
},
animation: {
enabled: true,
duration: 500
},
axes: {
number: { crosshair },
category: { crosshair },
log: { crosshair },
time: { crosshair }
}
} : {};
common.minHeight = 0;
common.minWidth = 0;
common.navigator = {
enabled: false,
height: 18
};
common.context = this.chartProxyParams.context;
return {
common,
...seriesChartOptions
};
}
getSeriesChartThemeDefaults() {
return void 0;
}
getActiveFormattingPanelOverrides() {
if (this.clearThemeOverrides) {
return {};
}
const inUseTheme = this.chart?.getOptions().theme;
return inUseTheme?.overrides ?? {};
}
destroy({ keepChartInstance = false } = {}) {
if (keepChartInstance) {
this.chart.resetAnimations();
return this.chart;
}
this.destroyChart();
}
destroyChart() {
if (this.chart) {
this.chart.destroy();
this.chart = void 0;
}
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/cartesian/cartesianChartProxy.ts
var CartesianChartProxy = class extends ChartProxy {
constructor() {
super(...arguments);
this.crossFilteringAllPoints = /* @__PURE__ */ new Set();
this.crossFilteringSelectedPoints = [];
}
getUpdateOptions(params, commonChartOptions) {
const axes = this.getAxes(params, commonChartOptions);
return {
...commonChartOptions,
data: this.getData(params, axes),
axes,
series: this.getSeries(params)
};
}
getData(params, axes) {
const supportsCrossFiltering = ["area", "line"].includes(this.standaloneChartType);
return this.crossFiltering && supportsCrossFiltering ? this.getCrossFilterData(params) : this.getDataTransformedData(params, axes);
}
getDataTransformedData(params, axes) {
const xAxisType = axes[0].type;
const { categories, data } = params;
const [category] = categories;
switch (xAxisType) {
case "category":
return this.transformCategoryData(data, category.id);
case "time":
return this.transformTimeData(data, category.id);
default:
return data;
}
}
getXAxisType(params) {
if (params.grouping) {
return "grouped-category";
} else if (this.isXAxisOfType(params, "time", (value) => value instanceof Date)) {
return "time";
} else if (this.isXAxisOfType(params, "number")) {
return "number";
}
return "category";
}
isXAxisOfType(params, type, isInstance) {
const [category] = params.categories;
if (category?.chartDataType) {
return category.chartDataType === type;
}
if (!isInstance) {
return false;
}
const testDatum = params.data[0];
if (!testDatum) {
return false;
}
return isInstance(testDatum[category.id]);
}
transformTimeData(data, categoryKey) {
const firstValue = data[0]?.[categoryKey];
if (firstValue instanceof Date) {
return data;
}
return data.map((datum) => {
const value = datum[categoryKey];
return typeof value === "string" ? {
...datum,
[categoryKey]: new Date(value)
} : datum;
});
}
crossFilteringReset() {
this.crossFilteringSelectedPoints = [];
this.crossFilteringAllPoints.clear();
}
crossFilteringPointSelected(point) {
return this.crossFilteringSelectedPoints.length == 0 || this.crossFilteringSelectedPoints.includes(point);
}
crossFilteringDeselectedPoints() {
return this.crossFilteringSelectedPoints.length > 0 && this.crossFilteringAllPoints.size !== this.crossFilteringSelectedPoints.length;
}
extractLineAreaCrossFilterSeries(series, params) {
const [category] = params.categories;
const getYKey = (yKey) => {
if (this.standaloneChartType === "area") {
const lastSelectedChartId = params.getCrossFilteringContext().lastSelectedChartId;
return lastSelectedChartId === params.chartId ? yKey + "-total" : yKey;
}
return yKey + "-total";
};
return series.map((s) => {
s.yKey = getYKey(s.yKey);
s.listeners = {
seriesNodeClick: (e) => {
const value = e.datum[s.xKey];
const multiSelection = e.event.metaKey || e.event.ctrlKey;
this.crossFilteringAddSelectedPoint(multiSelection, value);
this.crossFilterCallback(e);
}
};
s.marker = {
itemStyler: (p) => {
const value = p.datum[category.id];
return {
fill: p.highlighted ? "yellow" : p.fill,
size: p.highlighted ? 14 : this.crossFilteringPointSelected(value) ? 8 : 0
};
}
};
if (this.standaloneChartType === "area") {
s.fillOpacity = this.crossFilteringDeselectedPoints() ? 0.3 : 1;
}
if (this.standaloneChartType === "line") {
s.strokeOpacity = this.crossFilteringDeselectedPoints() ? 0.3 : 1;
}
return s;
});
}
getCrossFilterData(params) {
this.crossFilteringAllPoints.clear();
const [category] = params.categories;
const colId = params.fields[0].colId;
const filteredOutColId = `${colId}-filtered-out`;
const lastSelectedChartId = params.getCrossFilteringContext().lastSelectedChartId;
return params.data.map((d) => {
const value = d[category.id];
this.crossFilteringAllPoints.add(value);
const pointSelected = this.crossFilteringPointSelected(value);
if (this.standaloneChartType === "area" && lastSelectedChartId === params.chartId) {
d[`${colId}-total`] = pointSelected ? d[colId] : d[colId] + d[filteredOutColId];
}
if (this.standaloneChartType === "line") {
d[`${colId}-total`] = pointSelected ? d[colId] : d[colId] + d[filteredOutColId];
}
return d;
});
}
crossFilteringAddSelectedPoint(multiSelection, value) {
multiSelection ? this.crossFilteringSelectedPoints.push(value) : this.crossFilteringSelectedPoints = [value];
}
isHorizontal(commonChartOptions) {
const seriesType = this.standaloneChartType;
if (seriesType !== "waterfall" && seriesType !== "box-plot" && seriesType !== "range-bar") {
return false;
}
const theme = commonChartOptions.theme;
const isHorizontal = (theme2) => {
const direction = theme2?.overrides?.[seriesType]?.series?.direction;
if (direction != null) {
return direction === "horizontal";
}
if (typeof theme2?.baseTheme === "object") {
return isHorizontal(theme2.baseTheme);
}
return false;
};
return isHorizontal(theme);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/cartesian/histogramChartProxy.ts
var HistogramChartProxy = class extends CartesianChartProxy {
getSeries(params) {
const firstField = params.fields[0];
return [
{
type: this.standaloneChartType,
xKey: firstField.colId,
xName: firstField.displayName,
yName: this.chartProxyParams.translate("histogramFrequency"),
areaPlot: false
// only constant width is supported via integrated charts
}
];
}
getAxes(_params) {
return [
{
type: "number",
position: "bottom"
},
{
type: "number",
position: "left"
}
];
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/cartesian/waterfallChartProxy.ts
var WaterfallChartProxy = class extends CartesianChartProxy {
getAxes(params, commonChartOptions) {
return [
{
type: this.getXAxisType(params),
position: this.isHorizontal(commonChartOptions) ? "left" : "bottom"
},
{
type: "number",
position: this.isHorizontal(commonChartOptions) ? "bottom" : "left"
}
];
}
getSeries(params) {
const [category] = params.categories;
const [firstField] = params.fields;
const firstSeries = {
type: this.standaloneChartType,
xKey: category.id,
xName: category.name,
yKey: firstField.colId,
yName: firstField.displayName ?? void 0
};
return [firstSeries];
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/funnel/funnelChartProxy.ts
var FunnelChartProxy = class extends ChartProxy {
getUpdateOptions(params, commonChartOptions) {
return {
...commonChartOptions,
data: this.transformFunnelCategories(params),
series: this.getSeries(params)
};
}
transformFunnelCategories(params) {
const { data } = params;
const [{ id }] = params.categories;
return data.map((d, index) => ({
...d,
[id]: {
name: d[id],
id: index,
toString: () => d[id]
}
}));
}
getSeriesChartThemeDefaults() {
const config = {
crosshair: {
enabled: false
}
};
return {
zoom: {
enabled: false
},
...this.chartType !== "pyramid" && {
axes: {
category: config,
number: config
}
}
};
}
getSeries(params) {
const [{ id }] = params.categories;
const [{ colId }] = params.fields;
const series = {
type: this.standaloneChartType,
stageKey: id,
valueKey: colId
};
return [series];
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/hierarchical/hierarchicalChartProxy.ts
var import_ag_grid_community221 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/hierarchical/hierarchicalChartUtils.ts
var CATEGORY_LABEL_KEY = "AG-GRID-DEFAULT-LABEL-KEY";
function createCategoryHierarchy(data, categoryKeys) {
const hierarchy = buildNestedHierarchy(data, getItemDepth, getItemCategoryLabel);
return formatCategoryHierarchy(hierarchy);
function getItemDepth(_item) {
return categoryKeys.length;
}
function getItemCategoryLabel(item, categoryIndex) {
const categoryKey = categoryKeys[categoryIndex];
const categoryValue = item[categoryKey];
return getCategoryLabel(categoryValue);
}
function getCategoryLabel(value) {
if (value == null)
return null;
return String(value);
}
}
function createAutoGroupHierarchy(data, getItemLabels) {
const hierarchy = buildNestedHierarchy(data, getItemDepth, getItemGroupLabel);
return formatCategoryHierarchy(hierarchy);
function getItemDepth(item) {
return getItemLabels(item)?.length ?? 0;
}
function getItemGroupLabel(item, groupIndex) {
const labels2 = getItemLabels(item);
if (!labels2)
return null;
const labelIndex = labels2.length - 1 - groupIndex;
return labels2[labelIndex];
}
}
function formatCategoryHierarchy(hierarchy, key = null, isChild) {
const { depth, rootValues, value, children: inputChildren } = hierarchy;
if (rootValues) {
return rootValues.map((item) => ({ [CATEGORY_LABEL_KEY]: key, ...item }));
} else if (depth === 0) {
return [{ [CATEGORY_LABEL_KEY]: key, ...value }];
}
const children = [];
for (const [childKey, childHierarchy] of inputChildren.entries()) {
children.push(...formatCategoryHierarchy(childHierarchy, childKey, true));
}
return isChild ? [
{
[CATEGORY_LABEL_KEY]: key,
children,
...value ?? {}
}
] : children;
}
function buildNestedHierarchy(data, getItemDepth, getItemGroupKey) {
const hierarchy = { depth: 0, children: /* @__PURE__ */ new Map() };
data.forEach((item) => {
const itemDepth = getItemDepth(item);
createNestedItemHierarchy(item, itemDepth, getItemGroupKey, 0, hierarchy);
});
return hierarchy;
function createNestedItemHierarchy(item, itemDepth, getItemGroupKey2, currentDepth, hierarchy2) {
if (currentDepth === itemDepth) {
if (currentDepth === 0) {
if (!hierarchy2.rootValues) {
hierarchy2.rootValues = [];
}
hierarchy2.rootValues.push(item);
} else {
hierarchy2.value = item;
}
return hierarchy2;
} else {
const key = getItemGroupKey2(item, currentDepth);
const existingChildHierarchy = hierarchy2.children.get(key);
const childHierarchy = createNestedItemHierarchy(
item,
itemDepth,
getItemGroupKey2,
currentDepth + 1,
existingChildHierarchy || { depth: 0, children: /* @__PURE__ */ new Map() }
);
hierarchy2.children.set(key, childHierarchy);
hierarchy2.depth = Math.max(1 + childHierarchy.depth, hierarchy2.depth);
return hierarchy2;
}
}
}
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/hierarchical/hierarchicalChartProxy.ts
var HierarchicalChartProxy = class extends ChartProxy {
getUpdateOptions(params, commonChartOptions) {
const { fields } = params;
const [sizeField, colorField] = fields;
return {
...commonChartOptions,
series: this.getSeries(sizeField, colorField),
data: this.getData(params, sizeField, colorField)
};
}
getSeriesChartThemeDefaults() {
return {
gradientLegend: {
gradient: {
preferredLength: 200
},
position: "right"
}
};
}
getSeries(sizeField, colorField) {
return [
{
type: this.standaloneChartType,
labelKey: CATEGORY_LABEL_KEY,
// Size and color fields are inferred from the range data
sizeKey: sizeField?.colId,
sizeName: sizeField?.displayName ?? void 0,
colorKey: colorField?.colId,
colorName: colorField?.displayName ?? void 0
}
];
}
getData(params, sizeField, colorField) {
const { categories, data, groupData, grouping: isGrouped } = params;
if (isGrouped) {
const processedData = colorField ? data.concat(
groupData?.map((groupDatum) => {
const newDatum = { ...groupDatum };
delete newDatum[sizeField.colId];
return newDatum;
}) ?? []
) : data;
return createAutoGroupHierarchy(processedData, (item) => item[import_ag_grid_community221.GROUP_AUTO_COLUMN_ID]?.labels ?? null);
} else {
const categoryKeys = categories.map(({ id }) => id);
return createCategoryHierarchy(data, categoryKeys);
}
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/polar/polarChartProxy.ts
var PolarChartProxy = class extends ChartProxy {
getAxes(_) {
const radialBar = this.standaloneChartType === "radial-bar";
return [
{ type: radialBar ? "angle-number" : "angle-category" },
{ type: radialBar ? "radius-category" : "radius-number" }
];
}
getSeries(params) {
const { fields, categories, seriesGroupType } = params;
const [category] = categories;
const radialBar = this.standaloneChartType === "radial-bar";
const seriesGroupTypeOptions = this.getSeriesGroupTypeOptions(seriesGroupType);
return fields.map((f) => ({
type: this.standaloneChartType,
angleKey: radialBar ? f.colId : category.id,
angleName: radialBar ? f.displayName ?? void 0 : category.name,
radiusKey: radialBar ? category.id : f.colId,
radiusName: radialBar ? category.name : f.displayName ?? void 0,
...seriesGroupTypeOptions
}));
}
getSeriesGroupType() {
const standaloneChartType = this.standaloneChartType;
if (!["nightingale", "radial-bar", "radial-column"].includes(standaloneChartType)) {
return void 0;
}
const firstSeriesProperties = this.getChart().series?.[0]?.properties.toJson();
const getStackedValue = () => firstSeriesProperties.normalizedTo ? "normalized" : "stacked";
if (standaloneChartType === "nightingale") {
return firstSeriesProperties.grouped ? "grouped" : getStackedValue();
} else {
return firstSeriesProperties.stacked ? getStackedValue() : "grouped";
}
}
getUpdateOptions(params, commonChartOptions) {
const axes = this.getAxes(params);
return {
...commonChartOptions,
data: this.getData(params, axes),
axes,
series: this.getSeries(params)
};
}
getData(params, axes) {
const isCategoryAxis = axes.some((axis) => axis.type === "angle-category" || axis.type === "radius-category");
if (isCategoryAxis) {
const [category] = params.categories;
return this.transformCategoryData(params.data, category.id);
} else {
return params.data;
}
}
getSeriesGroupTypeOptions(seriesGroupType) {
if (!seriesGroupType) {
return {};
}
return {
grouped: seriesGroupType === "grouped" || void 0,
stacked: seriesGroupType !== "grouped" || void 0,
normalizedTo: seriesGroupType === "normalized" ? 100 : void 0
};
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/specialized/heatmapChartProxy.ts
var HEATMAP_CATEGORY_KEY = "AG-GRID-DEFAULT-HEATMAP-CATEGORY-KEY";
var HEATMAP_SERIES_KEY = "AG-GRID-DEFAULT-HEATMAP-SERIES-KEY";
var HEATMAP_VALUE_KEY = "AG-GRID-DEFAULT-HEATMAP-VALUE-KEY";
function flatMap(items, iteratee) {
return items.reduce((acc, item, index, array) => acc.concat(iteratee(item, index, array)), new Array());
}
var HeatmapChartProxy = class extends ChartProxy {
getUpdateOptions(params, commonChartOptions) {
const xSeriesKey = HEATMAP_SERIES_KEY;
const xValueKey = HEATMAP_VALUE_KEY;
const yKey = HEATMAP_CATEGORY_KEY;
return {
...commonChartOptions,
series: this.getSeries(params, xSeriesKey, xValueKey, yKey),
data: this.getData(params, xSeriesKey, xValueKey, yKey)
};
}
getSeries(params, xSeriesKey, xValueKey, yKey) {
const [category] = params.categories;
return [
{
type: this.standaloneChartType,
// The axis keys reference synthetic fields based on the category values and series column names
yKey,
xKey: xSeriesKey,
// The color key references a synthetic field based on the series column value for a specific cell
colorKey: xValueKey,
yName: category.name,
// We don't know how to label the 'x' series, as it is a synthetic series created from the set of all input columns
// In future releases we may want to consider inferring the series label from column groupings etc
xName: void 0,
colorName: void 0
}
];
}
getData(params, xSeriesKey, xValueKey, yKey) {
const [category] = params.categories;
return flatMap(params.data, (datum, index) => {
const value = datum[category.id];
const valueString = value == null ? "" : String(value);
const yValue = { id: index, value, toString: () => valueString };
return params.fields.map(({ colId, displayName }) => ({
...datum,
[xSeriesKey]: displayName,
[xValueKey]: datum[colId],
[yKey]: yValue
}));
});
}
getSeriesChartThemeDefaults() {
return {
gradientLegend: {
gradient: {
preferredLength: 200
},
position: "right"
},
series: {
tooltip: {
renderer: renderHeatmapTooltip
}
}
};
}
};
function renderHeatmapTooltip(params) {
const { xKey, yKey, colorKey, yName, datum } = params;
const table = [
{ label: yName, value: datum[yKey] },
{ label: datum[xKey], value: colorKey && datum[colorKey] }
];
return {
title: "",
data: table.map(({ label, value }) => ({ label: String(label), value: String(value) }))
};
}
// packages/ag-grid-enterprise/src/charts/chartComp/model/chartDataModel.ts
var import_ag_grid_community225 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/datasource/chartDatasource.ts
var import_ag_grid_community222 = require("ag-grid-community");
var ChartDatasource = class extends import_ag_grid_community222.BeanStub {
wireBeans(beans) {
this.sortSvc = beans.sortSvc;
this.gridRowModel = beans.rowModel;
this.colModel = beans.colModel;
this.valueSvc = beans.valueSvc;
this.pivotResultCols = beans.pivotResultCols;
this.rowNodeSorter = beans.rowNodeSorter;
}
getData(params) {
if (params.crossFiltering) {
if (params.grouping) {
(0, import_ag_grid_community222._warn)(141);
return { chartData: [], colNames: {} };
}
if (!(0, import_ag_grid_community222._isClientSideRowModel)(this.gos)) {
(0, import_ag_grid_community222._warn)(142);
return { chartData: [], colNames: {} };
}
}
const isServerSide = (0, import_ag_grid_community222._isServerSideRowModel)(this.gos);
if (isServerSide && params.pivoting) {
this.updatePivotKeysForSSRM();
}
const result = this.extractRowsFromGridRowModel(params);
result.chartData = this.aggregateRowsByDimension(params, result.chartData);
return result;
}
extractRowsFromGridRowModel(params) {
const { crossFiltering, startRow, endRow, valueCols, dimensionCols, grouping } = params;
let extractedRowData = [];
const colNames = {};
const groupNodeIndexes = {};
const groupsToRemove = {};
let filteredNodes = {};
let allRowNodes = [];
let numRows;
if (crossFiltering) {
filteredNodes = this.getFilteredRowNodes();
allRowNodes = this.getAllRowNodes();
numRows = allRowNodes.length;
} else {
const modelLastRow = this.gridRowModel.getRowCount() - 1;
const hasNoRange = startRow === endRow && startRow === 0 && dimensionCols.length === 0 && valueCols.length === 0;
if (hasNoRange) {
numRows = 0;
} else {
const rangeLastRow = endRow >= 0 ? Math.min(endRow, modelLastRow) : modelLastRow;
numRows = rangeLastRow - startRow + 1;
}
}
if (numRows > 0) {
valueCols.forEach((col) => {
let colNamesArr = [];
const pivotKeys = col.getColDef().pivotKeys;
if (pivotKeys) {
colNamesArr = pivotKeys.slice();
}
const headerName = col.getColDef().headerName;
if (headerName) {
colNamesArr.push(headerName);
}
if (colNamesArr.length > 0) {
colNames[col.getId()] = colNamesArr;
}
});
}
let numRemovedNodes = 0;
let id = 0;
const groupingCache = {};
for (let i = 0; i < numRows; i++) {
const rowNode = crossFiltering ? allRowNodes[i] : this.gridRowModel.getRow(i + startRow);
if (rowNode.footer || rowNode.detail) {
numRemovedNodes++;
continue;
}
const data = { node: rowNode };
dimensionCols.forEach((col) => {
const colId = col.colId;
const column = this.colModel.getCol(colId);
if (column) {
const valueObject = this.valueSvc.getValue(column, rowNode);
if (grouping) {
const valueString = valueObject?.toString ? String(valueObject.toString()) : " ";
const labels2 = this.getGroupLabels(rowNode, valueString);
const value = labels2.slice().reverse();
const groupingValue = {
value,
// this is needed so that standalone can handle animations properly when data updates
id: id++,
toString: () => value.filter(Boolean).join(" - ")
};
const groupingKey = groupingValue.toString();
const cachedGroupingValue = groupingCache[groupingKey];
data[colId] = cachedGroupingValue ? cachedGroupingValue : groupingCache[groupingKey] = groupingValue;
if (rowNode.group) {
groupNodeIndexes[labels2.toString()] = i - numRemovedNodes;
}
const groupKey = labels2.slice(1, labels2.length).toString();
if (groupKey) {
groupsToRemove[groupKey] = groupNodeIndexes[groupKey];
}
} else {
data[colId] = valueObject;
}
} else {
data[DEFAULT_CHART_CATEGORY] = i + 1;
}
});
valueCols.forEach((col) => {
const colId = col.getColId();
if (crossFiltering) {
const filteredOutColId = colId + "-filtered-out";
const value = this.valueSvc.getValue(col, rowNode);
let actualValue = value;
if (value != null) {
if (typeof value.toNumber === "function") {
actualValue = value.toNumber();
} else if (typeof value.value === "number") {
actualValue = value.value;
}
}
if (filteredNodes[rowNode.id]) {
data[colId] = actualValue;
data[filteredOutColId] = params.aggFunc || params.isScatter ? void 0 : 0;
} else {
data[colId] = params.aggFunc || params.isScatter ? void 0 : 0;
data[filteredOutColId] = actualValue;
}
} else {
let value = this.valueSvc.getValue(col, rowNode);
if (value && typeof value.value === "number") {
value = value.value;
}
if (value && Object.prototype.hasOwnProperty.call(value, "toString")) {
value = parseFloat(value.toString());
}
data[colId] = value != null && typeof value.toNumber === "function" ? value.toNumber() : value;
}
});
extractedRowData.push(data);
}
let groupChartData;
if (grouping) {
const groupIndexesToRemove = Object.values(groupsToRemove);
const allData = extractedRowData;
extractedRowData = [];
groupChartData = [];
for (let i = 0; i < allData.length; i++) {
(groupIndexesToRemove.includes(i) ? groupChartData : extractedRowData).push(allData[i]);
}
}
return { chartData: extractedRowData, colNames, groupChartData };
}
aggregateRowsByDimension(params, dataFromGrid) {
const dimensionCols = params.dimensionCols;
if (!params.aggFunc || dimensionCols.length === 0) {
return dataFromGrid;
}
const lastCol = (0, import_ag_grid_community222._last)(dimensionCols);
const lastColId = lastCol && lastCol.colId;
const map = {};
const dataAggregated = [];
dataFromGrid.forEach((data) => {
let currentMap = map;
dimensionCols.forEach((col) => {
const colId = col.colId;
const key = data[colId];
if (colId === lastColId) {
let groupItem = currentMap[key];
if (!groupItem) {
groupItem = { __children: [] };
dimensionCols.forEach((dimCol) => {
const dimColId = dimCol.colId;
groupItem[dimColId] = data[dimColId];
});
currentMap[key] = groupItem;
dataAggregated.push(groupItem);
}
groupItem.__children.push(data);
} else {
if (!currentMap[key]) {
currentMap[key] = {};
}
currentMap = currentMap[key];
}
});
});
if (this.gos.assertModuleRegistered("SharedAggregation", 1)) {
dataAggregated.forEach(
(groupItem) => params.valueCols.forEach((col) => {
const colId = col.getColId();
if (params.crossFiltering) {
const dataToAgg = groupItem.__children.filter((child) => typeof child[colId] !== "undefined").map((child) => child[colId]);
const aggResult = _aggregateValues(this.beans, dataToAgg, params.aggFunc, col);
groupItem[colId] = aggResult && typeof aggResult.value !== "undefined" ? aggResult.value : aggResult;
const filteredOutColId = `${colId}-filtered-out`;
const dataToAggFiltered = groupItem.__children.filter((child) => typeof child[filteredOutColId] !== "undefined").map((child) => child[filteredOutColId]);
const aggResultFiltered = _aggregateValues(
this.beans,
dataToAggFiltered,
params.aggFunc,
col
);
groupItem[filteredOutColId] = aggResultFiltered && typeof aggResultFiltered.value !== "undefined" ? aggResultFiltered.value : aggResultFiltered;
} else {
const dataToAgg = groupItem.__children.map((child) => child[colId]);
const aggResult = _aggregateValues(this.beans, dataToAgg, params.aggFunc, col);
groupItem[colId] = aggResult && typeof aggResult.value !== "undefined" ? aggResult.value : aggResult;
}
})
);
}
return dataAggregated;
}
updatePivotKeysForSSRM() {
const secondaryColumns = this.pivotResultCols?.getPivotResultCols()?.list;
if (!secondaryColumns) {
return;
}
const pivotKeySeparator = this.extractPivotKeySeparator(secondaryColumns);
secondaryColumns.forEach((col) => {
if (pivotKeySeparator === "") {
col.getColDef().pivotKeys = [];
} else {
const keys = col.getColId().split(pivotKeySeparator);
col.getColDef().pivotKeys = keys.slice(0, keys.length - 1);
}
});
}
extractPivotKeySeparator(secondaryColumns) {
if (secondaryColumns.length === 0) {
return "";
}
const extractSeparator = (columnGroup, childId) => {
const groupId = columnGroup.getGroupId();
if (!columnGroup.getParent()) {
return childId.split(groupId)[1][0];
}
return extractSeparator(columnGroup.getParent(), groupId);
};
const firstSecondaryCol = secondaryColumns[0];
if (firstSecondaryCol.getParent() == null) {
return "";
}
return extractSeparator(firstSecondaryCol.getParent(), firstSecondaryCol.getColId());
}
getGroupLabels(rowNode, initialLabel) {
const labels2 = [initialLabel];
while (rowNode && rowNode.level !== 0) {
rowNode = rowNode.parent;
if (rowNode) {
if (rowNode.group) {
const groupColumn = this.colModel.getCol(import_ag_grid_community222.GROUP_AUTO_COLUMN_ID);
if (groupColumn) {
const valueObject = this.valueSvc.getValue(groupColumn, rowNode);
const valueString = valueObject?.toString ? String(valueObject.toString()) : " ";
labels2.push(valueString);
}
} else {
labels2.push(rowNode.key);
}
}
}
return labels2;
}
getFilteredRowNodes() {
const filteredNodes = {};
this.gridRowModel.forEachNodeAfterFilterAndSort((rowNode) => {
filteredNodes[rowNode.id] = rowNode;
});
return filteredNodes;
}
getAllRowNodes() {
const allRowNodes = [];
this.gridRowModel.forEachNode((rowNode) => {
allRowNodes.push(rowNode);
});
return this.sortRowNodes(allRowNodes);
}
sortRowNodes(rowNodes) {
const sortOptions = this.sortSvc?.getSortOptions();
if (!sortOptions || sortOptions.length == 0 || !this.rowNodeSorter) {
return rowNodes;
}
return this.rowNodeSorter.doFullSort(rowNodes, sortOptions);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/services/chartColumnService.ts
var import_ag_grid_community223 = require("ag-grid-community");
var ChartColumnService = class extends import_ag_grid_community223.BeanStub {
constructor() {
super(...arguments);
this.beanName = "chartColSvc";
this.valueColsWithoutSeriesType = /* @__PURE__ */ new Set();
}
wireBeans(beans) {
this.colModel = beans.colModel;
this.colNames = beans.colNames;
this.valueSvc = beans.valueSvc;
}
postConstruct() {
const clearValueCols = () => this.valueColsWithoutSeriesType.clear();
this.addManagedEventListeners({
newColumnsLoaded: clearValueCols,
rowDataUpdated: clearValueCols
});
}
getColumn(colId) {
return this.colModel.getColDefCol(colId);
}
getAllDisplayedColumns() {
return this.beans.visibleCols.allCols;
}
getColDisplayName(col, includePath) {
const headerLocation = "chart";
const columnDisplayName = this.colNames.getDisplayNameForColumn(col, headerLocation);
if (includePath) {
const displayNames = [columnDisplayName];
const getDisplayName2 = (colGroup) => {
if (!colGroup) {
return;
}
const colGroupName = this.colNames.getDisplayNameForColumnGroup(colGroup, headerLocation);
if (colGroupName?.length) {
displayNames.unshift(colGroupName);
getDisplayName2(colGroup.getParent());
}
};
getDisplayName2(col.getParent());
return displayNames.join(" - ");
}
return columnDisplayName;
}
getRowGroupColumns() {
return this.beans.rowGroupColsSvc?.columns ?? [];
}
getGroupDisplayColumns() {
return this.beans.showRowGroupCols?.getShowRowGroupCols() ?? [];
}
isPivotMode() {
return this.colModel.isPivotMode();
}
isPivotActive() {
return this.colModel.isPivotActive();
}
getChartColumns() {
const gridCols = this.colModel.getCols();
const dimensionCols = /* @__PURE__ */ new Set();
const valueCols = /* @__PURE__ */ new Set();
gridCols.forEach((col) => {
const colDef = col.getColDef();
const chartDataType = colDef.chartDataType;
if (chartDataType) {
switch (chartDataType) {
case "category":
case "time":
dimensionCols.add(col);
return;
case "series":
valueCols.add(col);
return;
case "excluded":
return;
default:
(0, import_ag_grid_community223._warn)(153, { chartDataType });
break;
}
}
if (colDef.colId === "ag-Grid-AutoColumn") {
dimensionCols.add(col);
return;
}
if (!col.isPrimary()) {
valueCols.add(col);
return;
}
(this.isInferredValueCol(col) ? valueCols : dimensionCols).add(col);
});
return { dimensionCols, valueCols };
}
isInferredValueCol(col) {
const colId = col.getColId();
if (colId === "ag-Grid-AutoColumn") {
return false;
}
const row = (0, import_ag_grid_community223._getRowNode)(this.beans, { rowIndex: 0, rowPinned: null });
if (!row) {
return this.valueColsWithoutSeriesType.has(colId);
}
let cellValue = this.valueSvc.getValue(col, row);
if (cellValue == null) {
cellValue = this.extractLeafData(row, col);
}
if (cellValue != null) {
if (typeof cellValue.toNumber === "function") {
cellValue = cellValue.toNumber();
} else if (typeof cellValue.value === "number") {
cellValue = cellValue.value;
}
}
const isNumber = typeof cellValue === "number" || col.colDef.cellDataType === "number" || ["series", "time"].includes(col.colDef.chartDataType);
if (isNumber) {
this.valueColsWithoutSeriesType.add(colId);
} else if (cellValue == null && col.colDef.cellDataType !== "number") {
(0, import_ag_grid_community223._warn)(265, { colId });
}
return isNumber;
}
extractLeafData(row, col) {
if (!row.allLeafChildren) {
return null;
}
for (let i = 0; i < row.allLeafChildren.length; i++) {
const childRow = row.allLeafChildren[i];
const value = this.valueSvc.getValue(col, childRow);
if (value != null) {
return value;
}
}
return null;
}
destroy() {
this.valueColsWithoutSeriesType.clear();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/model/comboChartModel.ts
var import_ag_grid_community224 = require("ag-grid-community");
var SUPPORTED_COMBO_CHART_TYPES = /* @__PURE__ */ new Set(["line", "groupedColumn", "stackedColumn", "area", "stackedArea"]);
var ComboChartModel = class extends import_ag_grid_community224.BeanStub {
constructor(chartDataModel) {
super();
// this control flag is used to only log warning for the initial user config
this.suppressComboChartWarnings = false;
this.chartDataModel = chartDataModel;
this.seriesChartTypes = chartDataModel.params.seriesChartTypes ?? [];
}
postConstruct() {
this.initComboCharts();
}
update(seriesChartTypes) {
this.seriesChartTypes = seriesChartTypes ?? this.seriesChartTypes;
this.initComboCharts();
this.updateSeriesChartTypes();
}
initComboCharts() {
const seriesChartTypesExist = this.seriesChartTypes && this.seriesChartTypes.length > 0;
const customCombo = this.chartDataModel.chartType === "customCombo" || seriesChartTypesExist;
if (customCombo) {
this.chartDataModel.chartType = "customCombo";
this.savedCustomSeriesChartTypes = this.seriesChartTypes || [];
}
}
updateSeriesChartTypes() {
if (!this.chartDataModel.isComboChart()) {
return;
}
this.seriesChartTypes = this.seriesChartTypes.map((seriesChartType) => {
const primaryOnly = ["groupedColumn", "stackedColumn", "stackedArea"].includes(seriesChartType.chartType);
seriesChartType.secondaryAxis = primaryOnly ? false : seriesChartType.secondaryAxis;
return seriesChartType;
});
if (this.chartDataModel.chartType === "customCombo") {
this.updateSeriesChartTypesForCustomCombo();
return;
}
this.updateChartSeriesTypesForBuiltInCombos();
}
updateSeriesChartTypesForCustomCombo() {
const seriesChartTypesSupplied = this.seriesChartTypes && this.seriesChartTypes.length > 0;
if (!seriesChartTypesSupplied && !this.suppressComboChartWarnings) {
(0, import_ag_grid_community224._warn)(150);
}
this.seriesChartTypes = this.seriesChartTypes.map((s) => {
if (!SUPPORTED_COMBO_CHART_TYPES.has(s.chartType)) {
(0, import_ag_grid_community224._warn)(151, { chartType: s.chartType });
s.chartType = "line";
}
return s;
});
const getSeriesChartType = (valueCol) => {
if (!this.savedCustomSeriesChartTypes || this.savedCustomSeriesChartTypes.length === 0) {
this.savedCustomSeriesChartTypes = this.seriesChartTypes;
}
const providedSeriesChartType = this.savedCustomSeriesChartTypes.find((s) => s.colId === valueCol.colId);
if (!providedSeriesChartType) {
if (valueCol.selected && !this.suppressComboChartWarnings) {
(0, import_ag_grid_community224._warn)(152, { colId: valueCol.colId });
}
return {
colId: valueCol.colId,
chartType: "line",
secondaryAxis: false
};
}
return providedSeriesChartType;
};
const updatedSeriesChartTypes = this.chartDataModel.valueColState.map(getSeriesChartType);
this.seriesChartTypes = updatedSeriesChartTypes;
this.savedCustomSeriesChartTypes = updatedSeriesChartTypes;
this.suppressComboChartWarnings = true;
}
updateChartSeriesTypesForBuiltInCombos() {
const { chartType, valueColState } = this.chartDataModel;
const primaryChartType = chartType === "columnLineCombo" ? "groupedColumn" : "stackedArea";
const secondaryChartType = chartType === "columnLineCombo" ? "line" : "groupedColumn";
const selectedCols = valueColState.filter((cs) => cs.selected);
const lineIndex = Math.ceil(selectedCols.length / 2);
this.seriesChartTypes = selectedCols.map((valueCol, i) => {
const seriesType = i >= lineIndex ? secondaryChartType : primaryChartType;
return { colId: valueCol.colId, chartType: seriesType, secondaryAxis: false };
});
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/model/chartDataModel.ts
var DEFAULT_CHART_CATEGORY = "AG-GRID-DEFAULT-CATEGORY";
var ChartDataModel = class extends import_ag_grid_community225.BeanStub {
constructor(params) {
super();
this.unlinked = false;
this.chartData = [];
this.valueColState = [];
this.dimensionColState = [];
this.colNames = {};
this.crossFiltering = false;
this.grouping = false;
this.params = params;
this.chartId = params.chartId;
this.setParams(params);
}
wireBeans(beans) {
this.rangeSvc = beans.rangeSvc;
this.chartTranslation = beans.chartTranslation;
}
setParams(params) {
const {
chartType,
pivotChart,
chartThemeName,
switchCategorySeries,
aggFunc,
cellRange,
suppressChartRanges,
unlinkChart,
crossFiltering,
seriesGroupType
} = params;
this.chartType = chartType;
this.pivotChart = pivotChart ?? false;
this.chartThemeName = chartThemeName;
this.switchCategorySeries = !!switchCategorySeries;
this.aggFunc = aggFunc;
this.referenceCellRange = cellRange;
this.suppliedCellRange = cellRange;
this.suppressChartRanges = suppressChartRanges ?? false;
this.unlinked = !!unlinkChart;
this.crossFiltering = !!crossFiltering;
this.seriesGroupType = seriesGroupType;
}
postConstruct() {
this.datasource = this.createManagedBean(new ChartDatasource());
this.chartColSvc = this.createManagedBean(new ChartColumnService());
this.comboChartModel = this.createManagedBean(new ComboChartModel(this));
this.updateCellRanges({ setColsFromRange: true });
this.updateData();
}
updateModel(params) {
const { cellRange, seriesChartTypes } = params;
if (cellRange !== this.suppliedCellRange) {
this.dimensionCellRange = void 0;
this.valueCellRange = void 0;
}
this.setParams(params);
this.updateSelectedDimensions(cellRange?.columns);
this.updateCellRanges({ setColsFromRange: true });
const shouldUpdateComboModel = this.isComboChart() || seriesChartTypes;
if (shouldUpdateComboModel) {
this.comboChartModel.update(seriesChartTypes);
}
if (!this.unlinked) {
this.updateData();
}
}
updateCellRanges(params) {
const { updatedColState, resetOrder, maintainColState, setColsFromRange } = params ?? {};
if (this.valueCellRange) {
this.referenceCellRange = this.valueCellRange;
}
const { dimensionCols, valueCols } = this.chartColSvc.getChartColumns();
const allColsFromRanges = this.getAllColumnsFromRanges();
if (updatedColState) {
this.updateColumnState(updatedColState, resetOrder);
}
this.setDimensionCellRange(dimensionCols, allColsFromRanges, updatedColState);
this.setValueCellRange(valueCols, allColsFromRanges, setColsFromRange);
if (!updatedColState && !maintainColState) {
this.resetColumnState();
this.syncDimensionCellRange();
}
this.comboChartModel.updateSeriesChartTypes();
}
updateData() {
const { startRow, endRow } = this.getRowIndexes();
if (this.pivotChart) {
this.resetColumnState();
}
this.grouping = this.isGrouping();
const params = {
aggFunc: this.aggFunc,
dimensionCols: this.getSelectedDimensions(),
grouping: this.grouping,
pivoting: this.isPivotActive(),
crossFiltering: this.crossFiltering,
valueCols: this.getSelectedValueCols(),
startRow,
endRow,
isScatter: ["scatter", "bubble"].includes(this.chartType)
};
const { chartData, colNames, groupChartData } = this.datasource.getData(params);
this.chartData = chartData;
this.groupChartData = groupChartData;
this.colNames = colNames;
this.categoryAxisType = void 0;
}
isGrouping() {
const usingTreeData = this.gos.get("treeData");
const groupedCols = usingTreeData ? null : this.chartColSvc.getRowGroupColumns();
const isGroupActive = usingTreeData || groupedCols && groupedCols.length > 0;
const colIds = this.getSelectedDimensions().map(({ colId }) => colId);
const displayedGroupCols = this.chartColSvc.getGroupDisplayColumns();
const groupDimensionSelected = displayedGroupCols.map((col) => col.getColId()).some((id) => colIds.includes(id));
return !!isGroupActive && groupDimensionSelected;
}
getSelectedValueCols() {
return this.valueColState.filter((cs) => cs.selected).map((cs) => cs.column);
}
getSelectedDimensions() {
return this.dimensionColState.filter((cs) => cs.selected);
}
getColDisplayName(col, includePath) {
return this.chartColSvc.getColDisplayName(col, includePath);
}
isPivotMode() {
return this.chartColSvc.isPivotMode();
}
getChartDataType(colId) {
const column = this.chartColSvc.getColumn(colId);
return column ? column.getColDef().chartDataType : void 0;
}
isPivotActive() {
return this.chartColSvc.isPivotActive();
}
createCellRange(type, ...columns) {
return {
id: this.chartId,
// set range ID to match chart ID so we can identify changes to the ranges for this chart
startRow: this.referenceCellRange.startRow,
endRow: this.referenceCellRange.endRow,
columns,
startColumn: type === import_ag_grid_community225.CellRangeType.DIMENSION || this.referenceCellRange.startColumn == null ? columns[0] : this.referenceCellRange.startColumn,
type
};
}
getAllColumnsFromRanges() {
if (this.pivotChart) {
return new Set(this.chartColSvc.getAllDisplayedColumns());
}
const columns = this.dimensionCellRange || this.valueCellRange ? [] : this.referenceCellRange.columns;
if (this.dimensionCellRange) {
columns.push(...this.dimensionCellRange.columns);
}
if (this.valueCellRange) {
columns.push(...this.valueCellRange.columns);
}
return new Set(columns);
}
getRowIndexes() {
let startRow = 0, endRow = 0;
const { rangeSvc, valueCellRange, dimensionCellRange } = this;
const cellRange = valueCellRange || dimensionCellRange;
if (rangeSvc && cellRange) {
startRow = rangeSvc.getRangeStartRow(cellRange).rowIndex;
const endRowPosition = rangeSvc.getRangeEndRow(cellRange);
endRow = endRowPosition.rowPinned === "bottom" ? -1 : endRowPosition.rowIndex;
}
return { startRow, endRow };
}
resetColumnState() {
const { dimensionCols, valueCols } = this.chartColSvc.getChartColumns();
const allCols = this.getAllColumnsFromRanges();
const isInitialising = this.valueColState.length < 1;
this.dimensionColState = [];
this.valueColState = [];
const supportsMultipleDimensions = isHierarchical(getSeriesType(this.chartType));
let hasSelectedDimension = false;
let order = 1;
const aggFuncDimension = this.suppliedCellRange.columns[0];
dimensionCols.forEach((column) => {
const isAutoGroupCol = column.getColId() === "ag-Grid-AutoColumn";
let selected = false;
if (this.crossFiltering && this.aggFunc) {
if (aggFuncDimension.getColId() === column.getColId()) {
selected = true;
}
} else {
selected = isAutoGroupCol ? true : (!hasSelectedDimension || supportsMultipleDimensions) && allCols.has(column);
}
this.dimensionColState.push({
column,
colId: column.getColId(),
displayName: this.getColDisplayName(column),
selected,
order: order++
});
if (selected) {
hasSelectedDimension = true;
}
});
const defaultCategory = {
colId: DEFAULT_CHART_CATEGORY,
displayName: this.chartTranslation.translate("defaultCategory"),
selected: !hasSelectedDimension,
// if no dimensions in range select the default
order: 0
};
this.dimensionColState.unshift(defaultCategory);
const valueColumnsFromReferenceRange = this.referenceCellRange.columns.filter(
(c) => valueCols.has(c)
);
valueCols.forEach((column) => {
if (isInitialising && this.referenceCellRange.columns.includes(column)) {
column = valueColumnsFromReferenceRange.shift();
}
this.valueColState.push({
column,
colId: column.getColId(),
displayName: this.getColDisplayName(column),
selected: allCols.has(column),
order: order++
});
});
}
updateColumnState(updatedCol, resetOrder) {
const idsMatch = (cs) => cs.colId === updatedCol.colId;
const { dimensionColState, valueColState } = this;
const matchedDimensionColState = dimensionColState.find(idsMatch);
const matchedValueColState = valueColState.find(idsMatch);
if (matchedDimensionColState) {
const supportsMultipleDimensions = isHierarchical(getSeriesType(this.chartType));
if (!supportsMultipleDimensions) {
const selectedColumnState = updatedCol.selected ? matchedDimensionColState : dimensionColState.filter((cs) => cs !== matchedDimensionColState).find(({ selected }) => selected);
dimensionColState.forEach((cs) => cs.selected = cs === selectedColumnState);
} else {
matchedDimensionColState.selected = updatedCol.selected;
}
} else if (matchedValueColState) {
matchedValueColState.selected = updatedCol.selected;
}
const allColumns = [...dimensionColState, ...valueColState];
const orderedColIds = [];
if (!resetOrder) {
allColumns.forEach((col, i) => {
if (i === updatedCol.order) {
orderedColIds.push(updatedCol.colId);
}
if (col.colId !== updatedCol.colId) {
orderedColIds.push(col.colId);
}
});
allColumns.forEach((col) => {
const order = orderedColIds.indexOf(col.colId);
col.order = order >= 0 ? orderedColIds.indexOf(col.colId) : allColumns.length - 1;
});
}
this.reorderColState();
}
reorderColState() {
const ascColStateOrder = (a, b) => a.order - b.order;
this.dimensionColState.sort(ascColStateOrder);
this.valueColState.sort(ascColStateOrder);
}
setDimensionCellRange(dimensionCols, colsInRange, updatedColState) {
this.dimensionCellRange = void 0;
const supportsMultipleDimensions = isHierarchical(getSeriesType(this.chartType));
if (!updatedColState && !this.dimensionColState.length) {
const selectedCols = new Array();
dimensionCols.forEach((col) => {
if (selectedCols.length > 0 && !supportsMultipleDimensions || !colsInRange.has(col)) {
return;
}
selectedCols.push(col);
});
if (selectedCols.length > 0) {
this.dimensionCellRange = this.createCellRange(import_ag_grid_community225.CellRangeType.DIMENSION, ...selectedCols);
}
return;
}
let selectedDimensionColStates = updatedColState ? [updatedColState] : [];
if (this.crossFiltering && this.aggFunc) {
const aggFuncDimension = this.suppliedCellRange.columns[0];
selectedDimensionColStates = this.dimensionColState.filter(
(cs) => cs.colId === aggFuncDimension.getColId()
);
} else if (supportsMultipleDimensions || selectedDimensionColStates.length === 0 || selectedDimensionColStates.some(({ column }) => !column || !dimensionCols.has(column))) {
selectedDimensionColStates = this.dimensionColState.filter((cs) => cs.selected);
}
const isDefaultCategory = selectedDimensionColStates.length === 1 ? selectedDimensionColStates[0].colId === DEFAULT_CHART_CATEGORY : false;
const selectedColumns = selectedDimensionColStates.map(({ column }) => column).filter((value) => value != null);
if (selectedColumns.length > 0 && !isDefaultCategory) {
this.dimensionCellRange = this.createCellRange(import_ag_grid_community225.CellRangeType.DIMENSION, ...selectedColumns);
}
}
setValueCellRange(valueCols, colsInRange, setColsFromRange) {
this.valueCellRange = void 0;
const selectedValueCols = [];
const maxSelection = getMaxNumSeries(this.chartType);
let numSelected = 0;
valueCols.forEach((col) => {
if (setColsFromRange) {
if ((maxSelection == null || numSelected < maxSelection) && colsInRange.has(col)) {
selectedValueCols.push(col);
numSelected++;
}
} else {
if (this.valueColState.some((colState) => colState.selected && colState.colId === col.getColId())) {
selectedValueCols.push(col);
}
}
});
if (selectedValueCols.length > 0) {
let orderedColIds = [];
if (this.valueColState.length > 0) {
orderedColIds = this.valueColState.map((c) => c.colId);
} else {
colsInRange.forEach((c) => orderedColIds.push(c.getColId()));
}
selectedValueCols.sort((a, b) => orderedColIds.indexOf(a.getColId()) - orderedColIds.indexOf(b.getColId()));
this.valueCellRange = this.createCellRange(import_ag_grid_community225.CellRangeType.VALUE, ...selectedValueCols);
}
}
resetCellRanges(dimension, value) {
if (!dimension && !value) {
return;
}
const { dimensionCols, valueCols } = this.chartColSvc.getChartColumns();
const allColsFromRanges = this.getAllColumnsFromRanges();
if (dimension) {
this.setDimensionCellRange(dimensionCols, allColsFromRanges);
}
if (value) {
this.setValueCellRange(valueCols, allColsFromRanges);
}
}
updateSelectedDimensions(columns) {
const colIdSet = new Set(columns.map((column) => column.getColId()));
const supportsMultipleDimensions = isHierarchical(getSeriesType(this.chartType));
if (!supportsMultipleDimensions) {
const foundColState = this.dimensionColState.find((colState) => colIdSet.has(colState.colId)) || this.dimensionColState[0];
const selectedColumnId = foundColState.colId;
this.dimensionColState = this.dimensionColState.map((colState) => ({
...colState,
selected: colState.colId === selectedColumnId
}));
} else {
const foundColStates = this.dimensionColState.filter((colState) => colIdSet.has(colState.colId));
const selectedColumnIds = new Set(foundColStates.map((colState) => colState.colId));
this.dimensionColState = this.dimensionColState.map((colState) => ({
...colState,
selected: selectedColumnIds.has(colState.colId)
}));
}
}
syncDimensionCellRange() {
const selectedDimensions = this.getSelectedDimensions();
if (selectedDimensions.length === 0)
return;
const selectedCols = selectedDimensions.map(({ column }) => column).filter((value) => value != null);
if (selectedCols.length > 0) {
this.dimensionCellRange = this.createCellRange(import_ag_grid_community225.CellRangeType.DIMENSION, ...selectedCols);
}
}
isComboChart(chartType) {
return isComboChart(chartType ?? this.chartType);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/statistical/statisticalChartProxy.ts
var StatisticalChartProxy = class extends CartesianChartProxy {
getAxes(params, commonChartOptions) {
return [
{
type: this.getXAxisType(params),
position: this.isHorizontal(commonChartOptions) ? "left" : "bottom"
},
{
type: "number",
position: this.isHorizontal(commonChartOptions) ? "bottom" : "left"
}
];
}
computeSeriesStatistics(params, computeStatsFn) {
const { data, fields } = params;
const [category] = params.categories;
const categoryKey = category.id || DEFAULT_CHART_CATEGORY;
const groupedData = this.groupDataByCategory(categoryKey, data);
return Array.from(groupedData).map(([categoryValue, categoryData]) => {
const categoryResult = { [category.id]: categoryValue };
fields.forEach((field, seriesIndex) => {
const seriesValues = categoryData.map((datum) => datum[field.colId]).filter((value) => typeof value === "number" && !isNaN(value));
const computed = computeStatsFn(seriesValues);
for (const statKey of Object.keys(computed)) {
const propertyKey = `${statKey}:${seriesIndex}`;
categoryResult[propertyKey] = seriesValues.length > 0 ? computed[statKey] : null;
}
});
return categoryResult;
});
}
groupDataByCategory(categoryKey, data) {
const getCategory = (datum) => {
if (categoryKey === DEFAULT_CHART_CATEGORY) {
return 1;
}
const categoryValue = datum[categoryKey];
if (categoryValue === null || categoryValue === void 0) {
return "";
}
return categoryValue instanceof Date ? categoryValue.getTime() : categoryValue;
};
return data.reduce((acc, datum) => {
const category = getCategory(datum);
const existingCategoryData = acc.get(category);
if (existingCategoryData) {
existingCategoryData.push(datum);
} else {
acc.set(category, [datum]);
}
return acc;
}, /* @__PURE__ */ new Map());
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/statistical/boxPlotChartProxy.ts
var BoxPlotChartProxy = class extends StatisticalChartProxy {
getSeries(params) {
const [category] = params.categories;
return params.fields.map((field, seriesIndex) => ({
type: this.standaloneChartType,
// xKey/xName refer to category buckets
xKey: category.id,
xName: category.name,
// yName is used to label the series
yName: field.displayName ?? void 0,
// custom field labels shown in the tooltip
minName: "Min",
q1Name: "Q1",
medianName: "Median",
q3Name: "Q3",
maxName: "Max",
// generated 'synthetic fields' from getData()
minKey: `min:${seriesIndex}`,
q1Key: `q1:${seriesIndex}`,
medianKey: `median:${seriesIndex}`,
q3Key: `q3:${seriesIndex}`,
maxKey: `max:${seriesIndex}`
}));
}
getData(params) {
return this.computeSeriesStatistics(params, (seriesValues) => {
const sortedValues = seriesValues.sort((a, b) => a - b);
return {
min: sortedValues[0],
q1: this.quantile(sortedValues, 0.25),
median: this.quantile(sortedValues, 0.5),
q3: this.quantile(sortedValues, 0.75),
max: sortedValues[sortedValues.length - 1]
};
});
}
quantile(sortedValues, q) {
const position = (sortedValues.length - 1) * q;
const indexBelow = Math.floor(position);
const aboveValue = position - indexBelow;
if (sortedValues[indexBelow + 1] !== void 0) {
return sortedValues[indexBelow] + aboveValue * (sortedValues[indexBelow + 1] - sortedValues[indexBelow]);
}
return sortedValues[indexBelow];
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/statistical/rangeChartProxy.ts
var RangeChartProxy = class extends StatisticalChartProxy {
getSeries(params) {
const [category] = params.categories;
return params.fields.map((field, seriesIndex) => ({
type: this.standaloneChartType,
// xKey/xName refer to category buckets
xKey: category.id,
xName: category.name,
// yName is used to label the series
yName: field.displayName ?? void 0,
// custom field labels shown in the tooltip
yLowName: "Min",
yHighName: "Max",
// generated 'synthetic fields' from getData()
yLowKey: `min:${seriesIndex}`,
yHighKey: `max:${seriesIndex}`
}));
}
getData(params) {
return this.computeSeriesStatistics(params, (seriesValues) => {
return {
min: Math.min(...seriesValues),
max: Math.max(...seriesValues)
};
});
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/enterpriseChartProxyFactory.ts
var EnterpriseChartProxyFactory = class extends import_ag_grid_community226.BeanStub {
constructor() {
super(...arguments);
this.beanName = "enterpriseChartProxyFactory";
}
createChartProxy(chartProxyParams) {
switch (chartProxyParams.chartType) {
case "histogram":
return new HistogramChartProxy(chartProxyParams);
case "radarLine":
case "radarArea":
case "nightingale":
case "radialColumn":
case "radialBar":
return new PolarChartProxy(chartProxyParams);
case "rangeBar":
case "rangeArea":
return new RangeChartProxy(chartProxyParams);
case "boxPlot":
return new BoxPlotChartProxy(chartProxyParams);
case "treemap":
case "sunburst":
return new HierarchicalChartProxy(chartProxyParams);
case "heatmap":
return new HeatmapChartProxy(chartProxyParams);
case "waterfall":
return new WaterfallChartProxy(chartProxyParams);
case "funnel":
case "coneFunnel":
case "pyramid":
return new FunnelChartProxy(chartProxyParams);
}
return void 0;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/advancedSettingsMenuFactory.ts
var import_ag_grid_community238 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/advancedSettingsPanel.ts
var import_ag_grid_community237 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/chartPanelFeature.ts
var import_ag_grid_community227 = require("ag-grid-community");
var ChartPanelFeature = class extends import_ag_grid_community227.BeanStub {
constructor(chartController, eGui, cssClass, createPanels) {
super();
this.chartController = chartController;
this.eGui = eGui;
this.cssClass = cssClass;
this.createPanels = createPanels;
this.panels = [];
}
postConstruct() {
this.addManagedListeners(this.chartController, {
chartUpdated: () => this.refreshPanels(true),
chartApiUpdate: () => this.refreshPanels(false)
});
}
addComponent(component) {
this.createBean(component);
this.panels.push(component);
component.addCss(this.cssClass);
this.eGui.appendChild(component.getGui());
}
refreshPanels(reuse) {
const chartType = this.chartController.getChartType();
const isGrouping = this.chartController.isGrouping();
const seriesType = getSeriesType(chartType);
if (reuse && chartType === this.chartType && isGrouping === this.isGrouping) {
return;
}
this.destroyPanels();
this.createPanels(chartType, seriesType);
this.chartType = chartType;
this.isGrouping = isGrouping;
}
destroyPanels() {
this.panels.forEach((panel) => {
(0, import_ag_grid_community227._removeFromParent)(panel.getGui());
this.destroyBean(panel);
});
this.panels = [];
}
destroy() {
this.destroyPanels();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/animationPanel.ts
var import_ag_grid_community228 = require("ag-grid-community");
var AnimationPanel = class extends import_ag_grid_community228.Component {
constructor(chartMenuParamsFactory) {
super();
this.chartMenuParamsFactory = chartMenuParamsFactory;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const animationGroupParams = this.chartMenuParamsFactory.addEnableParams(
"animation.enabled",
{
cssIdentifier: "charts-advanced-settings-top-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: this.chartTranslation.translate("animation"),
suppressEnabledCheckbox: true,
useToggle: true
}
);
const animationHeightInputParams = this.chartMenuParamsFactory.getDefaultNumberInputParams(
"animation.duration",
"durationMillis",
{
min: 0
}
);
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="animationGroup">
<ag-input-number-field data-ref="animationHeightInput"></ag-input>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, import_ag_grid_community228.AgInputNumberFieldSelector],
{
animationGroup: animationGroupParams,
animationHeightInput: animationHeightInputParams
}
);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/crosshairPanel.ts
var import_ag_grid_community232 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/widgets/agColorPicker.ts
var import_ag_grid_community231 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/widgets/agColorPanel.ts
var import_ag_grid_community230 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/widgets/agColorInput.ts
var import_ag_grid_community229 = require("ag-grid-community");
var AgColorInputElement = {
tag: "div",
cls: "ag-color-input",
role: "presentation",
children: [
{ tag: "div", ref: "eLabel", cls: "ag-input-field-label" },
{
tag: "div",
ref: "eWrapper",
cls: "ag-wrapper ag-input-wrapper",
role: "presentation",
children: [
{ tag: "input", ref: "eInput", cls: "ag-input-field-input" },
{ tag: "div", ref: "eColor", cls: "ag-color-input-color" }
]
}
]
};
var AgColorInput = class extends import_ag_grid_community229.AgInputTextField {
constructor() {
super({
template: AgColorInputElement
});
this.eColor = import_ag_grid_community229.RefPlaceholder;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
this.color = beans.agChartsExports._Util.Color;
}
setColor(color) {
const rgbaColor = color.toRgbaString();
this.setValue(this.color.fromString(rgbaColor).toHexString().toUpperCase(), true);
this.eColor.style.backgroundColor = rgbaColor;
}
setValue(value, silent) {
const isValid = this.color.validColorString(value ?? "");
this.eInput.setCustomValidity(isValid ? "" : this.chartTranslation.translate("invalidColor"));
super.setValue(value, silent);
if (isValid && !silent) {
this.dispatchLocalEvent({ type: "colorChanged" });
}
return this;
}
onColorChanged(callback) {
this.addManagedListeners(this, { colorChanged: () => callback(this.color.fromString(this.value)) });
}
};
var AgColorInputSelector = {
selector: "AG-COLOR-INPUT",
component: AgColorInput
};
// packages/ag-grid-enterprise/src/charts/widgets/agColorPanel.ts
var maxRecentColors = 8;
var sharedRecentColors = [];
var AgColorPanel = class extends import_ag_grid_community230.Component {
constructor(config) {
super(
/* html */
`<div class="ag-color-panel" tabindex="-1">
<div data-ref="spectrumColor" class="ag-spectrum-color">
<div class="ag-spectrum-sat ag-spectrum-fill">
<div data-ref="spectrumVal" class="ag-spectrum-val ag-spectrum-fill">
<div data-ref="spectrumDragger" class="ag-spectrum-dragger"></div>
</div>
</div>
</div>
<div class="ag-spectrum-tools">
<div data-ref="spectrumHue" class="ag-spectrum-hue ag-spectrum-tool">
<div class="ag-spectrum-hue-background"></div>
<div data-ref="spectrumHueSlider" class="ag-spectrum-slider"></div>
</div>
<div data-ref="spectrumAlpha" class="ag-spectrum-alpha ag-spectrum-tool">
<div class="ag-spectrum-alpha-background"></div>
<div data-ref="spectrumAlphaSlider" class="ag-spectrum-slider"></div>
</div>
<ag-color-input data-ref="colorInput"></ag-color-input>
<div data-ref="recentColors" class="ag-recent-colors"></div>
</div>
</div>`,
[AgColorInputSelector]
);
this.H = 1;
// in the [0, 1] range
this.S = 1;
// in the [0, 1] range
this.B = 1;
// in the [0, 1] range
this.A = 1;
this.isSpectrumDragging = false;
this.isSpectrumHueDragging = false;
this.isSpectrumAlphaDragging = false;
this.colorChanged = false;
this.spectrumColor = import_ag_grid_community230.RefPlaceholder;
this.spectrumVal = import_ag_grid_community230.RefPlaceholder;
this.spectrumDragger = import_ag_grid_community230.RefPlaceholder;
this.spectrumHue = import_ag_grid_community230.RefPlaceholder;
this.spectrumHueSlider = import_ag_grid_community230.RefPlaceholder;
this.spectrumAlpha = import_ag_grid_community230.RefPlaceholder;
this.spectrumAlphaSlider = import_ag_grid_community230.RefPlaceholder;
this.colorInput = import_ag_grid_community230.RefPlaceholder;
this.recentColors = import_ag_grid_community230.RefPlaceholder;
this.picker = config.picker;
}
wireBeans(beans) {
this._Color = beans.agChartsExports._Util.Color;
}
postConstruct() {
this.initTabIndex();
this.initRecentColors();
this.addGuiEventListener("focus", () => this.spectrumColor.focus());
this.addGuiEventListener("keydown", (e) => {
if (e.key === import_ag_grid_community230.KeyCode.ENTER && !e.defaultPrevented) {
this.destroy();
}
});
this.addManagedListeners(this.spectrumColor, { keydown: (e) => this.moveDragger(e) });
this.addManagedListeners(this.spectrumAlphaSlider, { keydown: (e) => this.moveAlphaSlider(e) });
this.addManagedListeners(this.spectrumHueSlider, { keydown: (e) => this.moveHueSlider(e) });
this.addManagedListeners(this.spectrumVal, { mousedown: this.onSpectrumDraggerDown.bind(this) });
this.addManagedListeners(this.spectrumHue, { mousedown: this.onSpectrumHueDown.bind(this) });
this.addManagedListeners(this.spectrumAlpha, { mousedown: this.onSpectrumAlphaDown.bind(this) });
this.addGuiEventListener("mousemove", (e) => {
this.onSpectrumDraggerMove(e);
this.onSpectrumHueMove(e);
this.onSpectrumAlphaMove(e);
});
this.addManagedListeners(document, { mouseup: this.onMouseUp.bind(this) });
this.colorInput.onColorChanged(this.setColor.bind(this));
this.addManagedListeners(this.recentColors, {
click: this.onRecentColorClick.bind(this),
keydown: (e) => {
if (e.key === import_ag_grid_community230.KeyCode.ENTER || e.key === import_ag_grid_community230.KeyCode.SPACE) {
e.preventDefault();
this.onRecentColorClick(e);
}
}
});
}
initTabIndex() {
const tabIndex = this.tabIndex = this.gos.get("tabIndex").toString();
this.spectrumColor.setAttribute("tabindex", tabIndex);
this.spectrumHueSlider.setAttribute("tabindex", tabIndex);
this.spectrumAlphaSlider.setAttribute("tabindex", tabIndex);
}
refreshSpectrumRect() {
return this.spectrumValRect = this.spectrumVal.getBoundingClientRect();
}
refreshHueRect() {
return this.spectrumHueRect = this.spectrumHue.getBoundingClientRect();
}
refreshAlphaRect() {
return this.spectrumAlphaRect = this.spectrumAlpha.getBoundingClientRect();
}
onSpectrumDraggerDown(e) {
e.preventDefault();
this.refreshSpectrumRect();
this.isSpectrumDragging = true;
this.moveDragger(e);
}
onSpectrumDraggerMove(e) {
if (this.isSpectrumDragging) {
this.moveDragger(e);
}
}
onSpectrumHueDown(e) {
this.refreshHueRect();
this.isSpectrumHueDragging = true;
this.moveHueSlider(e);
}
onSpectrumHueMove(e) {
if (this.isSpectrumHueDragging) {
this.moveHueSlider(e);
}
}
onSpectrumAlphaDown(e) {
this.refreshAlphaRect();
this.isSpectrumAlphaDragging = true;
this.moveAlphaSlider(e);
}
onSpectrumAlphaMove(e) {
if (this.isSpectrumAlphaDragging) {
this.moveAlphaSlider(e);
}
}
onMouseUp() {
this.isSpectrumDragging = false;
this.isSpectrumHueDragging = false;
this.isSpectrumAlphaDragging = false;
}
moveDragger(e) {
const valRect = this.spectrumValRect;
if (!valRect) {
return;
}
let x;
let y;
if (e instanceof MouseEvent) {
x = e.clientX - valRect.left;
y = e.clientY - valRect.top;
} else {
const isLeft = e.key === import_ag_grid_community230.KeyCode.LEFT;
const isRight = e.key === import_ag_grid_community230.KeyCode.RIGHT;
const isUp = e.key === import_ag_grid_community230.KeyCode.UP;
const isDown = e.key === import_ag_grid_community230.KeyCode.DOWN;
const isVertical = isUp || isDown;
const isHorizontal = isLeft || isRight;
if (!isVertical && !isHorizontal) {
return;
}
e.preventDefault();
const { x: currentX, y: currentY } = this.getSpectrumValue();
x = currentX + (isHorizontal ? isLeft ? -5 : 5 : 0);
y = currentY + (isVertical ? isUp ? -5 : 5 : 0);
}
x = Math.max(x, 0);
x = Math.min(x, valRect.width);
y = Math.max(y, 0);
y = Math.min(y, valRect.height);
this.setSpectrumValue(x / valRect.width, 1 - y / valRect.height);
}
moveHueSlider(e) {
const rect = this.spectrumHueRect;
if (!rect) {
return;
}
const x = this.moveSlider(this.spectrumHueSlider, e);
if (x == null) {
return;
}
this.H = 1 - x / rect.width;
this.update();
}
moveAlphaSlider(e) {
const rect = this.spectrumAlphaRect;
if (!rect) {
return;
}
const x = this.moveSlider(this.spectrumAlphaSlider, e);
if (x == null) {
return;
}
this.A = x / rect.width;
this.update();
}
moveSlider(slider, e) {
const sliderRect = slider.getBoundingClientRect();
const parentRect = slider.parentElement?.getBoundingClientRect();
if (!slider || !parentRect) {
return null;
}
const offset = sliderRect.width / 2;
let x;
if (e instanceof MouseEvent) {
x = Math.floor(e.clientX - parentRect.left);
} else {
const isLeft = e.key === import_ag_grid_community230.KeyCode.LEFT;
const isRight = e.key === import_ag_grid_community230.KeyCode.RIGHT;
if (!isLeft && !isRight) {
return null;
}
e.preventDefault();
const diff = isLeft ? -5 : 5;
x = parseFloat(slider.style.left) + offset + diff;
}
x = Math.max(x, 0);
x = Math.min(x, parentRect.width);
slider.style.left = x - offset + "px";
return x;
}
update(suppressColorInputUpdate) {
const { A, S, B, H, _Color } = this;
const hue = H * 360;
const color = _Color.fromHSB(hue, S, B, A);
const rgbaColor = color.toRgbaString();
const colorWithoutAlpha = _Color.fromHSB(hue, S, B);
const rgbaColorWithoutAlpha = colorWithoutAlpha.toRgbaString();
const spectrumColor = _Color.fromHSB(hue, 1, 1);
const spectrumRgbaColor = spectrumColor.toRgbaString();
const colorPicker = this.picker;
const existingColor = _Color.fromString(colorPicker.getValue());
if (existingColor.toRgbaString() !== rgbaColor) {
this.colorChanged = true;
}
colorPicker.setValue(rgbaColor);
this.spectrumColor.style.backgroundColor = spectrumRgbaColor;
this.spectrumDragger.style.backgroundColor = rgbaColorWithoutAlpha;
this.spectrumHueSlider.style.backgroundColor = spectrumRgbaColor;
this.spectrumAlpha.style.setProperty(
"--ag-internal-spectrum-alpha-color-from",
_Color.fromHSB(hue, S, B, 0).toRgbaString()
);
this.spectrumAlpha.style.setProperty("--ag-internal-spectrum-alpha-color-to", rgbaColorWithoutAlpha);
this.spectrumAlpha.style.setProperty("--ag-internal-spectrum-alpha-color", rgbaColor);
if (!suppressColorInputUpdate) {
this.colorInput.setColor(color);
}
}
/**
* @param saturation In the [0, 1] interval.
* @param brightness In the [0, 1] interval.
*/
setSpectrumValue(saturation, brightness, suppressColorInputUpdate) {
const valRect = this.spectrumValRect || this.refreshSpectrumRect();
if (valRect == null) {
return;
}
const dragger = this.spectrumDragger;
const draggerRect = dragger.getBoundingClientRect();
saturation = Math.max(0, saturation);
saturation = Math.min(1, saturation);
brightness = Math.max(0, brightness);
brightness = Math.min(1, brightness);
this.S = saturation;
this.B = brightness;
dragger.style.left = saturation * valRect.width - draggerRect.width / 2 + "px";
dragger.style.top = (1 - brightness) * valRect.height - draggerRect.height / 2 + "px";
this.update(suppressColorInputUpdate);
}
getSpectrumValue() {
const dragger = this.spectrumDragger;
const draggerRect = dragger.getBoundingClientRect();
const x = parseFloat(dragger.style.left) + draggerRect.width / 2;
const y = parseFloat(dragger.style.top) + draggerRect.height / 2;
return { x, y };
}
initRecentColors() {
const recentColors = sharedRecentColors;
const colorsHtmlStr = recentColors.map((color, index) => {
return (
/* html */
`<div class="ag-recent-color" id=${index} style="background-color: ${color}; width: 15px; height: 15px;" recent-color="${color}" tabIndex="${this.tabIndex}"></div>`
);
});
this.recentColors.innerHTML = colorsHtmlStr.join("");
(0, import_ag_grid_community230._setDisplayed)(this.recentColors, !!recentColors.length);
}
setValue(val) {
const color = this._Color.fromString(val);
this.setColor(color, true);
}
setColor(color, updateColorInput) {
const [h, s, b] = color.toHSB();
this.H = (isNaN(h) ? 0 : h) / 360;
this.A = color.a;
const spectrumHueRect = this.spectrumHueRect || this.refreshHueRect();
const spectrumAlphaRect = this.spectrumAlphaRect || this.refreshAlphaRect();
this.spectrumHueSlider.style.left = `${(this.H - 1) * -spectrumHueRect.width - this.spectrumHueSlider.getBoundingClientRect().width / 2}px`;
this.spectrumAlphaSlider.style.left = `${this.A * spectrumAlphaRect.width - this.spectrumAlphaSlider.getBoundingClientRect().width / 2}px`;
this.setSpectrumValue(s, b, !updateColorInput);
}
onRecentColorClick(e) {
const target = e.target;
if (!(0, import_ag_grid_community230._exists)(target.id)) {
return;
}
const id = parseInt(target.id, 10);
this.setValue(sharedRecentColors[id]);
this.destroy();
}
addRecentColor() {
const color = this._Color.fromHSB(this.H * 360, this.S, this.B, this.A);
const rgbaColor = color.toRgbaString();
let recentColors = sharedRecentColors;
if (!this.colorChanged || recentColors[0] === rgbaColor) {
return;
}
recentColors = recentColors.filter((currentColor) => currentColor != rgbaColor);
recentColors = [rgbaColor].concat(recentColors);
if (recentColors.length > maxRecentColors) {
recentColors = recentColors.slice(0, maxRecentColors);
}
sharedRecentColors = recentColors;
}
destroy() {
this.addRecentColor();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/widgets/agColorPicker.ts
var AgColorPicker = class extends import_ag_grid_community231.AgPickerField {
constructor(config) {
super({
pickerAriaLabelKey: "ariaLabelColorPicker",
pickerAriaLabelValue: "Color Picker",
pickerType: "ag-list",
className: "ag-color-picker",
pickerIcon: "chartsColorPicker",
...config
});
}
postConstruct() {
this.eDisplayFieldColor = (0, import_ag_grid_community231._createElement)({
tag: "span",
cls: "ag-color-picker-color"
});
this.eDisplayFieldText = (0, import_ag_grid_community231._createElement)({
tag: "span",
cls: "ag-color-picker-value"
});
this.eDisplayField.append(this.eDisplayFieldColor, this.eDisplayFieldText);
super.postConstruct();
if (this.value) {
this.setValue(this.value);
}
}
createPickerComponent() {
const eGuiRect = this.eWrapper.getBoundingClientRect();
const parentRect = this.beans.popupSvc.getParentRect();
const colorDialog = this.createBean(
new AgDialog({
closable: false,
modal: true,
hideTitleBar: true,
minWidth: 190,
width: 190,
height: 250,
x: eGuiRect.right - parentRect.left - 190,
y: eGuiRect.top - parentRect.top - 250 - (this.config.pickerGap ?? 0),
postProcessPopupParams: {
type: "colorPicker",
eventSource: this.eWrapper
}
})
);
return colorDialog;
}
renderAndPositionPicker() {
const pickerComponent = this.pickerComponent;
const colorPanel = this.createBean(new AgColorPanel({ picker: this }));
pickerComponent.addCss("ag-color-dialog");
colorPanel.addDestroyFunc(() => {
if (pickerComponent.isAlive()) {
this.destroyBean(pickerComponent);
}
});
pickerComponent.setParentComponent(this);
pickerComponent.setBodyComponent(colorPanel);
colorPanel.setValue(this.getValue());
colorPanel.getGui().focus();
pickerComponent.addDestroyFunc(() => {
if (!this.isDestroyingPicker) {
this.beforeHidePicker();
this.isDestroyingPicker = true;
if (colorPanel.isAlive()) {
this.destroyBean(colorPanel);
}
if (this.isAlive()) {
this.getFocusableElement().focus();
}
} else {
this.isDestroyingPicker = false;
}
});
return () => this.pickerComponent?.close();
}
setValue(color) {
if (this.value === color) {
return this;
}
this.eDisplayFieldColor.style.backgroundColor = color;
this.eDisplayFieldText.textContent = this.beans.agChartsExports._Util.Color.fromString(
color
).toHexString().toUpperCase();
return super.setValue(color);
}
getValue() {
return this.value;
}
};
var AgColorPickerSelector = {
selector: "AG-COLOR-PICKER",
component: AgColorPicker
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/crosshairPanel.ts
var CrosshairPanel = class extends import_ag_grid_community232.Component {
constructor(chartMenuParamsFactory) {
super();
this.chartMenuParamsFactory = chartMenuParamsFactory;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const crosshairGroupParams = this.chartMenuParamsFactory.addEnableParams(
"crosshair.enabled",
{
cssIdentifier: "charts-advanced-settings-top-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: this.chartTranslation.translate("crosshair"),
suppressEnabledCheckbox: true,
useToggle: true
}
);
const crosshairLabelCheckboxParams = this.chartMenuParamsFactory.getDefaultCheckboxParams(
"crosshair.label.enabled",
"crosshairLabel"
);
const crosshairSnapCheckboxParams = this.chartMenuParamsFactory.getDefaultCheckboxParams(
"crosshair.snap",
"crosshairSnap"
);
const crosshairStrokeColorPickerParams = this.chartMenuParamsFactory.getDefaultColorPickerParams(
"crosshair.stroke",
"color"
);
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="crosshairGroup">
<ag-checkbox data-ref="crosshairLabelCheckbox"></ag-checkbox>
<ag-checkbox data-ref="crosshairSnapCheckbox"></ag-checkbox>
<ag-color-picker data-ref="crosshairStrokeColorPicker"></ag-color-picker>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, import_ag_grid_community232.AgCheckboxSelector, AgColorPickerSelector],
{
crosshairGroup: crosshairGroupParams,
crosshairLabelCheckbox: crosshairLabelCheckboxParams,
crosshairSnapCheckbox: crosshairSnapCheckboxParams,
crosshairStrokeColorPicker: crosshairStrokeColorPickerParams
}
);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/navigatorPanel.ts
var import_ag_grid_community235 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/widgets/agSlider.ts
var import_ag_grid_community234 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/widgets/agInputRange.ts
var import_ag_grid_community233 = require("ag-grid-community");
var AgInputRange = class extends import_ag_grid_community233.AgAbstractInputField {
constructor(config) {
super(config, "ag-range-field", "range");
}
postConstruct() {
super.postConstruct();
const { min, max, step } = this.config;
if (min != null) {
this.setMinValue(min);
}
if (max != null) {
this.setMaxValue(max);
}
this.setStep(step || 1);
}
addInputListeners() {
this.addManagedElementListeners(this.eInput, {
input: (e) => {
const value = e.target.value;
this.setValue(value);
}
});
}
setMinValue(value) {
this.min = value;
this.eInput.setAttribute("min", value.toString());
return this;
}
setMaxValue(value) {
this.max = value;
this.eInput.setAttribute("max", value.toString());
return this;
}
setStep(value) {
this.eInput.setAttribute("step", value.toString());
return this;
}
setValue(value, silent) {
if (this.min != null) {
value = Math.max(parseFloat(value), this.min).toString();
}
if (this.max != null) {
value = Math.min(parseFloat(value), this.max).toString();
}
const ret = super.setValue(value, silent);
this.eInput.value = value;
return ret;
}
};
var AgInputRangeSelector = {
selector: "AG-INPUT-RANGE",
component: AgInputRange
};
// packages/ag-grid-enterprise/src/charts/widgets/agSlider.ts
var AgSlider = class extends import_ag_grid_community234.AgAbstractLabel {
constructor(config) {
super(
config,
/* html */
`<div class="ag-slider">
<label data-ref="eLabel"></label>
<div class="ag-wrapper ag-slider-wrapper">
<ag-input-range data-ref="eSlider"></ag-input-range>
<ag-input-number-field data-ref="eText"></ag-input-number-field>
</div>
</div>`,
[AgInputRangeSelector, import_ag_grid_community234.AgInputNumberFieldSelector]
);
this.eLabel = import_ag_grid_community234.RefPlaceholder;
this.eSlider = import_ag_grid_community234.RefPlaceholder;
this.eText = import_ag_grid_community234.RefPlaceholder;
this.labelAlignment = "top";
}
postConstruct() {
super.postConstruct();
this.eSlider.addCss("ag-slider-field");
const { minValue, maxValue, textFieldWidth, step, value, onValueChange } = this.config;
if (minValue != null) {
this.setMinValue(minValue);
}
if (maxValue != null) {
this.setMaxValue(maxValue);
}
if (textFieldWidth != null) {
this.setTextFieldWidth(textFieldWidth);
}
if (step != null) {
this.setStep(step);
}
if (value != null) {
this.setValue(value);
}
if (onValueChange != null) {
this.onValueChange(onValueChange);
}
}
onValueChange(callbackFn) {
this.addManagedListeners(this.eText, {
fieldValueChanged: () => {
const textValue = parseFloat(this.eText.getValue());
this.eSlider.setValue(textValue.toString(), true);
callbackFn(textValue || 0);
}
});
this.addManagedListeners(this.eSlider, {
fieldValueChanged: () => {
const sliderValue = this.eSlider.getValue();
this.eText.setValue(sliderValue, true);
callbackFn(parseFloat(sliderValue));
}
});
return this;
}
setSliderWidth(width) {
this.eSlider.setWidth(width);
return this;
}
setTextFieldWidth(width) {
this.eText.setWidth(width);
return this;
}
setMinValue(minValue) {
this.eSlider.setMinValue(minValue);
this.eText.setMin(minValue);
return this;
}
setMaxValue(maxValue) {
this.eSlider.setMaxValue(maxValue);
this.eText.setMax(maxValue);
return this;
}
getValue() {
return this.eText.getValue();
}
setValue(value, silent) {
if (this.getValue() === value) {
return this;
}
this.eText.setValue(value, true);
this.eSlider.setValue(value, true);
if (!silent) {
this.dispatchLocalEvent({ type: "fieldValueChanged" });
}
return this;
}
setStep(step) {
this.eSlider.setStep(step);
this.eText.setStep(step);
return this;
}
};
var AgSliderSelector = {
selector: "AG-SLIDER",
component: AgSlider
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/navigatorPanel.ts
var NavigatorPanel = class extends import_ag_grid_community235.Component {
constructor(chartMenuParamsFactory) {
super();
this.chartMenuParamsFactory = chartMenuParamsFactory;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const navigatorGroupParams = this.chartMenuParamsFactory.addEnableParams(
"navigator.enabled",
{
cssIdentifier: "charts-advanced-settings-top-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: this.chartTranslation.translate("navigator"),
suppressEnabledCheckbox: true,
useToggle: true
}
);
const navigatorHeightSliderParams = this.chartMenuParamsFactory.getDefaultSliderParams(
"navigator.height",
"height",
60
);
navigatorHeightSliderParams.minValue = 10;
const navigatorMiniChartCheckboxParams = this.chartMenuParamsFactory.getDefaultCheckboxParams(
"navigator.miniChart.enabled",
"miniChart"
);
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="navigatorGroup">
<ag-slider data-ref="navigatorHeightSlider"></ag-slider>
<ag-checkbox data-ref="navigatorMiniChartCheckbox"></ag-checkbox>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, AgSliderSelector, import_ag_grid_community235.AgCheckboxSelector],
{
navigatorGroup: navigatorGroupParams,
navigatorHeightSlider: navigatorHeightSliderParams,
navigatorMiniChartCheckbox: navigatorMiniChartCheckboxParams
}
);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/zoomPanel.ts
var import_ag_grid_community236 = require("ag-grid-community");
var ZoomPanel = class extends import_ag_grid_community236.Component {
constructor(chartMenuParamsFactory) {
super();
this.chartMenuParamsFactory = chartMenuParamsFactory;
this.zoomScrollingStepInput = import_ag_grid_community236.RefPlaceholder;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const zoomGroupParams = this.chartMenuParamsFactory.addEnableParams("zoom.enabled", {
cssIdentifier: "charts-advanced-settings-top-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: this.chartTranslation.translate("zoom"),
suppressEnabledCheckbox: true,
useToggle: true
});
const zoomScrollingCheckboxParams = this.chartMenuParamsFactory.getDefaultCheckboxParams(
"zoom.enableScrolling",
"scrollingZoom"
);
const zoomScrollingStepSliderParams = this.chartMenuParamsFactory.getDefaultSliderParams(
"zoom.scrollingStep",
"scrollingStep",
1
);
zoomScrollingStepSliderParams.step = 0.01;
zoomScrollingStepSliderParams.minValue = zoomScrollingStepSliderParams.step;
const zoomSelectingCheckboxParams = this.chartMenuParamsFactory.getDefaultCheckboxParams(
"zoom.enableSelecting",
"selectingZoom"
);
zoomScrollingCheckboxParams.onValueChange = /* @__PURE__ */ ((onValueChange) => (value) => {
if (!onValueChange)
return;
onValueChange(value);
this.zoomScrollingStepInput.setDisabled(!value);
})(zoomScrollingCheckboxParams.onValueChange);
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="zoomGroup">
<ag-checkbox data-ref="zoomSelectingCheckbox"></ag-checkbox>
<ag-checkbox data-ref="zoomScrollingCheckbox"></ag-checkbox>
<ag-slider data-ref="zoomScrollingStepInput"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, import_ag_grid_community236.AgCheckboxSelector, AgSliderSelector],
{
zoomGroup: zoomGroupParams,
zoomScrollingCheckbox: zoomScrollingCheckboxParams,
zoomScrollingStepInput: zoomScrollingStepSliderParams,
zoomSelectingCheckbox: zoomSelectingCheckboxParams
}
);
this.zoomScrollingStepInput.setDisabled(!zoomScrollingCheckboxParams.value);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/advancedSettingsPanel.ts
var INTERACTIVITY_GROUPS = ["navigator", "zoom", "animation", "crosshair"];
var AdvancedSettingsPanel = class extends import_ag_grid_community237.Component {
constructor(chartMenuContext) {
super(
/* html */
`<div class="ag-chart-advanced-settings-wrapper"></div>`
);
this.chartMenuContext = chartMenuContext;
}
postConstruct() {
this.chartPanelFeature = this.createManagedBean(
new ChartPanelFeature(
this.chartMenuContext.chartController,
this.getGui(),
"ag-chart-advanced-settings-section",
(chartType, seriesType) => this.createPanels(chartType, seriesType)
)
);
this.chartPanelFeature.refreshPanels();
}
createPanels(chartType, seriesType) {
INTERACTIVITY_GROUPS.forEach((group) => {
if (!this.isGroupPanelShownForSeries(group, seriesType)) {
return;
}
const comp = this.createPanel(group);
this.chartPanelFeature.addComponent(comp);
});
}
isGroupPanelShownForSeries(group, seriesType) {
return group === "animation" || isCartesian(seriesType) && !isFunnel(seriesType);
}
createPanel(group) {
const { chartMenuParamsFactory, chartAxisMenuParamsFactory } = this.chartMenuContext;
switch (group) {
case "navigator":
return new NavigatorPanel(chartMenuParamsFactory);
case "zoom":
return new ZoomPanel(chartMenuParamsFactory);
case "animation":
return new AnimationPanel(chartMenuParamsFactory);
case "crosshair":
return new CrosshairPanel(chartAxisMenuParamsFactory);
}
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/advancedSettingsMenuFactory.ts
var AdvancedSettingsMenuFactory = class extends import_ag_grid_community238.BeanStub {
constructor() {
super(...arguments);
this.beanName = "advSettingsMenuFactory";
}
showMenu(chartMenuContext, eventSource) {
this.hideMenu();
const menu = this.createBean(new AdvancedSettingsMenu(chartMenuContext));
this.activeDialog = this.createBean(
new AgDialog({
title: this.beans.chartTranslation.translate("advancedSettings"),
component: menu,
width: 300,
height: 400,
resizable: true,
movable: true,
centered: true,
closable: true,
afterGuiAttached: () => {
(0, import_ag_grid_community238._findFocusableElements)(menu.getGui())[0]?.focus();
},
closedCallback: () => {
this.activeMenu = this.destroyBean(this.activeMenu);
this.activeDialog = void 0;
eventSource?.focus({ preventScroll: true });
}
})
);
this.activeMenu = menu;
}
hideMenu() {
if (this.activeDialog) {
this.destroyBean(this.activeDialog);
}
}
destroy() {
this.activeMenu = this.destroyBean(this.activeMenu);
this.activeDialog = this.destroyBean(this.activeDialog);
super.destroy();
}
};
var AdvancedSettingsMenu = class extends import_ag_grid_community238.TabGuardComp {
constructor(chartMenuContext) {
super(
/* html */
`<div class="ag-chart-advanced-settings"></div>`
);
this.chartMenuContext = chartMenuContext;
}
postConstruct() {
this.advancedSettingsPanel = this.createManagedBean(new AdvancedSettingsPanel(this.chartMenuContext));
this.getGui().appendChild(this.advancedSettingsPanel.getGui());
this.initialiseTabGuard({
onTabKeyDown: this.onTabKeyDown.bind(this),
focusTrapActive: true
});
}
onTabKeyDown(e) {
if (e.defaultPrevented) {
return;
}
e.preventDefault();
const backwards = e.shiftKey;
const panelGui = this.advancedSettingsPanel.getGui();
const nextEl = (0, import_ag_grid_community238._findNextFocusableElement)(this.beans, panelGui, false, backwards);
if (nextEl) {
nextEl.focus();
} else {
const focusableElements = (0, import_ag_grid_community238._findFocusableElements)(panelGui);
if (focusableElements.length) {
focusableElements[backwards ? focusableElements.length - 1 : 0].focus();
}
}
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/chartMenuList.ts
var import_ag_grid_community239 = require("ag-grid-community");
var ChartMenuListFactory = class extends import_ag_grid_community239.BeanStub {
constructor() {
super(...arguments);
this.beanName = "chartMenuListFactory";
}
wireBeans(beans) {
this.popupSvc = beans.popupSvc;
this.chartMenuSvc = beans.chartMenuSvc;
this.chartTranslation = beans.chartTranslation;
}
showMenuList(params) {
const { eventSource, showMenu, chartMenuContext } = params;
const areChartToolPanelsEnabled = this.chartMenuSvc.doChartToolPanelsExist(chartMenuContext.chartController);
const menuItems = this.mapWithStockItems(
this.getMenuItems(chartMenuContext.chartController, areChartToolPanelsEnabled),
chartMenuContext,
showMenu,
eventSource,
areChartToolPanelsEnabled
);
if (!menuItems.length) {
return;
}
const chartMenuList = this.createBean(new ChartMenuList(menuItems));
this.activeChartMenuList = chartMenuList;
let multiplier = -1;
let alignSide = "left";
if (this.gos.get("enableRtl")) {
multiplier = 1;
alignSide = "right";
}
const eGui = chartMenuList.getGui();
this.popupSvc.addPopup({
modal: true,
eChild: eGui,
closeOnEsc: true,
closedCallback: () => {
this.destroyBean(chartMenuList);
this.activeChartMenuList = void 0;
if ((0, import_ag_grid_community239._isNothingFocused)(this.beans)) {
eventSource.focus({ preventScroll: true });
}
},
afterGuiAttached: (params2) => chartMenuList.afterGuiAttached(params2),
positionCallback: () => {
{
this.popupSvc.positionPopupByComponent({
type: "chartMenu",
eventSource,
ePopup: eGui,
alignSide,
nudgeX: 4 * multiplier,
nudgeY: 4,
position: "under",
keepWithinBounds: true
});
}
},
ariaLabel: "Chart Menu"
});
}
getMenuItems(chartController, areChartToolPanelsEnabled) {
const defaultItems = [
...areChartToolPanelsEnabled ? ["chartEdit"] : [],
...chartController.isEnterprise() ? ["chartAdvancedSettings"] : [],
chartController.isChartLinked() ? "chartUnlink" : "chartLink",
"chartDownload"
];
const chartMenuItems = this.gos.get("chartMenuItems");
if (!chartMenuItems) {
return defaultItems;
} else if (Array.isArray(chartMenuItems)) {
return chartMenuItems;
} else {
return chartMenuItems(
(0, import_ag_grid_community239._addGridCommonParams)(this.gos, {
defaultItems,
chartId: chartController.getChartId()
})
);
}
}
mapWithStockItems(originalList, chartMenuContext, showMenu, eventSource, areChartToolPanelsEnabled) {
if (!originalList) {
return [];
}
const resultList = [];
originalList.forEach((menuItemOrString) => {
let result;
if (typeof menuItemOrString === "string") {
result = this.getStockMenuItem(
menuItemOrString,
chartMenuContext,
showMenu,
eventSource,
areChartToolPanelsEnabled
);
} else {
result = { ...menuItemOrString };
}
if (!result) {
return;
}
const { subMenu } = result;
if (Array.isArray(subMenu)) {
result.subMenu = this.mapWithStockItems(
subMenu,
chartMenuContext,
showMenu,
eventSource,
areChartToolPanelsEnabled
);
}
resultList.push(result);
});
return resultList;
}
getStockMenuItem(key, chartMenuContext, showMenu, eventSource, areChartToolPanelsEnabled) {
switch (key) {
case "chartEdit":
return areChartToolPanelsEnabled ? this.createMenuItem(this.chartTranslation.translate("chartEdit"), "chartsMenuEdit", showMenu) : null;
case "chartAdvancedSettings":
return this.createMenuItem(
this.chartTranslation.translate("chartAdvancedSettings"),
"chartsMenuAdvancedSettings",
() => this.chartMenuSvc.openAdvancedSettings(chartMenuContext, eventSource)
);
case "chartUnlink":
return chartMenuContext.chartController.isChartLinked() ? this.createMenuItem(
this.chartTranslation.translate("chartUnlink"),
"unlinked",
() => this.chartMenuSvc.toggleLinked(chartMenuContext)
) : null;
case "chartLink":
return !chartMenuContext.chartController.isChartLinked() ? this.createMenuItem(
this.chartTranslation.translate("chartLink"),
"linked",
() => this.chartMenuSvc.toggleLinked(chartMenuContext)
) : null;
case "chartDownload":
return this.createMenuItem(
this.chartTranslation.translate("chartDownload"),
"chartsDownload",
() => this.chartMenuSvc.downloadChart(chartMenuContext)
);
}
return null;
}
createMenuItem(name, iconName, action) {
return {
name,
icon: (0, import_ag_grid_community239._createIconNoSpan)(iconName, this.beans, null),
action
};
}
destroy() {
this.destroyBean(this.activeChartMenuList);
super.destroy();
}
};
var ChartMenuList = class extends import_ag_grid_community239.Component {
constructor(menuItems) {
super(
/* html */
`
<div data-ref="eChartsMenu" role="presentation" class="ag-menu ag-chart-menu-popup"></div>
`
);
this.menuItems = menuItems;
this.eChartsMenu = import_ag_grid_community239.RefPlaceholder;
}
postConstruct() {
this.mainMenuList = this.createManagedBean(new AgMenuList(0));
this.mainMenuList.addMenuItems(this.menuItems);
this.mainMenuList.addEventListener("closeMenu", this.onHidePopup.bind(this));
this.eChartsMenu.appendChild(this.mainMenuList.getGui());
}
onHidePopup() {
this.hidePopupFunc?.();
}
afterGuiAttached({ hidePopup }) {
if (hidePopup) {
this.hidePopupFunc = hidePopup;
this.addDestroyFunc(hidePopup);
}
(0, import_ag_grid_community239._focusInto)(this.mainMenuList.getGui());
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/services/chartCrossFilterService.ts
var import_ag_grid_community240 = require("ag-grid-community");
var ChartCrossFilterService = class extends import_ag_grid_community240.BeanStub {
constructor() {
super(...arguments);
this.beanName = "chartCrossFilterSvc";
}
wireBeans(beans) {
this.colModel = beans.colModel;
this.valueSvc = beans.valueSvc;
this.filterManager = beans.filterManager;
if ((0, import_ag_grid_community240._isClientSideRowModel)(this.gos, beans.rowModel)) {
this.clientSideRowModel = beans.rowModel;
}
}
filter(event, reset = false) {
const filterModel = this.filterManager?.getFilterModel() ?? {};
if (reset) {
this.resetFilters(filterModel);
return;
}
const colId = this.extractFilterColId(event);
if (this.isValidColumnFilter(colId)) {
this.updateFilters(filterModel, event, colId);
} else {
(0, import_ag_grid_community240._warn)(154, { colId });
}
}
resetFilters(filterModel) {
const filtersExist = Object.keys(filterModel).length > 0;
if (filtersExist) {
this.filterManager?.setFilterModel(null);
this.filterManager?.onFilterChanged({ source: "api" });
}
}
updateFilters(filterModel, event, colId) {
const dataKey = this.extractFilterColId(event);
const rawValue = event.datum[dataKey];
if (rawValue === void 0) {
return;
}
const selectedValue = rawValue.toString();
if (event.event.metaKey || event.event.ctrlKey) {
const existingGridValues = this.getCurrentGridValuesForCategory(colId);
const valueAlreadyExists = existingGridValues.includes(selectedValue);
let updatedValues;
if (valueAlreadyExists) {
updatedValues = existingGridValues.filter((v) => v !== selectedValue);
} else {
updatedValues = existingGridValues;
updatedValues.push(selectedValue);
}
filterModel[colId] = this.getUpdatedFilterModel(colId, updatedValues);
} else {
const updatedValues = [selectedValue];
filterModel = { [colId]: this.getUpdatedFilterModel(colId, updatedValues) };
}
this.filterManager?.setFilterModel(filterModel);
}
getUpdatedFilterModel(colId, updatedValues) {
const columnFilterType = this.getColumnFilterType(colId);
if (columnFilterType === "agMultiColumnFilter") {
return { filterType: "multi", filterModels: [null, { filterType: "set", values: updatedValues }] };
}
return { filterType: "set", values: updatedValues };
}
getCurrentGridValuesForCategory(colId) {
const filteredValues = [];
const column = this.getColumnById(colId);
this.clientSideRowModel?.forEachNodeAfterFilter((rowNode) => {
if (column && !rowNode.group) {
const value = this.valueSvc.getValue(column, rowNode) + "";
if (!filteredValues.includes(value)) {
filteredValues.push(value);
}
}
});
return filteredValues;
}
extractFilterColId(event) {
return event.xKey || event.calloutLabelKey;
}
isValidColumnFilter(colId) {
if (colId.indexOf("-filtered-out")) {
colId = colId.replace("-filtered-out", "");
}
const filterType = this.getColumnFilterType(colId);
if (typeof filterType === "boolean") {
return filterType;
}
return ["agSetColumnFilter", "agMultiColumnFilter"].includes(filterType);
}
getColumnFilterType(colId) {
const gridColumn = this.getColumnById(colId);
if (gridColumn) {
const colDef = gridColumn.getColDef();
return colDef.filter;
}
}
getColumnById(colId) {
return this.colModel.getCol(colId);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/services/chartMenuService.ts
var import_ag_grid_community241 = require("ag-grid-community");
var CHART_TOOLBAR_ALLOW_LIST = [
"chartUnlink",
"chartLink",
"chartDownload",
"chartMenu"
];
var CHART_TOOL_PANEL_MENU_OPTIONS = {
settings: "chartSettings",
data: "chartData",
format: "chartFormat"
};
var ChartMenuService = class extends import_ag_grid_community241.BeanStub {
constructor() {
super(...arguments);
this.beanName = "chartMenuSvc";
}
wireBeans(beans) {
this.advSettingsMenuFactory = beans.advSettingsMenuFactory;
}
downloadChart(chartMenuContext, dimensions, fileName, fileFormat) {
chartMenuContext.chartController.getChartProxy().downloadChart(dimensions, fileName, fileFormat);
}
toggleLinked(chartMenuContext) {
chartMenuContext.chartController.detachChartRange();
}
openAdvancedSettings(chartMenuContext, eventSource) {
this.advSettingsMenuFactory?.showMenu(chartMenuContext, eventSource);
}
hideAdvancedSettings() {
this.advSettingsMenuFactory?.hideMenu();
}
getChartToolbarOptions() {
const defaultChartToolbarOptions = ["chartMenu"];
const toolbarItemsFunc = this.gos.getCallback("getChartToolbarItems");
const params = {
defaultItems: defaultChartToolbarOptions
};
return toolbarItemsFunc ? toolbarItemsFunc(params).filter((option) => {
if (!CHART_TOOLBAR_ALLOW_LIST.includes(option)) {
(0, import_ag_grid_community241._warn)(155, { option });
return false;
}
return true;
}) : defaultChartToolbarOptions;
}
getChartToolPanels(chartController) {
const chartToolPanelsDef = this.gos.get("chartToolPanelsDef");
const panelsOverride = chartToolPanelsDef?.panels?.map((panel) => {
const menuOption = CHART_TOOL_PANEL_MENU_OPTIONS[panel];
if (!menuOption) {
(0, import_ag_grid_community241._warn)(156, { panel });
}
return menuOption;
}).filter((panel) => Boolean(panel));
let panels = panelsOverride ?? Object.values(CHART_TOOL_PANEL_MENU_OPTIONS);
if (chartController.isPivotChart()) {
panels = panels.filter((panel) => panel !== "chartData");
}
const defaultToolPanel = chartToolPanelsDef?.defaultToolPanel;
const defaultPanel = defaultToolPanel && CHART_TOOL_PANEL_MENU_OPTIONS[defaultToolPanel] || panels[0];
return {
panels,
defaultPanel
};
}
doesChartToolbarExist() {
const chartToolbarOptions = this.getChartToolbarOptions();
return chartToolbarOptions.length > 0;
}
doChartToolPanelsExist(chartController) {
const { panels } = this.getChartToolPanels(chartController);
return panels.length > 0;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/services/chartTranslationService.ts
var import_ag_grid_community242 = require("ag-grid-community");
var DEFAULT_CHART_TRANSLATIONS = {
pivotChartTitle: "Pivot Chart",
rangeChartTitle: "Range Chart",
settings: "Chart",
data: "Set Up",
format: "Customize",
categories: "Categories",
defaultCategory: "(None)",
series: "Series",
switchCategorySeries: "Switch Category / Series",
categoryValues: "Category Values",
seriesLabels: "Series Labels",
aggregate: "Aggregate",
xyValues: "X Y Values",
paired: "Paired Mode",
axis: "Axis",
xAxis: "Horizontal Axis",
yAxis: "Vertical Axis",
polarAxis: "Polar Axis",
radiusAxis: "Radius Axis",
navigator: "Navigator",
zoom: "Zoom",
animation: "Animation",
crosshair: "Crosshair",
color: "Color",
thickness: "Thickness",
preferredLength: "Preferred Length",
xType: "X Type",
axisType: "Axis Type",
automatic: "Automatic",
category: "Category",
number: "Number",
time: "Time",
timeFormat: "Time Format",
autoRotate: "Auto Rotate",
labelRotation: "Rotation",
circle: "Circle",
polygon: "Polygon",
square: "Square",
cross: "Cross",
diamond: "Diamond",
plus: "Plus",
triangle: "Triangle",
heart: "Heart",
orientation: "Orientation",
fixed: "Fixed",
parallel: "Parallel",
perpendicular: "Perpendicular",
radiusAxisPosition: "Position",
ticks: "Ticks",
gridLines: "Grid Lines",
width: "Width",
height: "Height",
length: "Length",
padding: "Padding",
spacing: "Spacing",
chartStyle: "Chart Style",
title: "Title",
chartTitles: "Titles",
chartTitle: "Chart Title",
chartSubtitle: "Subtitle",
horizontalAxisTitle: "Horizontal Axis Title",
verticalAxisTitle: "Vertical Axis Title",
polarAxisTitle: "Polar Axis Title",
titlePlaceholder: "Chart Title",
background: "Background",
font: "Font",
weight: "Weight",
top: "Top",
right: "Right",
bottom: "Bottom",
left: "Left",
labels: "Labels",
calloutLabels: "Callout Labels",
sectorLabels: "Sector Labels",
positionRatio: "Position Ratio",
size: "Size",
shape: "Shape",
minSize: "Minimum Size",
maxSize: "Maximum Size",
legend: "Legend",
position: "Position",
markerSize: "Marker Size",
markerStroke: "Marker Stroke",
markerPadding: "Marker Padding",
itemSpacing: "Item Spacing",
itemPaddingX: "Item Padding X",
itemPaddingY: "Item Padding Y",
layoutHorizontalSpacing: "Horizontal Spacing",
layoutVerticalSpacing: "Vertical Spacing",
strokeWidth: "Stroke Width",
offset: "Offset",
offsets: "Offsets",
tooltips: "Tooltips",
callout: "Callout",
markers: "Markers",
shadow: "Shadow",
blur: "Blur",
xOffset: "X Offset",
yOffset: "Y Offset",
lineWidth: "Line Width",
lineDash: "Line Dash",
lineDashOffset: "Dash Offset",
scrollingZoom: "Scrolling",
scrollingStep: "Scrolling Step",
selectingZoom: "Selecting",
durationMillis: "Duration (ms)",
crosshairLabel: "Label",
crosshairSnap: "Snap to Node",
normal: "Normal",
bold: "Bold",
italic: "Italic",
boldItalic: "Bold Italic",
predefined: "Predefined",
fillOpacity: "Fill Opacity",
strokeColor: "Line Color",
strokeOpacity: "Line Opacity",
miniChart: "Mini-Chart",
histogramBinCount: "Bin count",
connectorLine: "Connector Line",
seriesItems: "Series Items",
seriesItemType: "Item Type",
seriesItemPositive: "Positive",
seriesItemNegative: "Negative",
seriesItemLabels: "Item Labels",
columnGroup: "Column",
barGroup: "Bar",
pieGroup: "Pie",
lineGroup: "Line",
scatterGroup: "X Y (Scatter)",
areaGroup: "Area",
polarGroup: "Polar",
statisticalGroup: "Statistical",
hierarchicalGroup: "Hierarchical",
specializedGroup: "Specialized",
combinationGroup: "Combination",
groupedColumnTooltip: "Grouped",
stackedColumnTooltip: "Stacked",
normalizedColumnTooltip: "100% Stacked",
groupedBarTooltip: "Grouped",
stackedBarTooltip: "Stacked",
normalizedBarTooltip: "100% Stacked",
pieTooltip: "Pie",
donutTooltip: "Donut",
lineTooltip: "Line",
stackedLineTooltip: "Stacked",
normalizedLineTooltip: "100% Stacked",
groupedAreaTooltip: "Area",
stackedAreaTooltip: "Stacked",
normalizedAreaTooltip: "100% Stacked",
scatterTooltip: "Scatter",
bubbleTooltip: "Bubble",
histogramTooltip: "Histogram",
radialColumnTooltip: "Radial Column",
radialBarTooltip: "Radial Bar",
radarLineTooltip: "Radar Line",
radarAreaTooltip: "Radar Area",
nightingaleTooltip: "Nightingale",
rangeBarTooltip: "Range Bar",
rangeAreaTooltip: "Range Area",
boxPlotTooltip: "Box Plot",
treemapTooltip: "Treemap",
sunburstTooltip: "Sunburst",
waterfallTooltip: "Waterfall",
heatmapTooltip: "Heatmap",
columnLineComboTooltip: "Column & Line",
areaColumnComboTooltip: "Area & Column",
customComboTooltip: "Custom Combination",
innerRadius: "Inner Radius",
startAngle: "Start Angle",
endAngle: "End Angle",
reverseDirection: "Reverse Direction",
groupPadding: "Group Padding",
seriesPadding: "Series Padding",
tile: "Tile",
whisker: "Whisker",
cap: "Cap",
capLengthRatio: "Length Ratio",
labelPlacement: "Placement",
inside: "Inside",
outside: "Outside",
noDataToChart: "No data available to be charted.",
pivotChartRequiresPivotMode: "Pivot Chart requires Pivot Mode enabled.",
chartSettingsToolbarTooltip: "Menu",
chartLinkToolbarTooltip: "Linked to Grid",
chartUnlinkToolbarTooltip: "Unlinked from Grid",
chartDownloadToolbarTooltip: "Download Chart",
chartMenuToolbarTooltip: "Menu",
chartEdit: "Edit Chart",
chartAdvancedSettings: "Advanced Settings",
chartLink: "Link to Grid",
chartUnlink: "Unlink from Grid",
chartDownload: "Download Chart",
histogramFrequency: "Frequency",
seriesChartType: "Series Chart Type",
seriesType: "Series Type",
secondaryAxis: "Secondary Axis",
seriesAdd: "Add a series",
categoryAdd: "Add a category",
bar: "Bar",
column: "Column",
histogram: "Histogram",
advancedSettings: "Advanced Settings",
direction: "Direction",
horizontal: "Horizontal",
vertical: "Vertical",
seriesGroupType: "Group Type",
groupedSeriesGroupType: "Grouped",
stackedSeriesGroupType: "Stacked",
normalizedSeriesGroupType: "100% Stacked",
legendEnabled: "Enabled",
invalidColor: "Color value is invalid",
groupedColumnFull: "Grouped Column",
stackedColumnFull: "Stacked Column",
normalizedColumnFull: "100% Stacked Column",
groupedBarFull: "Grouped Bar",
stackedBarFull: "Stacked Bar",
normalizedBarFull: "100% Stacked Bar",
stackedAreaFull: "Stacked Area",
normalizedAreaFull: "100% Stacked Area",
stackedLineFull: "Stacked Line",
normalizedLineFull: "100% Stacked Line",
customCombo: "Custom Combination",
funnel: "Funnel",
coneFunnel: "Cone Funnel",
pyramid: "Pyramid",
funnelGroup: "Funnel",
funnelTooltip: "Funnel",
coneFunnelTooltip: "Cone Funnel",
pyramidTooltip: "Pyramid",
dropOff: "Drop-Off",
stageLabels: "Stage Labels",
reverse: "Reverse",
tooltipMode: "Tooltip Mode",
tooltipModeSingle: "Single",
tooltipModeShared: "Multiple",
tooltipModeCompact: "Compact",
// menu items
groupedColumn: "Grouped",
stackedColumn: "Stacked",
pie: "Pie",
donut: "Donut",
line: "Line",
scatter: "Scatter",
bubble: "Bubble",
area: "Area",
stackedArea: "Stacked",
radarLine: "Radar Line",
radarArea: "Radar Area",
nightingale: "Nightingale",
radialColumn: "Radial Column",
radialBar: "Radial Bar",
boxPlot: "Box Plot",
rangeBar: "Range Bar",
rangeArea: "Range Area",
treemap: "Treemap",
sunburst: "Sunburst",
waterfall: "Waterfall",
heatmap: "Heatmap",
columnLineCombo: "Column & Line",
AreaColumnCombo: "Area & Column",
// aria
ariaChartMenuClose: "Close Chart Edit Menu",
ariaChartSelected: "Selected",
// group
group: "Group",
// time formats
timeFormatSlashesDDMMYYYY: "DD/MM/YYYY",
timeFormatSlashesMMDDYYYY: "MM/DD/YYYY",
timeFormatSlashesDDMMYY: "DD/MM/YY",
timeFormatSlashesMMDDYY: "MM/DD/YY",
timeFormatDotsDDMYY: "DD.M.YY",
timeFormatDotsMDDYY: "M.DD.YY",
timeFormatDashesYYYYMMDD: "YYYY-MM-DD",
timeFormatSpacesDDMMMMYYYY: "DD MMMM YYYY",
timeFormatHHMMSS: "HH:MM:SS",
timeFormatHHMMSSAmPm: "HH:MM:SS AM/PM",
// agg funcs
sum: "Sum",
first: "First",
last: "Last",
min: "Min",
max: "Max",
count: "Count",
avg: "Average"
};
var ChartTranslationService = class extends import_ag_grid_community242.BeanStub {
constructor() {
super(...arguments);
this.beanName = "chartTranslation";
}
translate(toTranslate) {
const translate = this.getLocaleTextFunc();
const defaultTranslation = DEFAULT_CHART_TRANSLATIONS[toTranslate];
return translate(toTranslate, defaultTranslation);
}
};
// packages/ag-grid-enterprise/src/charts/chartService.ts
var import_ag_grid_community290 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/gridChartComp.ts
var import_ag_grid_community288 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/chartController.ts
var import_ag_grid_community244 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/utils/chartParamsValidator.ts
var import_ag_grid_community243 = require("ag-grid-community");
var validateIfDefined = (validationFn) => {
return (value) => {
if (value == void 0)
return true;
return validationFn(value);
};
};
var isString = (value) => typeof value === "string";
var isBoolean = (value) => typeof value === "boolean";
var isValidSeriesChartType = (value) => typeof value === "object";
var createWarnMessage = (property, expectedType) => (value) => `AG Grid - unable to update chart as invalid params supplied: \`${property}: ${value}\`, expected ${expectedType}.`;
var createEnterpriseMessage = (feature) => {
const url = "https://www.ag-grid.com/javascript-data-grid/integrated-charts-installation/";
return `${feature} is not supported in AG Charts Community ('ag-charts-enterprise' hasn't been loaded). See ${url} for more details.`;
};
var legacyChartTypes = ["doughnut"];
var baseUpdateChartParams = [
"type",
"chartId",
"chartType",
"chartThemeName",
"chartThemeOverrides",
"unlinkChart"
];
function isValidChartType(value) {
return !!getSeriesTypeIfExists(value) || isComboChart(value);
}
function isLegacyChartType(value) {
return legacyChartTypes.includes(value);
}
var validateChartType = validateIfDefined(
(chartType) => {
if (isValidChartType(chartType))
return true;
if (isLegacyChartType(chartType)) {
const renamedChartType = getCanonicalChartType(chartType);
(0, import_ag_grid_community243._warnOnce)(`The chart type '${chartType}' has been deprecated. Please use '${renamedChartType}' instead.`);
return renamedChartType;
}
return false;
}
);
var validateAgChartThemeOverrides = validateIfDefined((themeOverrides) => {
return typeof themeOverrides === "object";
});
var validateChartParamsCellRange = validateIfDefined((cellRange) => {
return typeof cellRange === "object";
});
var validateAggFunc = validateIfDefined((aggFunc) => {
return typeof aggFunc === "string" || typeof aggFunc === "function";
});
var enterpriseChartTypeValidation = (isEnterprise) => ({
property: "chartType",
validationFn: validateIfDefined(
(chartType) => isEnterprise || !chartType || !isEnterpriseChartType(chartType)
),
warnMessage: (chartType) => createEnterpriseMessage(`The '${chartType}' chart type`)
});
var switchCategorySeriesValidation = (isEnterprise) => ({
property: "switchCategorySeries",
validationFn: validateIfDefined((switchCategorySeries) => {
if (!switchCategorySeries || isEnterprise) {
return true;
}
return void 0;
}),
warnMessage: () => createEnterpriseMessage(`'switchCategorySeries' has been ignored as it`),
warnIfFixed: true
});
var commonUpdateValidations = () => [
{ property: "chartId", validationFn: isString, warnMessage: createWarnMessage("chartId", "string") },
{
property: "chartType",
validationFn: validateChartType,
warnMessage: createWarnMessage("chartType", "ChartType")
},
{
property: "chartThemeName",
validationFn: isString,
warnMessage: createWarnMessage("chartThemeName", "string")
},
{
property: "chartThemeOverrides",
validationFn: validateAgChartThemeOverrides,
warnMessage: createWarnMessage("chartThemeOverrides", "AgChartThemeOverrides")
},
{ property: "unlinkChart", validationFn: isBoolean, warnMessage: createWarnMessage("unlinkChart", "boolean") }
];
var cellRangeValidations = (isEnterprise) => [
{
property: "cellRange",
validationFn: validateChartParamsCellRange,
warnMessage: createWarnMessage("cellRange", "ChartParamsCellRange")
},
{
property: "suppressChartRanges",
validationFn: isBoolean,
warnMessage: createWarnMessage("suppressChartRanges", "boolean")
},
{
property: "aggFunc",
validationFn: validateAggFunc,
warnMessage: createWarnMessage("aggFunc", "string or IAggFunc")
},
switchCategorySeriesValidation(isEnterprise)
];
function validateUpdateParams(params, isEnterprise) {
const paramsToValidate = params;
switch (paramsToValidate.type) {
case "rangeChartUpdate":
return validateUpdateRangeChartParams(params, isEnterprise);
case "pivotChartUpdate":
return validateUpdatePivotChartParams(params);
case "crossFilterChartUpdate":
return validateUpdateCrossFilterChartParams(params, isEnterprise);
default:
(0, import_ag_grid_community243._warnOnce)(
`Invalid value supplied for 'type': ${params.type}. It must be either 'rangeChartUpdate', 'pivotChartUpdate', or 'crossFilterChartUpdate'.`
);
return false;
}
}
function validateCreateParams(params, isEnterprise) {
return validateProperties(params, [
enterpriseChartTypeValidation(isEnterprise),
switchCategorySeriesValidation(isEnterprise)
]);
}
function validateUpdateRangeChartParams(params, isEnterprise) {
const validations = [
...commonUpdateValidations(),
enterpriseChartTypeValidation(isEnterprise),
...cellRangeValidations(isEnterprise),
{
property: "seriesChartTypes",
validationFn: (value) => value === void 0 || Array.isArray(value) && value.every(isValidSeriesChartType),
warnMessage: createWarnMessage("seriesChartTypes", "Array of SeriesChartType")
}
];
return validateProperties(
params,
validations,
[
...baseUpdateChartParams,
"cellRange",
"suppressChartRanges",
"switchCategorySeries",
"aggFunc",
"seriesChartTypes",
"seriesGroupType"
],
"UpdateRangeChartParams"
);
}
function validateUpdatePivotChartParams(params) {
const validations = [...commonUpdateValidations()];
return validateProperties(params, validations, [...baseUpdateChartParams], "UpdatePivotChartParams");
}
function validateUpdateCrossFilterChartParams(params, isEnterprise) {
const validations = [
...commonUpdateValidations(),
...cellRangeValidations(isEnterprise)
];
return validateProperties(
params,
validations,
[...baseUpdateChartParams, "cellRange", "suppressChartRanges", "aggFunc"],
"UpdateCrossFilterChartParams"
);
}
function validateProperties(params, validations, validPropertyNames, paramsType) {
let validatedProperties = void 0;
for (const validation of validations) {
const { property, validationFn, warnMessage, warnIfFixed } = validation;
if (property in params) {
const value = params[property];
const validationResult = validationFn(value);
if (validationResult === true)
continue;
if (validationResult === false) {
(0, import_ag_grid_community243._warnOnce)(warnMessage(value));
return false;
}
validatedProperties = validatedProperties || { ...params };
validatedProperties[property] = validationResult;
if (warnIfFixed) {
(0, import_ag_grid_community243._warnOnce)(warnMessage(value));
}
}
}
if (validPropertyNames) {
for (const property of Object.keys(params)) {
if (!validPropertyNames.includes(property)) {
(0, import_ag_grid_community243._warnOnce)(`Unexpected property supplied. ${paramsType} does not contain: \`${property}\`.`);
return false;
}
}
}
if (validatedProperties)
return validatedProperties;
return true;
}
// packages/ag-grid-enterprise/src/charts/chartComp/chartController.ts
var DEFAULT_THEMES = ["ag-default", "ag-material", "ag-sheets", "ag-polychroma", "ag-vivid"];
var ChartController = class extends import_ag_grid_community244.BeanStub {
constructor(model) {
super();
this.model = model;
this.isEnterprise = () => this.agChartsExports.isEnterprise;
}
wireBeans(beans) {
this.rangeSvc = beans.rangeSvc;
this.agChartsExports = beans.agChartsExports;
}
postConstruct() {
this.setChartRange();
if (this.model.unlinked) {
if (this.rangeSvc) {
this.rangeSvc.setCellRanges([]);
}
}
const listener = this.updateForGridChange.bind(this, {});
this.addManagedEventListeners({
cellSelectionChanged: (event) => {
if (event.id && event.id === this.model.chartId) {
this.updateForRangeChange();
}
},
columnMoved: listener,
columnPinned: listener,
columnVisible: listener,
columnRowGroupChanged: listener,
modelUpdated: listener,
cellValueChanged: this.updateForDataChange.bind(this),
cellEditValuesChanged: this.updateForDataChange.bind(this)
});
}
update(params) {
if (!this.validUpdateType(params))
return false;
const validationResult = validateUpdateParams(params, this.agChartsExports.isEnterprise);
if (!validationResult)
return false;
const validParams = validationResult === true ? params : validationResult;
this.applyValidatedChartParams(validParams);
return true;
}
applyValidatedChartParams(params) {
const { chartId, chartType, chartThemeName, unlinkChart } = params;
const common = {
chartId,
pivotChart: this.model.pivotChart,
chartType: chartType ?? this.model.chartType,
chartThemeName: chartThemeName ?? this.model.chartThemeName,
unlinkChart: unlinkChart ?? this.model.unlinked,
cellRange: this.model.suppliedCellRange,
switchCategorySeries: this.model.switchCategorySeries,
aggFunc: this.model.aggFunc,
seriesChartTypes: void 0,
suppressChartRanges: false,
crossFiltering: false
};
const chartModelParams = { ...common };
switch (params.type) {
case "rangeChartUpdate":
chartModelParams.cellRange = this.createCellRange(params) ?? this.model.suppliedCellRange;
chartModelParams.switchCategorySeries = params.switchCategorySeries ?? this.model.switchCategorySeries;
chartModelParams.aggFunc = params.aggFunc ?? this.model.aggFunc;
chartModelParams.seriesChartTypes = params.seriesChartTypes;
chartModelParams.suppressChartRanges = params.suppressChartRanges ?? this.model.suppressChartRanges;
chartModelParams.seriesGroupType = params.seriesGroupType ?? this.model.seriesGroupType;
break;
case "crossFilterChartUpdate":
chartModelParams.cellRange = this.createCellRange(params) ?? this.model.suppliedCellRange;
chartModelParams.switchCategorySeries = false;
chartModelParams.aggFunc = params.aggFunc ?? this.model.aggFunc;
chartModelParams.crossFiltering = true;
chartModelParams.suppressChartRanges = params.suppressChartRanges ?? this.model.suppressChartRanges;
break;
case "pivotChartUpdate":
chartModelParams.switchCategorySeries = false;
break;
}
this.model.updateModel(chartModelParams);
const removeChartCellRanges = chartModelParams.unlinkChart || chartModelParams.suppressChartRanges;
removeChartCellRanges ? this.rangeSvc?.setCellRanges([]) : this.setChartRange();
}
updateForGridChange(params) {
if (this.model.unlinked) {
return;
}
const { maintainColState, setColsFromRange } = params ?? {};
this.model.updateCellRanges({ maintainColState, setColsFromRange });
this.model.updateData();
this.setChartRange();
}
updateForDataChange() {
if (this.model.unlinked) {
return;
}
this.model.updateData();
this.raiseChartModelUpdateEvent();
}
updateForRangeChange() {
this.updateForGridChange({ setColsFromRange: true });
this.raiseChartRangeSelectionChangedEvent();
}
updateForPanelChange(params) {
this.model.updateCellRanges(params);
this.model.updateData();
if (params.skipAnimation) {
this.getChartProxy().getChartRef().skipAnimations();
}
this.setChartRange();
this.raiseChartRangeSelectionChangedEvent();
}
updateThemeOverrides(updatedOverrides) {
this.chartProxy.updateThemeOverrides(updatedOverrides);
}
getChartUpdateParams(updatedOverrides) {
const selectedCols = this.getSelectedValueColState();
const fields = selectedCols.map((c) => ({ colId: c.colId, displayName: c.displayName }));
const data = this.getChartData();
const selectedDimensions = this.getSelectedDimensions();
const params = {
data,
groupData: this.model.groupChartData,
grouping: this.isGrouping(),
categories: selectedDimensions.map((selectedDimension) => ({
id: selectedDimension.colId,
name: selectedDimension.displayName,
chartDataType: this.model.categoryAxisType ?? this.model.getChartDataType(selectedDimension.colId)
})),
fields,
chartId: this.getChartId(),
getCrossFilteringContext: () => ({ lastSelectedChartId: "xxx" }),
//this.params.crossFilteringContext, //TODO
seriesChartTypes: this.getSeriesChartTypes(),
updatedOverrides,
seriesGroupType: this.model.seriesGroupType
};
return this.isCategorySeriesSwitched() ? this.invertCategorySeriesParams(params) : params;
}
invertCategorySeriesParams(params) {
const [category] = params.categories;
const categories = [{ id: DEFAULT_CHART_CATEGORY, name: "" }];
const fields = params.data.map((value, index) => {
const categoryKey = `${category.id}:${index}`;
const categoryValue = value[category.id];
const seriesLabel = categoryValue == null ? "" : String(categoryValue);
return { colId: categoryKey, displayName: seriesLabel };
});
const data = params.fields.map((field) => {
const row = {
[DEFAULT_CHART_CATEGORY]: field.displayName
};
for (const [index, value] of params.data.entries()) {
const categoryKey = `${category.id}:${index}`;
const seriesLabelValue = value[field.colId];
row[categoryKey] = seriesLabelValue;
}
return row;
});
return {
...params,
categories,
fields,
data
};
}
getChartModel() {
const modelType = this.model.pivotChart ? "pivot" : "range";
const seriesChartTypes = this.isComboChart() ? this.model.comboChartModel.seriesChartTypes : void 0;
return {
modelType,
chartId: this.model.chartId,
chartType: this.model.chartType,
chartThemeName: this.getChartThemeName(),
chartOptions: this.chartProxy?.getChartThemeOverrides(),
chartPalette: this.chartProxy?.getChartPalette(),
cellRange: this.getCellRangeParams(),
switchCategorySeries: this.model.switchCategorySeries,
suppressChartRanges: this.model.suppressChartRanges,
aggFunc: this.model.aggFunc,
unlinkChart: this.model.unlinked,
seriesChartTypes,
seriesGroupType: this.model.seriesGroupType
};
}
getChartId() {
return this.model.chartId;
}
getChartData() {
return this.model.chartData;
}
getChartType() {
return this.model.chartType;
}
setChartType(chartType) {
this.updateMultiSeriesAndCategory(this.model.chartType, chartType);
this.model.chartType = chartType;
this.model.comboChartModel.updateSeriesChartTypes();
this.model.switchCategorySeries = false;
this.model.categoryAxisType = void 0;
this.model.seriesGroupType = void 0;
this.raiseChartModelUpdateEvent();
}
isCategorySeriesSwitched() {
return this.model.switchCategorySeries && !this.model.isGrouping();
}
switchCategorySeries(inverted) {
if (!supportsInvertedCategorySeries(this.getChartType()))
return;
this.model.switchCategorySeries = inverted;
this.raiseChartModelUpdateEvent();
}
getAggFunc() {
return this.model.aggFunc;
}
setAggFunc(value, silent) {
if (this.model.aggFunc === value)
return;
this.model.aggFunc = value;
if (silent)
return;
this.model.updateData();
this.raiseChartModelUpdateEvent();
}
updateMultiSeriesAndCategory(previousChartType, chartType) {
const updateForMax = (columns, maxNum) => {
let numSelected = 0;
for (const colState of columns) {
if (!colState.selected)
continue;
if (numSelected >= maxNum) {
colState.selected = false;
} else {
numSelected++;
}
}
if (numSelected === 0) {
columns[0].selected = true;
}
};
const maxNumDimensions = getMaxNumCategories(chartType);
const maxNumSeries = getMaxNumSeries(chartType);
const updateDimensionColState = maxNumDimensions != null && (getMaxNumCategories(previousChartType) ?? 100) > (maxNumDimensions ?? 100);
const updateValueColState = maxNumSeries != null && (getMaxNumSeries(previousChartType) ?? 100) > (maxNumSeries ?? 100);
if (updateDimensionColState) {
updateForMax(this.model.dimensionColState, maxNumDimensions);
}
if (updateValueColState) {
updateForMax(this.model.valueColState, maxNumSeries);
}
if (updateDimensionColState || updateValueColState) {
this.model.resetCellRanges(updateDimensionColState, updateValueColState);
this.setChartRange(true);
}
}
setChartThemeName(chartThemeName, silent) {
this.model.chartThemeName = chartThemeName;
if (!silent) {
this.raiseChartModelUpdateEvent();
}
}
getChartThemeName() {
return this.model.chartThemeName;
}
isPivotChart() {
return this.model.pivotChart;
}
isPivotMode() {
return this.model.isPivotMode();
}
isGrouping() {
return this.model.isGrouping();
}
isCrossFilterChart() {
return this.model.crossFiltering;
}
getThemeNames() {
return this.gos.get("chartThemes") || DEFAULT_THEMES;
}
getThemes() {
const themeNames = this.getThemeNames();
return themeNames.map((themeName) => {
const stockTheme = isStockTheme(themeName, this.agChartsExports._Theme);
const theme = stockTheme ? themeName : this.chartProxy.lookupCustomChartTheme(themeName);
return this.agChartsExports._Theme.getChartTheme(theme);
});
}
getPalettes() {
const themes = this.getThemes();
return themes.map((theme) => {
return theme.palette;
});
}
getValueColState() {
return this.model.valueColState.map(this.displayNameMapper.bind(this));
}
getSelectedValueColState() {
return this.getValueColState().filter((cs) => cs.selected);
}
getSelectedDimensions() {
return this.model.getSelectedDimensions();
}
displayNameMapper(col) {
const { column } = col;
if (column) {
col.displayName = this.model.getColDisplayName(column, this.model.isPivotMode());
} else {
const colNames = this.model.colNames[col.colId];
col.displayName = colNames ? colNames.join(" - ") : this.model.getColDisplayName(column);
}
return col;
}
getColStateForMenu() {
return { dimensionCols: this.model.dimensionColState, valueCols: this.getValueColState() };
}
setChartRange(silent = false) {
if (this.rangeSvc && !this.model.suppressChartRanges && !this.model.unlinked) {
this.rangeSvc.setCellRanges(this.getCellRanges());
}
if (!silent) {
this.raiseChartModelUpdateEvent();
}
}
detachChartRange() {
this.model.unlinked = !this.model.unlinked;
if (this.model.unlinked) {
if (this.rangeSvc) {
this.rangeSvc.setCellRanges([]);
}
} else {
this.updateForGridChange();
}
this.dispatchLocalEvent({ type: "chartLinkedChanged" });
}
setChartProxy(chartProxy) {
this.chartProxy = chartProxy;
}
getChartProxy() {
return this.chartProxy;
}
isActiveXYChart() {
return ["scatter", "bubble"].includes(this.getChartType());
}
isChartLinked() {
return !this.model.unlinked;
}
customComboExists() {
const savedCustomSeriesChartTypes = this.model.comboChartModel.savedCustomSeriesChartTypes;
return savedCustomSeriesChartTypes && savedCustomSeriesChartTypes.length > 0;
}
getSeriesChartTypes() {
return this.model.comboChartModel.seriesChartTypes;
}
isComboChart(chartType) {
return this.model.isComboChart(chartType);
}
updateSeriesChartType(colId, chartType, secondaryAxis) {
const seriesChartType = this.model.comboChartModel.seriesChartTypes.find((s) => s.colId === colId);
if (seriesChartType) {
const updateChartType = this.model.chartType !== "customCombo";
if (updateChartType) {
this.model.chartType = "customCombo";
}
const prevSeriesChartType = seriesChartType.chartType;
if (chartType != null) {
seriesChartType.chartType = chartType;
}
if (secondaryAxis != null) {
seriesChartType.secondaryAxis = secondaryAxis;
}
this.model.comboChartModel.savedCustomSeriesChartTypes = this.model.comboChartModel.seriesChartTypes;
this.model.comboChartModel.updateSeriesChartTypes();
this.updateForDataChange();
if (updateChartType) {
this.dispatchLocalEvent({
type: "chartTypeChanged"
});
}
if (prevSeriesChartType !== chartType) {
this.dispatchLocalEvent({
type: "chartSeriesChartTypeChanged"
});
}
this.raiseChartOptionsChangedEvent();
}
}
getActiveSeriesChartTypes() {
const selectedColIds = this.getSelectedValueColState().map((c) => c.colId);
return this.getSeriesChartTypes().filter((s) => selectedColIds.includes(s.colId));
}
getChartSeriesTypes(chartType) {
const targetChartType = chartType ?? this.getChartType();
return this.isComboChart(targetChartType) ? ["line", "bar", "area"] : [getSeriesType(targetChartType)];
}
getChartSeriesType() {
const seriesChartTypes = this.getSeriesChartTypes();
if (seriesChartTypes.length === 0) {
return "bar";
}
const ct = seriesChartTypes[0].chartType;
if (ct === "columnLineCombo") {
return "bar";
}
if (ct === "areaColumnCombo") {
return "area";
}
return getSeriesType(ct);
}
getCellRanges() {
return [this.model.dimensionCellRange, this.model.valueCellRange].filter((r) => r);
}
createCellRange(params) {
return params.cellRange && this.rangeSvc?.createPartialCellRangeFromRangeParams(params.cellRange, true);
}
validUpdateType(params) {
if (!params.type) {
(0, import_ag_grid_community244._warn)(136);
return false;
}
const chartTypeMap = {
"Range Chart": () => !this.isPivotChart() && !this.isCrossFilterChart(),
"Pivot Chart": () => this.isPivotChart(),
"Cross Filter Chart": () => this.isCrossFilterChart()
};
const currentChartType = Object.keys(chartTypeMap).find((type) => chartTypeMap[type]()) ?? "Range Chart";
const valid = params.type === `${currentChartType[0].toLowerCase()}${currentChartType.slice(1).replace(/ /g, "")}Update`;
if (!valid) {
(0, import_ag_grid_community244._warn)(137, { currentChartType, type: params.type });
}
return valid;
}
getCellRangeParams() {
const cellRanges = this.getCellRanges();
const firstCellRange = cellRanges[0];
const startRow = firstCellRange && firstCellRange.startRow || null;
const endRow = firstCellRange && firstCellRange.endRow || null;
return {
rowStartIndex: startRow && startRow.rowIndex,
rowStartPinned: startRow && startRow.rowPinned,
rowEndIndex: endRow && endRow.rowIndex,
rowEndPinned: endRow && endRow.rowPinned,
columns: cellRanges.reduce(
(columns, value) => columns.concat(value.columns.map((c) => c.getId())),
[]
)
};
}
setCategoryAxisType(categoryAxisType) {
this.model.categoryAxisType = categoryAxisType;
this.raiseChartModelUpdateEvent();
}
getSeriesGroupType() {
return this.model.seriesGroupType ?? this.chartProxy.getSeriesGroupType();
}
setSeriesGroupType(seriesGroupType) {
this.model.seriesGroupType = seriesGroupType;
this.raiseChartModelUpdateEvent();
}
raiseChartModelUpdateEvent() {
this.dispatchLocalEvent({ type: "chartModelUpdate" });
this.raiseChartOptionsChangedEvent();
}
raiseChartUpdatedEvent() {
this.dispatchLocalEvent({ type: "chartUpdated" });
}
raiseChartApiUpdateEvent() {
this.dispatchLocalEvent({ type: "chartApiUpdate" });
}
raiseChartOptionsChangedEvent() {
const { chartId, chartType } = this.getChartModel();
this.eventSvc.dispatchEvent({
type: "chartOptionsChanged",
chartId,
chartType,
chartThemeName: this.getChartThemeName(),
chartOptions: this.chartProxy?.getChartThemeOverrides()
});
}
raiseChartRangeSelectionChangedEvent() {
this.eventSvc.dispatchEvent({
type: "chartRangeSelectionChanged",
id: this.model.chartId,
chartId: this.model.chartId,
cellRange: this.getCellRangeParams()
});
}
destroy() {
super.destroy();
if (this.rangeSvc) {
this.rangeSvc.setCellRanges([]);
}
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/cartesian/areaChartProxy.ts
var AreaChartProxy = class extends CartesianChartProxy {
getAxes(params) {
const axes = [
{
type: this.getXAxisType(params),
position: "bottom"
},
{
type: "number",
position: "left"
}
];
if (this.isNormalised()) {
const numberAxis = axes[1];
numberAxis.label = { ...numberAxis.label, formatter: (params2) => Math.round(params2.value) + "%" };
}
return axes;
}
getSeries(params) {
const [category] = params.categories;
const series = params.fields.map(
(f) => ({
type: this.standaloneChartType,
xKey: category.id,
xName: category.name,
yKey: f.colId,
yName: f.displayName,
normalizedTo: this.chartType === "normalizedArea" ? 100 : void 0,
stacked: ["normalizedArea", "stackedArea"].includes(this.chartType)
})
);
return this.crossFiltering ? this.extractLineAreaCrossFilterSeries(series, params) : series;
}
isNormalised() {
return !this.crossFiltering && this.chartType === "normalizedArea";
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/cartesian/barChartProxy.ts
var HORIZONTAL_CHART_TYPES = /* @__PURE__ */ new Set(["bar", "groupedBar", "stackedBar", "normalizedBar"]);
var BarChartProxy = class extends CartesianChartProxy {
getAxes(params) {
const axes = [
{
type: this.getXAxisType(params),
position: this.isHorizontal() ? "left" : "bottom"
},
{
type: "number",
position: this.isHorizontal() ? "bottom" : "left"
}
];
if (this.isNormalised()) {
const numberAxis = axes[1];
numberAxis.label = { ...numberAxis.label, formatter: (params2) => Math.round(params2.value) + "%" };
}
return axes;
}
getSeries(params) {
const [category] = params.categories;
const series = params.fields.map(
(f) => ({
type: this.standaloneChartType,
direction: this.isHorizontal() ? "horizontal" : "vertical",
stacked: this.crossFiltering || isStacked(this.chartType),
normalizedTo: this.isNormalised() ? 100 : void 0,
xKey: category.id,
xName: category.name,
yKey: f.colId,
yName: f.displayName
})
);
return this.crossFiltering ? this.extractCrossFilterSeries(series) : series;
}
extractCrossFilterSeries(series) {
const allSeries = [];
for (let i = 0; i < series.length; i++) {
const commonSeries = series[i];
const primarySeries = {
...commonSeries,
listeners: {
seriesNodeClick: this.crossFilterCallback
}
};
const filteredOutSeries = {
...primarySeries,
yKey: `${primarySeries.yKey}-filtered-out`,
showInLegend: false
};
allSeries.push(primarySeries);
allSeries.push(filteredOutSeries);
}
return allSeries;
}
isNormalised() {
const normalisedCharts = ["normalizedColumn", "normalizedBar"];
return !this.crossFiltering && normalisedCharts.includes(this.chartType);
}
isHorizontal() {
return HORIZONTAL_CHART_TYPES.has(this.chartType);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/cartesian/lineChartProxy.ts
var LineChartProxy = class extends CartesianChartProxy {
getAxes(params) {
const axes = [
{
type: this.getXAxisType(params),
position: "bottom"
},
{
type: "number",
position: "left"
}
];
if (this.isNormalised()) {
const numberAxis = axes[1];
numberAxis.label = { ...numberAxis.label, formatter: (params2) => Math.round(params2.value) + "%" };
}
return axes;
}
getSeries(params) {
const [category] = params.categories;
const stacked = ["normalizedLine", "stackedLine"].includes(this.chartType);
const series = params.fields.map(
(f) => ({
type: this.standaloneChartType,
xKey: category.id,
xName: category.name,
yKey: f.colId,
yName: f.displayName,
normalizedTo: stacked && this.isNormalised() ? 100 : void 0,
stacked
})
);
return this.crossFiltering ? this.extractLineAreaCrossFilterSeries(series, params) : series;
}
isNormalised() {
const normalisedCharts = ["normalizedLine"];
return !this.crossFiltering && normalisedCharts.includes(this.chartType);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/cartesian/scatterChartProxy.ts
var ScatterChartProxy = class extends CartesianChartProxy {
getAxes(_params) {
return [
{
type: "number",
position: "bottom"
},
{
type: "number",
position: "left"
}
];
}
getSeries(params) {
const [category] = params.categories;
const paired = this.isPaired();
const seriesDefinitions = this.getSeriesDefinitions(params.fields, paired);
const labelFieldDefinition = category.id === DEFAULT_CHART_CATEGORY ? void 0 : category;
const series = seriesDefinitions.map((seriesDefinition) => {
if (seriesDefinition?.sizeField) {
const opts2 = {
type: "bubble",
xKey: seriesDefinition.xField.colId,
xName: seriesDefinition.xField.displayName ?? void 0,
yKey: seriesDefinition.yField.colId,
yName: seriesDefinition.yField.displayName ?? void 0,
title: `${seriesDefinition.yField.displayName} vs ${seriesDefinition.xField.displayName}`,
sizeKey: seriesDefinition.sizeField.colId,
sizeName: seriesDefinition.sizeField.displayName ?? "",
labelKey: labelFieldDefinition ? labelFieldDefinition.id : seriesDefinition.yField.colId,
labelName: labelFieldDefinition ? labelFieldDefinition.name : void 0
};
return opts2;
}
const opts = {
type: "scatter",
xKey: seriesDefinition.xField.colId,
xName: seriesDefinition.xField.displayName ?? void 0,
yKey: seriesDefinition.yField.colId,
yName: seriesDefinition.yField.displayName ?? void 0,
title: `${seriesDefinition.yField.displayName} vs ${seriesDefinition.xField.displayName}`,
labelKey: labelFieldDefinition ? labelFieldDefinition.id : seriesDefinition.yField.colId,
labelName: labelFieldDefinition ? labelFieldDefinition.name : void 0
};
return opts;
});
return this.crossFiltering ? this.extractCrossFilterSeries(series, params) : series;
}
extractCrossFilterSeries(series, params) {
const { data } = params;
const filteredOutKey = (key) => `${key}-filtered-out`;
const calcMarkerDomain = (data2, sizeKey) => {
const markerDomain = [Infinity, -Infinity];
if (sizeKey != null) {
for (const datum of data2) {
const value = datum[sizeKey] ?? datum[filteredOutKey(sizeKey)];
if (value < markerDomain[0]) {
markerDomain[0] = value;
}
if (value > markerDomain[1]) {
markerDomain[1] = value;
}
}
}
if (markerDomain[0] <= markerDomain[1]) {
return markerDomain;
}
return void 0;
};
const updatePrimarySeries = (series2) => {
let markerDomain = void 0;
if (series2.type === "bubble") {
const { sizeKey } = series2;
markerDomain = calcMarkerDomain(data, sizeKey);
}
return {
...series2,
domain: markerDomain,
highlight: { highlightedItem: { fill: "yellow" } },
listeners: {
...series2.listeners,
seriesNodeClick: this.crossFilterCallback
}
};
};
const updateFilteredOutSeries = (series2) => {
const { yKey, xKey } = series2;
let alteredSizeKey = {};
if (series2.type === "bubble") {
alteredSizeKey = { sizeKey: filteredOutKey(series2.sizeKey) };
}
return {
...series2,
...alteredSizeKey,
yKey: filteredOutKey(yKey),
xKey: filteredOutKey(xKey),
showInLegend: false,
listeners: {
...series2.listeners,
seriesNodeClick: (e) => {
const value = e.datum[filteredOutKey(xKey)];
const filterableEvent = {
...e,
xKey,
datum: { ...e.datum, [xKey]: value }
};
this.crossFilterCallback(filterableEvent);
}
}
};
};
const updatedSeries = series.map(updatePrimarySeries);
return [...updatedSeries, ...updatedSeries.map(updateFilteredOutSeries)];
}
getSeriesDefinitions(fields, paired) {
if (fields.length < 2) {
return [];
}
const isBubbleChart = this.chartType === "bubble";
if (paired) {
if (isBubbleChart) {
return fields.map(
(currentXField, i) => i % 3 === 0 ? {
xField: currentXField,
yField: fields[i + 1],
sizeField: fields[i + 2]
} : null
).filter((x) => x && x.yField && x.sizeField);
}
return fields.map(
(currentXField, i) => i % 2 === 0 ? {
xField: currentXField,
yField: fields[i + 1]
} : null
).filter((x) => x && x.yField);
}
const xField = fields[0];
if (isBubbleChart) {
return fields.map(
(yField, i) => i % 2 === 1 ? {
xField,
yField,
sizeField: fields[i + 1]
} : null
).filter((x) => x && x.sizeField);
}
return fields.filter((value, i) => i > 0).map((yField) => ({ xField, yField }));
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/combo/comboChartProxy.ts
var ComboChartProxy = class extends CartesianChartProxy {
getAxes(params) {
const fields = params ? params.fields : [];
const fieldsMap = new Map(fields.map((f) => [f.colId, f]));
const { primaryYKeys, secondaryYKeys } = this.getYKeys(fields, params.seriesChartTypes);
const axes = [
{
type: this.getXAxisType(params),
position: "bottom"
}
];
if (primaryYKeys.length > 0) {
axes.push({
type: "number",
keys: primaryYKeys,
position: "left"
});
}
if (secondaryYKeys.length > 0) {
secondaryYKeys.forEach((secondaryYKey) => {
const field = fieldsMap.get(secondaryYKey);
const secondaryAxisIsVisible = field && field.colId === secondaryYKey;
if (!secondaryAxisIsVisible) {
return;
}
const secondaryAxisOptions = {
type: "number",
keys: [secondaryYKey],
position: "right"
};
axes.push(secondaryAxisOptions);
});
}
return axes;
}
getSeries(params) {
const { fields, seriesChartTypes } = params;
const [category] = params.categories;
return fields.map((field) => {
const seriesChartType = seriesChartTypes.find((s) => s.colId === field.colId);
if (seriesChartType) {
const chartType = seriesChartType.chartType;
const grouped = ["groupedColumn", "groupedBar"].includes(chartType);
const groupedOpts = grouped ? { grouped: true } : {};
return {
type: getSeriesType(chartType),
xKey: category.id,
yKey: field.colId,
yName: field.displayName,
stacked: ["stackedArea", "stackedColumn"].includes(chartType),
...groupedOpts
};
}
});
}
getYKeys(fields, seriesChartTypes) {
const primaryYKeys = [];
const secondaryYKeys = [];
fields.forEach((field) => {
const colId = field.colId;
const seriesChartType = seriesChartTypes.find((s) => s.colId === colId);
if (seriesChartType) {
seriesChartType.secondaryAxis ? secondaryYKeys.push(colId) : primaryYKeys.push(colId);
}
});
return { primaryYKeys, secondaryYKeys };
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/pie/pieChartProxy.ts
function calculateOffsets(offset) {
const outerRadiusOffset = offset.currentOffset;
offset.currentOffset -= offset.offsetAmount;
const innerRadiusOffset = offset.currentOffset;
offset.currentOffset -= offset.offsetAmount;
return { outerRadiusOffset, innerRadiusOffset };
}
var PieChartProxy = class extends ChartProxy {
getUpdateOptions(params, commonChartOptions) {
return {
...commonChartOptions,
data: this.crossFiltering ? this.getCrossFilterData(params) : params.data,
series: this.getSeries(params)
};
}
getSeries(params) {
const [category] = params.categories;
const numFields = params.fields.length;
const offset = {
currentOffset: 0,
offsetAmount: numFields > 1 ? 20 : 40
};
const series = this.getFields(params).map(
(f) => {
const options = {
type: this.standaloneChartType,
angleKey: f.colId,
angleName: f.displayName,
sectorLabelKey: f.colId,
calloutLabelName: category.name,
calloutLabelKey: category.id
};
if (this.chartType === "donut" || this.chartType === "doughnut") {
const { outerRadiusOffset, innerRadiusOffset } = calculateOffsets(offset);
const title = f.displayName ? {
title: { text: f.displayName, showInLegend: numFields > 1 }
} : void 0;
return {
...options,
type: "donut",
outerRadiusOffset,
innerRadiusOffset,
...title
};
}
return options;
}
);
return this.crossFiltering ? this.extractCrossFilterSeries(series) : series;
}
getCrossFilterData(params) {
const colId = params.fields[0].colId;
const filteredOutColId = `${colId}-filtered-out`;
return params.data.map((d) => {
const total = d[colId] + d[filteredOutColId];
d[`${colId}-total`] = total;
d[filteredOutColId] = 1;
d[colId] = d[colId] / total;
return d;
});
}
extractCrossFilterSeries(series) {
const primarySeries = series[0];
const angleKey = primarySeries.angleKey;
const commonOptions = {
...primarySeries,
radiusMin: 0,
radiusMax: 1,
listeners: {
seriesNodeClick: this.crossFilterCallback
},
legendItemKey: primarySeries.calloutLabelKey,
angleKey: `${angleKey}-total`
};
const primaryOptions = {
...commonOptions,
radiusKey: angleKey,
sectorLabelKey: `${angleKey}-total`
};
const filteredOutOptions = {
...commonOptions,
radiusKey: `${angleKey}-filtered-out`,
showInLegend: false
};
return [filteredOutOptions, primaryOptions];
}
getFields(params) {
return this.chartType === "pie" ? params.fields.slice(0, 1) : params.fields;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/chartMenu.ts
var import_ag_grid_community286 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/chartToolbar.ts
var import_ag_grid_community245 = require("ag-grid-community");
var ChartToolbar = class extends import_ag_grid_community245.Component {
constructor() {
super(
/* html */
`<div class="ag-chart-menu" data-ref="eMenu"></div>`
);
this.eMenu = import_ag_grid_community245.RefPlaceholder;
this.buttonListenersDestroyFuncs = [];
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
updateParams(params) {
const { buttons } = params;
this.createButtons(buttons);
}
createButtons(buttons) {
this.buttonListenersDestroyFuncs.forEach((func) => func?.());
this.buttonListenersDestroyFuncs = [];
const menuEl = this.eMenu;
(0, import_ag_grid_community245._clearElement)(menuEl);
buttons.forEach((buttonConfig) => {
const { buttonName, iconName, callback } = buttonConfig;
const buttonEl = this.createButton(iconName);
const tooltipTitle = this.chartTranslation.translate(
buttonName + "ToolbarTooltip"
);
if (tooltipTitle && buttonEl instanceof HTMLElement) {
buttonEl.title = tooltipTitle;
}
this.buttonListenersDestroyFuncs.push(
...this.addManagedElementListeners(buttonEl, {
click: (event) => callback(event.currentTarget)
})
);
menuEl.appendChild(buttonEl);
});
}
createButton(iconName) {
const buttonEl = (0, import_ag_grid_community245._createIconNoSpan)(iconName, this.beans);
buttonEl.classList.add("ag-chart-menu-icon");
const wrapperEl = (0, import_ag_grid_community245._createElement)({
tag: "button",
attrs: { type: "button" },
cls: "ag-chart-menu-toolbar-button"
});
wrapperEl.appendChild(buttonEl);
return wrapperEl;
}
destroy() {
this.buttonListenersDestroyFuncs = [];
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/tabbedChartMenu.ts
var import_ag_grid_community285 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/data/chartDataPanel.ts
var import_ag_grid_community253 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/data/categoriesDataPanel.ts
var import_ag_grid_community248 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/data/dragDataPanel.ts
var import_ag_grid_community247 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/widgets/agPillSelect.ts
var import_ag_grid_community246 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/widgets/agPillSelect.css-GENERATED.ts
var agPillSelectCSS = (
/*css*/
`.ag-pill-select{display:flex;flex-direction:column}:where(.ag-pill-select){.ag-column-drop-list{padding:0}.ag-select{padding-top:var(--ag-spacing)}.ag-picker-field-wrapper{background-color:transparent;border:0}.ag-picker-field-display{cursor:pointer;font-weight:500}.ag-picker-field-display,.ag-picker-field-icon{color:var(--ag-chart-menu-label-color)}}`
);
// packages/ag-grid-enterprise/src/charts/widgets/agPillSelect.ts
var AgPillSelect = class extends import_ag_grid_community246.Component {
constructor(config) {
super(
/* html */
`<div class="ag-pill-select" role="presentation"></div>`
);
this.config = config ?? {};
const { selectedValueList, valueFormatter, valueList } = this.config;
this.selectedValues = selectedValueList ?? [];
this.valueList = valueList ?? [];
this.valueFormatter = valueFormatter ?? ((value) => (0, import_ag_grid_community246._escapeString)(value));
this.registerCSS(agPillSelectCSS);
}
postConstruct() {
const { ariaLabel, onValuesChange, dragSourceId } = this.config;
this.dropZonePanel = this.createManagedBean(
new PillSelectDropZonePanel(
{
getValues: () => this.selectedValues,
setValues: (values) => this.updateValues(values),
isDraggable: () => this.selectedValues.length > 1
},
(value) => this.valueFormatter(value),
ariaLabel,
dragSourceId
)
);
const eGui = this.getGui();
eGui.appendChild(this.dropZonePanel.getGui());
this.initSelect();
if (onValuesChange != null) {
this.onValuesChange = onValuesChange;
}
}
setValues(valueList, selectedValues) {
const { added, removed, updated } = this.getChanges(this.valueList, valueList);
let refreshSelect = false;
if (added.length || removed.length || updated.length) {
refreshSelect = true;
}
this.valueList = valueList;
this.updateValues(selectedValues, refreshSelect, true);
return this;
}
setValueFormatter(valueFormatter) {
this.valueFormatter = valueFormatter;
return this;
}
initSelect() {
const options = this.createSelectOptions();
if (!options.length) {
return false;
}
const { selectPlaceholder: placeholder } = this.config;
this.eSelect = this.createBean(
new import_ag_grid_community246.AgSelect({
options,
placeholder,
onValueChange: (value) => this.addValue(value),
pickerIcon: "chartsMenuAdd"
})
);
this.getGui().appendChild(this.eSelect.getGui());
return true;
}
createSelectOptions() {
const options = [];
const { maxSelection } = this.config;
if (maxSelection && this.selectedValues.length >= maxSelection) {
return options;
}
this.valueList.forEach((value) => {
if (!this.selectedValues.includes(value)) {
options.push({ value, text: this.valueFormatter(value) });
}
});
return options;
}
addValue(value) {
this.dropZonePanel.addItem(value);
}
updateValues(values, forceRefreshSelect, silent) {
const previousSelectedValues = this.selectedValues;
this.selectedValues = values;
const changes = this.getChanges(previousSelectedValues, values);
const refreshSelect = forceRefreshSelect || changes.added.length || changes.removed.length;
const activeElement = (0, import_ag_grid_community246._getActiveDomElement)(this.beans);
const selectHasFocus = this.eSelect?.getGui().contains(activeElement);
const dropZoneHasFocus = this.dropZonePanel?.getGui().contains(activeElement);
if (!silent) {
this.onValuesChange?.(changes);
}
const emptyRefreshedSelect = refreshSelect ? !this.refreshSelect() : false;
this.dropZonePanel.refreshGui();
if (refreshSelect && selectHasFocus) {
if (emptyRefreshedSelect) {
this.dropZonePanel.focusList(true);
} else {
this.eSelect?.getFocusableElement().focus();
}
}
if (dropZoneHasFocus && !values.length) {
this.eSelect?.getFocusableElement().focus();
}
}
getChanges(previousSelectedValues, newSelectedValues) {
const added = newSelectedValues.filter((value) => !previousSelectedValues.includes(value));
const removed = previousSelectedValues.filter((value) => !newSelectedValues.includes(value));
const updated = newSelectedValues.filter((value, index) => previousSelectedValues[index] !== value);
return { added, removed, updated, selected: newSelectedValues };
}
refreshSelect() {
if (!this.eSelect) {
return this.initSelect();
}
const options = this.createSelectOptions();
if (!options.length) {
(0, import_ag_grid_community246._removeFromParent)(this.eSelect.getGui());
this.eSelect = this.destroyBean(this.eSelect);
return false;
}
this.eSelect.clearOptions().addOptions(options).setValue(void 0, true);
return true;
}
destroy() {
this.destroyBean(this.eSelect);
super.destroy();
}
};
var PillSelectDragComp = class extends PillDragComp {
constructor(value, dragSourceDropTarget, ghost, valueFormatter, draggable, sourceId) {
super(dragSourceDropTarget, ghost, false);
this.value = value;
this.valueFormatter = valueFormatter;
this.draggable = draggable;
this.sourceId = sourceId;
}
getItem() {
return this.value;
}
getDisplayName() {
return this.valueFormatter(this.value);
}
getAriaDisplayName() {
return this.getDisplayName();
}
getTooltip() {
return void 0;
}
createGetDragItem() {
return () => ({
value: this.value
});
}
getDragSourceType() {
return import_ag_grid_community246.DragSourceType.ChartPanel;
}
getDragSourceId() {
return this.sourceId;
}
isMovable() {
return this.isDraggable();
}
isDraggable() {
return this.draggable;
}
};
var PillSelectDropZonePanel = class extends PillDropZonePanel {
constructor(model, valueFormatter, ariaLabel, sourceId) {
super(false);
this.model = model;
this.valueFormatter = valueFormatter;
this.ariaLabel = ariaLabel;
this.sourceId = sourceId;
}
postConstruct() {
super.init();
}
isItemDroppable(item, draggingEvent) {
return this.isSourceEventFromTarget(draggingEvent) || this.sourceId != null && this.sourceId === draggingEvent.dragSource.sourceId;
}
updateItems(items) {
this.model.setValues(items);
}
getExistingItems() {
return this.model.getValues();
}
getIconName() {
return this.isPotentialDndItems() ? "move" : "notAllowed";
}
getAriaLabel() {
return this.ariaLabel;
}
createPillComponent(item, dropTarget, ghost) {
return new PillSelectDragComp(
item,
dropTarget,
ghost,
this.valueFormatter,
this.model.isDraggable(),
this.sourceId
);
}
getItems(dragItem) {
return [dragItem.value];
}
isInterestedIn(type) {
return type === import_ag_grid_community246.DragSourceType.ChartPanel;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/data/dragDataPanel.ts
var DragDataPanel = class extends import_ag_grid_community247.Component {
constructor(chartController, allowMultipleSelection, maxSelection, template) {
super(template);
this.chartController = chartController;
this.allowMultipleSelection = allowMultipleSelection;
this.maxSelection = maxSelection;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
addItem(eItem) {
this.groupComp.addItem(eItem);
}
createGroup(columns, valueFormatter, selectLabelKey, dragSourceId, skipAnimation) {
if (this.allowMultipleSelection) {
const selectedValueList = columns.filter((col) => col.selected);
this.valuePillSelect = this.groupComp.createManagedBean(
new AgPillSelect({
valueList: columns,
selectedValueList,
valueFormatter,
selectPlaceholder: this.chartTranslation.translate(selectLabelKey),
dragSourceId,
onValuesChange: (params) => this.onValueChange(params),
maxSelection: this.maxSelection
})
);
this.groupComp.addItem(this.valuePillSelect);
} else {
const params = this.createValueSelectParams(columns);
params.onValueChange = (updatedColState) => {
columns.forEach((col) => {
col.selected = false;
});
updatedColState.selected = true;
if (updatedColState.colId === DEFAULT_CHART_CATEGORY) {
this.chartController.setAggFunc(void 0, true);
}
this.chartController.updateForPanelChange({ updatedColState, skipAnimation: skipAnimation?.() });
};
this.valueSelect = this.groupComp.createManagedBean(new import_ag_grid_community247.AgSelect(params));
this.groupComp.addItem(this.valueSelect);
}
}
refreshValueSelect(columns) {
if (!this.valueSelect) {
return;
}
const { options, value } = this.createValueSelectParams(columns);
this.valueSelect.clearOptions().addOptions(options).setValue(value, true);
}
createValueSelectParams(columns) {
let selectedValue;
const options = columns.map((value) => {
const text = value.displayName ?? "";
if (value.selected) {
selectedValue = value;
}
return {
value,
text
};
});
return {
options,
value: selectedValue
};
}
onValueChange({ added, updated, removed, selected }) {
let updatedColState;
let resetOrder;
const updateOrder = () => {
selected.forEach((col, index) => {
col.order = index;
});
resetOrder = true;
};
if (added.length) {
updatedColState = added[0];
updatedColState.selected = true;
updateOrder();
} else if (removed.length) {
updatedColState = removed[0];
updatedColState.selected = false;
} else if (updated.length) {
updateOrder();
updatedColState = updated[0];
}
if (updatedColState) {
this.chartController.updateForPanelChange({ updatedColState, resetOrder });
}
}
destroy() {
this.valuePillSelect = void 0;
this.valueSelect = void 0;
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/data/categoriesDataPanel.ts
var DEFAULT_AGG_FUNC = "sum";
var CategoriesDataPanel = class extends DragDataPanel {
constructor(chartController, title, allowMultipleSelection, dimensionCols, isOpen) {
const maxSelection = void 0;
super(
chartController,
allowMultipleSelection,
maxSelection,
/* html */
`<div id="categoriesGroup"></div>`
);
this.title = title;
this.dimensionCols = dimensionCols;
this.isOpen = isOpen;
}
postConstruct() {
this.groupComp = this.createBean(
new AgGroupComponent({
title: this.title,
enabled: true,
suppressEnabledCheckbox: true,
suppressOpenCloseIcons: false,
cssIdentifier: "charts-data",
expanded: this.isOpen
})
);
this.createGroup(
this.dimensionCols,
(col) => col.displayName ?? "",
"categoryAdd",
"categorySelect",
() => !this.chartController.getAggFunc()
);
this.createAggFuncControls(this.dimensionCols);
this.getGui().appendChild(this.groupComp.getGui());
}
refresh(dimensionCols) {
this.valuePillSelect?.setValues(
dimensionCols,
dimensionCols.filter((col) => col.selected)
);
this.refreshValueSelect(dimensionCols);
this.refreshAggFuncControls(dimensionCols, this.chartController.getAggFunc());
}
createAggFuncControls(dimensionCols) {
const aggFunc = this.chartController.getAggFunc();
this.groupComp.addItem(
this.aggFuncToggle = this.createBean(
new import_ag_grid_community248.AgToggleButton({
label: this.chartTranslation.translate("aggregate"),
labelAlignment: "left",
labelWidth: "flex",
inputWidth: "flex",
value: aggFunc != void 0,
onValueChange: (value) => {
const aggFunc2 = value ? DEFAULT_AGG_FUNC : void 0;
this.chartController.setAggFunc(aggFunc2);
this.aggFuncSelect?.setValue(aggFunc2, true);
this.aggFuncSelect?.setDisplayed(aggFunc2 != void 0);
}
})
)
);
this.groupComp.addItem(
this.aggFuncSelect = this.createBean(
new import_ag_grid_community248.AgSelect({
options: [
{ value: "sum", text: this.chartTranslation.translate("sum") },
{ value: "first", text: this.chartTranslation.translate("first") },
{ value: "last", text: this.chartTranslation.translate("last") },
{ value: "min", text: this.chartTranslation.translate("min") },
{ value: "max", text: this.chartTranslation.translate("max") },
{ value: "count", text: this.chartTranslation.translate("count") },
{ value: "avg", text: this.chartTranslation.translate("avg") }
],
value: typeof aggFunc === "string" ? aggFunc : void 0,
onValueChange: (value) => {
this.chartController.setAggFunc(value);
}
})
)
);
this.refreshAggFuncControls(dimensionCols, aggFunc);
}
refreshAggFuncControls(dimensionCols, aggFunc) {
const selectedDimensions = dimensionCols.filter((col) => col.selected);
const supportsAggregation = selectedDimensions.some((col) => col.colId !== DEFAULT_CHART_CATEGORY);
this.aggFuncToggle?.setValue(aggFunc != void 0);
this.aggFuncSelect?.setValue(typeof aggFunc === "string" ? aggFunc : void 0, true);
this.aggFuncToggle?.setDisplayed(supportsAggregation);
this.aggFuncSelect?.setDisplayed(supportsAggregation && aggFunc != void 0);
}
clearAggFuncControls() {
this.aggFuncToggle = this.destroyBean(this.aggFuncToggle);
this.aggFuncSelect = this.destroyBean(this.aggFuncSelect);
}
destroy() {
this.clearAggFuncControls();
this.groupComp = this.destroyBean(this.groupComp);
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/data/chartSpecificDataPanel.ts
var import_ag_grid_community250 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/chartMenuParamsFactory.ts
var import_ag_grid_community249 = require("ag-grid-community");
var ChartMenuParamsFactory = class extends import_ag_grid_community249.BeanStub {
constructor(chartOptionsProxy) {
super();
this.chartOptionsProxy = chartOptionsProxy;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
getDefaultColorPickerParams(expression, labelKey, options) {
return this.addValueParams(
expression,
{
label: this.chartTranslation.translate(labelKey ?? "color"),
labelWidth: "flex",
inputWidth: "flex",
labelAlignment: "top",
pickerGap: 6
},
options
);
}
getDefaultNumberInputParams(expression, labelKey, options) {
return this.addValueParams(
expression,
{
label: this.chartTranslation.translate(labelKey),
labelAlignment: "top",
labelWidth: "flex",
inputWidth: "flex",
precision: options?.precision,
step: options?.step,
min: options?.min,
max: options?.max
},
{
parseInputValue: (value) => {
const numberValue = Number(value);
return isNaN(numberValue) ? void 0 : numberValue;
},
formatInputValue: (value) => {
return value == null ? "" : `${value}`;
}
}
);
}
getDefaultSliderParams(expression, labelKey, defaultMaxValue, isArray) {
let value = this.chartOptionsProxy.getValue(expression) ?? 0;
if (isArray && Array.isArray(value)) {
value = value[0];
}
const params = this.getDefaultSliderParamsWithoutValueParams(value, labelKey, defaultMaxValue);
params.onValueChange = (value2) => this.chartOptionsProxy.setValue(expression, isArray ? [value2] : value2);
return params;
}
getDefaultSliderParamsWithoutValueParams(value, labelKey, defaultMaxValue) {
return {
label: this.chartTranslation.translate(labelKey),
minValue: 0,
maxValue: Math.max(value, defaultMaxValue),
textFieldWidth: 45,
value: `${value}`
};
}
getDefaultCheckboxParams(expression, labelKey, options) {
const value = this.chartOptionsProxy.getValue(expression);
const params = {
label: this.chartTranslation.translate(labelKey),
value,
readOnly: options?.readOnly,
passive: options?.passive
};
params.onValueChange = (value2) => {
this.chartOptionsProxy.setValue(expression, typeof value2 === "boolean" ? value2 : void 0);
};
return params;
}
getDefaultToggleParams(expression, labelKey, options) {
const value = this.chartOptionsProxy.getValue(expression);
const params = {
label: this.chartTranslation.translate(labelKey),
labelAlignment: "left",
labelWidth: "flex",
inputWidth: "flex",
value,
readOnly: options?.readOnly,
passive: options?.passive
};
params.onValueChange = (value2) => {
this.chartOptionsProxy.setValue(expression, typeof value2 === "boolean" ? value2 : void 0);
};
return params;
}
getDefaultSelectParams(expression, labelKey, dropdownOptions) {
return this.getDefaultSelectParamsWithoutValueParams(
labelKey,
dropdownOptions,
this.chartOptionsProxy.getValue(expression),
(value) => {
this.chartOptionsProxy.setValue(expression, value);
}
);
}
getDefaultSelectParamsWithoutValueParams(labelKey, options, value, onValueChange) {
return {
label: this.chartTranslation.translate(labelKey),
labelAlignment: "top",
options,
pickerGap: 6,
value,
onValueChange
};
}
getDefaultFontPanelParams(expression, labelKey) {
const keyMapper = (key) => `${expression}.${key}`;
return this.addEnableParams(keyMapper("enabled"), {
name: this.chartTranslation.translate(labelKey),
suppressEnabledCheckbox: false,
chartMenuParamsFactory: this,
keyMapper
});
}
addValueParams(expression, params, options) {
const optionsValue = this.chartOptionsProxy.getValue(expression);
params.value = options?.formatInputValue ? options.formatInputValue(optionsValue) : optionsValue;
params.onValueChange = (value) => {
const optionsValue2 = options?.parseInputValue ? options.parseInputValue(value) : value;
this.chartOptionsProxy.setValue(expression, optionsValue2);
};
return params;
}
addEnableParams(expression, params) {
params.enabled = this.chartOptionsProxy.getValue(expression) ?? false;
params.onEnableChange = (value) => this.chartOptionsProxy.setValue(expression, value);
return params;
}
getChartOptions() {
return this.chartOptionsProxy;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/data/chartSpecificDataPanel.ts
var ChartSpecificDataPanel = class extends import_ag_grid_community250.Component {
constructor(chartMenuContext, isOpen) {
super();
this.chartMenuContext = chartMenuContext;
this.isOpen = isOpen;
this.chartSpecificGroup = import_ag_grid_community250.RefPlaceholder;
this.hasContent = false;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
this.chartSvc = beans.chartSvc;
}
postConstruct() {
const title = this.getTitle();
const chartSpecificGroupParams = {
title,
enabled: true,
suppressEnabledCheckbox: true,
suppressOpenCloseIcons: false,
cssIdentifier: "charts-data",
expanded: this.isOpen,
items: [...this.createDirectionSelect(), this.createReverseSelect(), this.createGroupTypeSelect()]
};
this.setTemplate(
/* html */
`
<div id="chartSpecificGroup">
<ag-group-component data-ref="chartSpecificGroup"></ag-group-component>
</div>`,
[AgGroupComponentSelector],
{
chartSpecificGroup: chartSpecificGroupParams
}
);
this.setDisplayed(this.hasContent);
}
refresh() {
this.hasContent = false;
this.chartSpecificGroup.setTitle(this.getTitle());
this.updateDirectionSelect();
this.updateReverseSelect();
this.updateGroupTypeSelect();
this.setDisplayed(this.hasContent);
}
getTitle() {
const chartType = this.chartMenuContext.chartController.getChartType();
return this.chartTranslation.translate(getFullChartNameTranslationKey(chartType));
}
createDirectionSelect() {
if (!this.chartSvc.isEnterprise()) {
return [];
}
const { chartOptionsService, chartController } = this.chartMenuContext;
const chartOptionsSeriesProxy = chartOptionsService.getSeriesOptionsProxy(
() => getSeriesType(chartController.getChartType())
);
const chartSeriesMenuParamsFactory = this.createManagedBean(
new ChartMenuParamsFactory(chartOptionsSeriesProxy)
);
const options = ["horizontal", "vertical"].map((value) => ({
value,
text: this.chartTranslation.translate(value)
}));
const params = chartSeriesMenuParamsFactory.getDefaultSelectParams("direction", "direction", options);
const onValueChange = params.onValueChange;
params.onValueChange = (value) => {
onValueChange(value);
chartController.raiseChartModelUpdateEvent();
};
this.directionSelect = this.createManagedBean(new import_ag_grid_community250.AgSelect(params));
this.updateDirectionSelect();
return [this.directionSelect];
}
createReverseSelect() {
const { chartMenuParamsFactory } = this.chartMenuContext;
const params = chartMenuParamsFactory.getDefaultToggleParams("series.reverse", "reverse");
this.reverseToggle = this.createManagedBean(new import_ag_grid_community250.AgToggleButton(params));
this.updateReverseSelect();
return this.reverseToggle;
}
updateReverseSelect() {
const isDisplayed = this.chartMenuContext.chartController.getChartType() === "pyramid";
this.updateDisplayed(this.reverseToggle, isDisplayed);
}
updateDirectionSelect() {
const isDisplayed = canSwitchDirection(this.chartMenuContext.chartController.getChartType());
this.updateDisplayed(this.directionSelect, isDisplayed);
}
createGroupTypeSelect() {
const { chartController, chartMenuParamsFactory } = this.chartMenuContext;
this.groupTypeSelect = this.createManagedBean(
new import_ag_grid_community250.AgSelect(
chartMenuParamsFactory.getDefaultSelectParamsWithoutValueParams(
"seriesGroupType",
SERIES_GROUP_TYPES.map((value) => ({
value,
text: this.chartTranslation.translate(`${value}SeriesGroupType`)
})),
chartController.getSeriesGroupType(),
(value) => chartController.setSeriesGroupType(value)
)
)
);
this.updateGroupTypeSelect();
return this.groupTypeSelect;
}
updateGroupTypeSelect() {
const isDisplayed = ["radialColumn", "radialBar", "nightingale"].includes(
this.chartMenuContext.chartController.getChartType()
);
this.updateDisplayed(this.groupTypeSelect, isDisplayed);
}
updateDisplayed(select, isDisplayed) {
select?.setDisplayed(isDisplayed);
if (select) {
this.hasContent = this.hasContent || isDisplayed;
}
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/data/seriesChartTypePanel.ts
var import_ag_grid_community251 = require("ag-grid-community");
var SeriesChartTypePanel = class extends import_ag_grid_community251.Component {
constructor(chartController, columns, isOpen) {
super(
/* html */
`<div id="seriesChartTypeGroup"></div>`
);
this.chartController = chartController;
this.columns = columns;
this.isOpen = isOpen;
this.selectedColIds = [];
this.chartTypeComps = /* @__PURE__ */ new Map();
this.secondaryAxisComps = /* @__PURE__ */ new Map();
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
this.createSeriesChartTypeGroup(this.columns);
}
refresh(columns) {
if (!(0, import_ag_grid_community251._areEqual)(this.getValidColIds(columns), this.selectedColIds)) {
this.recreate(columns);
} else {
this.refreshComps();
}
}
recreate(columns) {
this.isOpen = this.seriesChartTypeGroupComp.isExpanded();
(0, import_ag_grid_community251._clearElement)(this.getGui());
this.destroyBean(this.seriesChartTypeGroupComp);
this.columns = columns;
this.selectedColIds = [];
this.clearComps();
this.postConstruct();
}
getValidColIds(columns) {
const seriesChartTypes = this.chartController.getSeriesChartTypes();
return columns.filter((col) => col.selected && !!seriesChartTypes.filter((s) => s.colId === col.colId)[0]).map(({ colId }) => colId);
}
createSeriesChartTypeGroup(columns) {
this.seriesChartTypeGroupComp = this.createBean(
new AgGroupComponent({
title: this.chartTranslation.translate("seriesChartType"),
enabled: true,
suppressEnabledCheckbox: true,
suppressOpenCloseIcons: false,
cssIdentifier: "charts-data",
expanded: this.isOpen
})
);
const seriesChartTypes = this.chartController.getSeriesChartTypes();
columns.forEach((col) => {
if (!col.selected) {
return;
}
const seriesChartType = seriesChartTypes.filter((s) => s.colId === col.colId)[0];
if (!seriesChartType) {
return;
}
this.selectedColIds.push(col.colId);
const seriesItemGroup = this.seriesChartTypeGroupComp.createManagedBean(
new AgGroupComponent({
title: col.displayName,
enabled: true,
suppressEnabledCheckbox: true,
suppressOpenCloseIcons: true,
cssIdentifier: "charts-format-sub-level"
})
);
const isSecondaryAxisDisabled = (chartType) => ["groupedColumn", "stackedColumn", "stackedArea"].includes(chartType);
const secondaryAxisComp = this.seriesChartTypeGroupComp.createManagedBean(
new import_ag_grid_community251.AgCheckbox({
label: this.chartTranslation.translate("secondaryAxis"),
labelWidth: "flex",
disabled: isSecondaryAxisDisabled(seriesChartType.chartType),
value: !!seriesChartType.secondaryAxis,
onValueChange: (enabled) => this.chartController.updateSeriesChartType(col.colId, void 0, enabled)
})
);
seriesItemGroup.addItem(secondaryAxisComp);
const options = ["line", "area", "stackedArea", "groupedColumn", "stackedColumn"].map(
(value) => ({
value,
text: this.chartTranslation.translate(getFullChartNameTranslationKey(value))
})
);
const chartTypeComp = seriesItemGroup.createManagedBean(
new import_ag_grid_community251.AgSelect({
options,
value: seriesChartType.chartType,
onValueChange: (chartType) => this.chartController.updateSeriesChartType(col.colId, chartType)
})
);
seriesItemGroup.addItem(chartTypeComp);
this.seriesChartTypeGroupComp.addItem(seriesItemGroup);
this.chartTypeComps.set(col.colId, chartTypeComp);
this.secondaryAxisComps.set(col.colId, secondaryAxisComp);
});
this.getGui().appendChild(this.seriesChartTypeGroupComp.getGui());
}
refreshComps() {
const seriesChartTypes = this.chartController.getSeriesChartTypes();
this.selectedColIds.forEach((colId) => {
const seriesChartType = seriesChartTypes.find((chartType) => chartType.colId === colId);
if (!seriesChartType) {
return;
}
const chartTypeComp = this.chartTypeComps.get(colId);
const secondaryAxisComp = this.secondaryAxisComps.get(colId);
chartTypeComp?.setValue(seriesChartType.chartType);
secondaryAxisComp?.setValue(!!seriesChartType.secondaryAxis);
secondaryAxisComp?.setDisabled(this.isSecondaryAxisDisabled(seriesChartType.chartType));
});
}
clearComps() {
this.chartTypeComps.clear();
this.secondaryAxisComps.clear();
}
isSecondaryAxisDisabled(chartType) {
return ["groupedColumn", "stackedColumn", "stackedArea"].includes(chartType);
}
destroy() {
this.clearComps();
this.seriesChartTypeGroupComp = this.destroyBean(this.seriesChartTypeGroupComp);
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/data/seriesDataPanel.ts
var import_ag_grid_community252 = require("ag-grid-community");
var SeriesDataPanel = class extends DragDataPanel {
constructor(chartController, chartOptionsService, title, allowMultipleSelect, maxSelection, valueCols, isOpen) {
super(
chartController,
allowMultipleSelect,
maxSelection,
/* html */
`<div id="seriesGroup"></div>`
);
this.chartOptionsService = chartOptionsService;
this.title = title;
this.valueCols = valueCols;
this.isOpen = isOpen;
}
postConstruct() {
this.groupComp = this.createBean(
new AgGroupComponent({
title: this.title,
enabled: true,
suppressEnabledCheckbox: true,
suppressOpenCloseIcons: false,
cssIdentifier: "charts-data",
expanded: this.isOpen
})
);
if (this.chartController.isActiveXYChart()) {
const pairedModeToggle = this.groupComp.createManagedBean(
new import_ag_grid_community252.AgToggleButton({
label: this.chartTranslation.translate("paired"),
labelAlignment: "left",
labelWidth: "flex",
inputWidth: "flex",
value: this.chartOptionsService.getPairedMode(),
onValueChange: (newValue) => {
this.chartOptionsService.setPairedMode(!!newValue);
this.chartController.updateForGridChange({ maintainColState: true });
}
})
);
this.groupComp.addItem(pairedModeToggle);
}
this.createGroup(this.valueCols, this.generateGetSeriesLabel(this.valueCols), "seriesAdd", "seriesSelect");
this.getGui().appendChild(this.groupComp.getGui());
}
refresh(valueCols) {
this.valuePillSelect?.setValueFormatter(this.generateGetSeriesLabel(valueCols));
this.valuePillSelect?.setValues(
valueCols,
valueCols.filter((col) => col.selected)
);
this.refreshValueSelect(valueCols);
}
generateGetSeriesLabel(valueCols) {
if (!this.chartController.isActiveXYChart()) {
return (col) => col.displayName ?? "";
}
const selectedCols = valueCols.filter((col) => col.selected);
const isBubble = this.chartController.getChartType() === "bubble";
const isInPairedMode = this.chartOptionsService.getPairedMode();
const indexToAxisLabel = /* @__PURE__ */ new Map();
indexToAxisLabel.set(0, "X");
indexToAxisLabel.set(1, "Y");
indexToAxisLabel.set(2, "size");
return (col) => {
const escapedLabel = col.displayName ?? "";
if (!col.selected) {
return escapedLabel;
}
const index = selectedCols.indexOf(col);
if (index === -1) {
return escapedLabel;
}
let axisLabel;
if (isInPairedMode) {
axisLabel = indexToAxisLabel.get(index % (isBubble ? 3 : 2));
} else {
if (index === 0) {
axisLabel = "X";
} else {
axisLabel = isBubble && index % 2 === 0 ? "size" : "Y";
}
}
return `${escapedLabel} (${axisLabel})`;
};
}
destroy() {
this.groupComp = this.destroyBean(this.groupComp);
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/data/chartDataPanel.ts
var DefaultDataPanelDef = {
groups: [
{ type: "categories", isOpen: true },
{ type: "series", isOpen: true },
{ type: "seriesChartType", isOpen: true },
{ type: "chartSpecific", isOpen: true }
]
};
var ChartDataPanel = class extends import_ag_grid_community253.Component {
constructor(chartMenuContext) {
super(
/* html */
`<div class="ag-chart-data-wrapper ag-scrollable-container"></div>`
);
this.chartMenuContext = chartMenuContext;
this.isSwitchCategorySeriesToggled = false;
this.restoreSwitchCategorySeriesToggleFocus = false;
this.panels = [];
this.chartController = chartMenuContext.chartController;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
this.chartSvc = beans.chartSvc;
}
postConstruct() {
this.createSwitchCategorySeriesToggle();
this.isSwitchCategorySeriesToggled = this.chartController.isCategorySeriesSwitched();
this.updatePanels();
const listener = this.updatePanels.bind(this);
this.addManagedListeners(this.chartController, {
chartModelUpdate: listener,
chartApiUpdate: listener
});
}
destroy() {
this.clearPanelComponents();
super.destroy();
}
updatePanels() {
const currentChartType = this.chartType;
const isSwitchCategorySeriesToggledCurrent = this.isSwitchCategorySeriesToggled;
const { dimensionCols, valueCols } = this.chartController.getColStateForMenu();
this.chartType = this.chartController.getChartType();
this.isSwitchCategorySeriesToggled = this.chartController.isCategorySeriesSwitched();
const hasChangedSwitchCategorySeries = this.isSwitchCategorySeriesToggled !== isSwitchCategorySeriesToggledCurrent;
if (this.canRefresh(currentChartType, this.chartType) && !hasChangedSwitchCategorySeries) {
this.categoriesDataPanel?.refresh(dimensionCols);
this.seriesDataPanel?.refresh(valueCols);
this.seriesChartTypePanel?.refresh(valueCols);
this.chartSpecificPanel?.refresh();
} else {
this.recreatePanels(dimensionCols, valueCols);
}
const isSwitchCategorySeriesDisplayed = supportsInvertedCategorySeries(this.chartType) && this.chartSvc.isEnterprise() && !this.chartController.isGrouping();
(0, import_ag_grid_community253._setDisplayed)(this.switchCategorySeriesToggle.getGui(), isSwitchCategorySeriesDisplayed);
if (hasChangedSwitchCategorySeries) {
this.switchCategorySeriesToggle?.setValue(this.chartController.isCategorySeriesSwitched());
}
if (this.restoreSwitchCategorySeriesToggleFocus) {
this.restoreSwitchCategorySeriesToggleFocus = false;
if (isSwitchCategorySeriesDisplayed) {
this.switchCategorySeriesToggle.getFocusableElement().focus();
}
}
}
canRefresh(oldChartType, newChartType) {
if (oldChartType === void 0)
return false;
if (oldChartType === newChartType) {
return true;
}
const isCombo = (chartType) => ["columnLineCombo", "areaColumnCombo", "customCombo"].includes(chartType);
if (isCombo(oldChartType) && isCombo(newChartType)) {
return true;
}
return false;
}
recreatePanels(dimensionCols, valueCols) {
this.clearPanelComponents();
const { chartType } = this;
if (!chartType)
return;
const isCategorySeriesSwitched = this.chartController.isCategorySeriesSwitched();
this.getDataPanelDef().groups?.forEach(({ type, isOpen }) => {
if (type === (isCategorySeriesSwitched ? "series" : "categories")) {
this.categoriesDataPanel = this.createBean(
new CategoriesDataPanel(
this.chartController,
this.getCategoryGroupTitle(isCategorySeriesSwitched),
this.getCategoryGroupMultipleSelect(chartType, isCategorySeriesSwitched),
dimensionCols,
isOpen
)
);
this.panels.push(this.categoriesDataPanel);
} else if (type === (isCategorySeriesSwitched ? "categories" : "series")) {
this.seriesDataPanel = this.createBean(
new SeriesDataPanel(
this.chartController,
this.chartMenuContext.chartOptionsService,
this.getSeriesGroupTitle(isCategorySeriesSwitched),
this.getSeriesGroupMultipleSelect(chartType, isCategorySeriesSwitched),
this.getSeriesGroupMaxSelection(chartType, isCategorySeriesSwitched),
valueCols,
isOpen
)
);
this.panels.push(this.seriesDataPanel);
} else if (type === "seriesChartType") {
if (this.chartController.isComboChart()) {
this.seriesChartTypePanel = this.createBean(
new SeriesChartTypePanel(this.chartController, valueCols, isOpen)
);
this.panels.push(this.seriesChartTypePanel);
}
} else if (type === "chartSpecific") {
this.chartSpecificPanel = this.createBean(new ChartSpecificDataPanel(this.chartMenuContext, isOpen));
this.panels.push(this.chartSpecificPanel);
} else {
(0, import_ag_grid_community253._warn)(144, { type });
}
});
(isCategorySeriesSwitched ? this.categoriesDataPanel : this.seriesDataPanel)?.addItem(
this.switchCategorySeriesToggle.getGui()
);
this.addPanelComponents();
}
addPanelComponents() {
if (!this.panels.length) {
return;
}
const eDocument = (0, import_ag_grid_community253._getDocument)(this.beans);
const fragment = eDocument.createDocumentFragment();
for (const panel of this.panels) {
panel.addCss("ag-chart-data-section");
fragment.appendChild(panel.getGui());
}
this.getGui().appendChild(fragment);
}
clearPanelComponents() {
const eGui = this.getGui();
this.panels.forEach((panel) => {
eGui.removeChild(panel.getGui());
this.destroyBean(panel);
});
this.panels = [];
}
getDataPanelDef() {
return this.gos.get("chartToolPanelsDef")?.dataPanel ?? DefaultDataPanelDef;
}
getCategoryGroupTitle(isCategorySeriesSwitched) {
if (isCategorySeriesSwitched)
return this.chartTranslation.translate("seriesLabels");
return this.chartTranslation.translate(this.chartController.isActiveXYChart() ? "labels" : "categories");
}
getCategoryGroupMultipleSelect(chartType, isCategorySeriesSwitched) {
if (isCategorySeriesSwitched)
return false;
return getMaxNumCategories(chartType) !== 1;
}
getSeriesGroupTitle(isCategorySeriesSwitched) {
if (isCategorySeriesSwitched)
return this.chartTranslation.translate("categoryValues");
return this.chartTranslation.translate(this.chartController.isActiveXYChart() ? "xyValues" : "series");
}
getSeriesGroupMultipleSelect(chartType, isCategorySeriesSwitched) {
return this.getSeriesGroupMaxSelection(chartType, isCategorySeriesSwitched) !== 1;
}
getSeriesGroupMaxSelection(chartType, isCategorySeriesSwitched) {
if (isCategorySeriesSwitched)
return void 0;
return getMaxNumSeries(chartType);
}
createSwitchCategorySeriesToggle() {
this.switchCategorySeriesToggle = this.createManagedBean(
new import_ag_grid_community253.AgToggleButton({
label: this.chartTranslation.translate("switchCategorySeries"),
labelAlignment: "left",
labelWidth: "flex",
inputWidth: "flex",
value: this.chartController.isCategorySeriesSwitched(),
onValueChange: (value) => {
this.restoreSwitchCategorySeriesToggleFocus = true;
this.chartController.switchCategorySeries(value);
}
})
);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/formatPanel.ts
var import_ag_grid_community278 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/axis/cartesianAxisPanel.ts
var import_ag_grid_community258 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/widgets/agAngleSelect.ts
var import_ag_grid_community254 = require("ag-grid-community");
var AgAngleSelect = class extends import_ag_grid_community254.AgAbstractLabel {
constructor(config) {
super(
config,
/* html */
`<div class="ag-angle-select">
<div data-ref="eLabel"></div>
<div class="ag-wrapper ag-angle-select-wrapper">
<div class="ag-angle-select-field">
<div data-ref="eParentCircle" class="ag-angle-select-parent-circle">
<div data-ref="eChildCircle" class="ag-angle-select-child-circle"></div>
</div>
</div>
<ag-input-number-field data-ref="eAngleValue"></ag-input-number-field>
</div>
</div>`,
[import_ag_grid_community254.AgInputNumberFieldSelector]
);
this.eLabel = import_ag_grid_community254.RefPlaceholder;
this.eParentCircle = import_ag_grid_community254.RefPlaceholder;
this.eChildCircle = import_ag_grid_community254.RefPlaceholder;
this.eAngleValue = import_ag_grid_community254.RefPlaceholder;
this.radius = 0;
this.offsetX = 0;
this.offsetY = 0;
}
wireBeans(beans) {
this.dragSvc = beans.dragSvc;
}
postConstruct() {
super.postConstruct();
const { value, onValueChange } = this.config;
if (value != null) {
this.setValue(value, void 0, true);
}
if (onValueChange != null) {
this.onValueChange(onValueChange);
}
this.dragListener = {
eElement: this.eParentCircle,
dragStartPixels: 0,
onDragStart: () => {
this.parentCircleRect = this.eParentCircle.getBoundingClientRect();
},
onDragging: (e) => this.calculateAngleDrag(e),
onDragStop: () => {
}
};
this.dragSvc?.addDragSource(this.dragListener);
this.eAngleValue.setLabel("").setLabelWidth(5).setInputWidth(45).setMin(0).setMax(360).setValue(`${this.degrees}`).onValueChange((value2) => {
if (value2 == null || value2 === "") {
value2 = "0";
}
value2 = this.eAngleValue.normalizeValue(value2);
let floatValue = parseFloat(value2);
if (floatValue > 180) {
floatValue = floatValue - 360;
}
this.setValue(floatValue);
});
this.updateNumberInput();
if ((0, import_ag_grid_community254._exists)(this.getValue())) {
this.eAngleValue.setValue(this.normalizeNegativeValue(this.getValue()).toString());
}
this.addManagedListeners(this, {
fieldValueChanged: () => {
if (this.eAngleValue.getInputElement().contains((0, import_ag_grid_community254._getActiveDomElement)(this.beans))) {
return;
}
this.updateNumberInput();
}
});
}
updateNumberInput() {
const normalizedValue = this.normalizeNegativeValue(this.getValue());
this.eAngleValue.setValue(normalizedValue.toString());
}
positionChildCircle(radians) {
const rect = this.parentCircleRect || { width: 24, height: 24 };
const eChildCircle = this.eChildCircle;
const centerX = rect.width / 2;
const centerY = rect.height / 2;
eChildCircle.style.left = `${centerX + Math.cos(radians) * 8}px`;
eChildCircle.style.top = `${centerY + Math.sin(radians) * 8}px`;
}
calculatePolar() {
const x = this.offsetX;
const y = this.offsetY;
const radians = Math.atan2(y, x);
this.degrees = this.toDegrees(radians);
this.radius = Math.sqrt(x * x + y * y);
this.positionChildCircle(radians);
}
calculateCartesian() {
const radians = this.toRadians(this.getValue());
const radius = this.getRadius();
this.setOffsetX(Math.cos(radians) * radius).setOffsetY(Math.sin(radians) * radius);
}
setOffsetX(offset) {
if (this.offsetX !== offset) {
this.offsetX = offset;
this.calculatePolar();
}
return this;
}
setOffsetY(offset) {
if (this.offsetY !== offset) {
this.offsetY = offset;
this.calculatePolar();
}
return this;
}
calculateAngleDrag(e) {
const rect = this.parentCircleRect;
const centerX = rect.width / 2;
const centerY = rect.height / 2;
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const dx = x - centerX;
const dy = y - centerY;
const radians = Math.atan2(dy, dx);
this.setValue(radians, true);
}
toDegrees(radians) {
return radians / Math.PI * 180;
}
toRadians(degrees) {
return degrees / 180 * Math.PI;
}
normalizeNegativeValue(degrees) {
return degrees < 0 ? 360 + degrees : degrees;
}
normalizeAngle180(radians) {
radians %= Math.PI * 2;
if (radians < -Math.PI) {
radians += Math.PI * 2;
} else if (radians >= Math.PI) {
radians -= Math.PI * 2;
}
return radians;
}
getRadius() {
return this.radius;
}
setRadius(r) {
if (this.radius === r) {
return this;
}
this.radius = r;
this.calculateCartesian();
return this;
}
onValueChange(callbackFn) {
this.addManagedListeners(this, {
fieldValueChanged: () => {
callbackFn(this.degrees);
}
});
return this;
}
getValue(radians) {
return radians ? this.toRadians(this.degrees) : this.degrees;
}
setValue(degrees, radians, silent) {
let radiansValue;
if (!radians) {
radiansValue = this.normalizeAngle180(this.toRadians(degrees));
} else {
radiansValue = degrees;
}
degrees = this.toDegrees(radiansValue);
if (this.degrees !== degrees) {
this.degrees = Math.floor(degrees);
this.calculateCartesian();
this.positionChildCircle(radiansValue);
if (!silent) {
this.dispatchLocalEvent({ type: "fieldValueChanged" });
}
}
return this;
}
setWidth(width) {
(0, import_ag_grid_community254._setFixedWidth)(this.getGui(), width);
return this;
}
setDisabled(disabled) {
super.setDisabled(disabled);
this.eAngleValue.setDisabled(disabled);
return this;
}
destroy() {
this.dragSvc?.removeDragSource(this.dragListener);
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/fontPanel.ts
var import_ag_grid_community255 = require("ag-grid-community");
function _capitalise(str) {
return str[0].toUpperCase() + str.substring(1).toLowerCase();
}
var FontPanel = class extends import_ag_grid_community255.Component {
constructor(params) {
super();
this.params = params;
this.fontGroup = import_ag_grid_community255.RefPlaceholder;
this.activeComps = [];
this.chartOptions = params.chartMenuParamsFactory.getChartOptions();
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const {
cssIdentifier = "charts-format-sub-level",
name: title,
enabled,
onEnableChange,
suppressEnabledCheckbox,
chartMenuParamsFactory,
keyMapper
} = this.params;
const fontGroupParams = {
cssIdentifier,
direction: "vertical",
suppressOpenCloseIcons: true,
title,
enabled,
suppressEnabledCheckbox: true,
onEnableChange: (enabled2) => {
if (onEnableChange) {
onEnableChange(enabled2);
}
},
useToggle: !suppressEnabledCheckbox
};
this.setTemplate(
/* html */
`<div class="ag-font-panel">
<ag-group-component data-ref="fontGroup">
<ag-select data-ref="familySelect"></ag-select>
<ag-select data-ref="weightStyleSelect"></ag-select>
<div class="ag-charts-font-size-color">
<ag-select data-ref="sizeSelect"></ag-select>
<ag-color-picker data-ref="colorPicker"></ag-color-picker>
</div>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, import_ag_grid_community255.AgSelectSelector, AgColorPickerSelector],
{
fontGroup: fontGroupParams,
familySelect: this.getFamilySelectParams(),
weightStyleSelect: this.getWeightStyleSelectParams(),
sizeSelect: this.getSizeSelectParams(),
colorPicker: chartMenuParamsFactory.getDefaultColorPickerParams(keyMapper("color"))
}
);
this.toggleCss("ag-font-panel-no-header", !title);
}
addItem(comp, prepend) {
if (prepend) {
this.fontGroup.prependItem(comp);
} else {
this.fontGroup.addItem(comp);
}
this.activeComps.push(comp);
}
setEnabled(enabled) {
this.fontGroup.setEnabled(enabled);
}
getFamilySelectParams() {
const families = [
"Arial, sans-serif",
"Aria Black, sans-serif",
"Book Antiqua, serif",
"Charcoal, sans-serif",
"Comic Sans MS, cursive",
"Courier, monospace",
"Courier New, monospace",
"Gadget, sans-serif",
"Geneva, sans-serif",
"Helvetica, sans-serif",
"Impact, sans-serif",
"Lucida Console, monospace",
"Lucida Grande, sans-serif",
"Lucida Sans Unicode, sans-serif",
"Monaco, monospace",
"Palatino Linotype, serif",
"Palatino, serif",
"Times New Roman, serif",
"Times, serif",
"Verdana, sans-serif"
];
const family = this.getInitialFontValue("fontFamily");
let initialValue = families[0];
if (family) {
const lowerCaseValues = families.map((f) => f.toLowerCase());
const valueIndex = lowerCaseValues.indexOf(family.toLowerCase());
if (valueIndex >= 0) {
initialValue = families[valueIndex];
} else {
const capitalisedFontValue = _capitalise(family);
families.push(capitalisedFontValue);
initialValue = capitalisedFontValue;
}
}
const options = families.sort().map((value) => ({ value, text: value }));
return this.params.chartMenuParamsFactory.getDefaultSelectParamsWithoutValueParams(
"font",
options,
`${initialValue}`,
(newValue) => this.setFont({ fontFamily: newValue })
);
}
getSizeSelectParams() {
const sizes = [8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36];
const size = this.getInitialFontValue("fontSize");
if (!sizes.includes(size)) {
sizes.push(size);
}
const options = sizes.sort((a, b) => a - b).map((value) => ({ value: `${value}`, text: `${value}` }));
return this.params.chartMenuParamsFactory.getDefaultSelectParamsWithoutValueParams(
"size",
options,
`${size}`,
(newValue) => this.setFont({ fontSize: parseInt(newValue, 10) })
);
}
getWeightStyleSelectParams() {
const weight = this.getInitialFontValue("fontWeight") ?? "normal";
const style = this.getInitialFontValue("fontStyle") ?? "normal";
const weightStyles = [
{ name: "normal", weight: "normal", style: "normal" },
{ name: "bold", weight: "bold", style: "normal" },
{ name: "italic", weight: "normal", style: "italic" },
{ name: "boldItalic", weight: "bold", style: "italic" }
];
let selectedOption = weightStyles.find((x) => x.weight === weight && x.style === style);
if (!selectedOption) {
selectedOption = { name: "predefined", weight, style };
weightStyles.unshift(selectedOption);
}
const options = weightStyles.map((ws) => ({
value: ws.name,
text: this.chartTranslation.translate(ws.name)
}));
return this.params.chartMenuParamsFactory.getDefaultSelectParamsWithoutValueParams(
"weight",
options,
selectedOption.name,
(newValue) => {
const selectedWeightStyle = weightStyles.find((x) => x.name === newValue);
this.setFont({ fontWeight: selectedWeightStyle.weight, fontStyle: selectedWeightStyle.style });
}
);
}
destroyActiveComps() {
this.activeComps.forEach((comp) => {
(0, import_ag_grid_community255._removeFromParent)(comp.getGui());
this.destroyBean(comp);
});
}
destroy() {
this.destroyActiveComps();
super.destroy();
}
setFont(font) {
const { keyMapper } = this.params;
for (const fontKey of Object.keys(font)) {
const value = font[fontKey];
if (value) {
this.chartOptions.setValue(keyMapper(fontKey), value);
}
}
}
getInitialFontValue(fontKey) {
const { keyMapper } = this.params;
return this.chartOptions.getValue(keyMapper(fontKey));
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/axis/axisTicksPanel.ts
var import_ag_grid_community256 = require("ag-grid-community");
var AxisTicksPanel = class extends import_ag_grid_community256.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
this.axisTicksSizeSlider = import_ag_grid_community256.RefPlaceholder;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const { chartMenuUtils } = this;
const axisTicksGroupParams = chartMenuUtils.addEnableParams("tick.enabled", {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: this.chartTranslation.translate("ticks"),
suppressEnabledCheckbox: true,
useToggle: true
});
const axisTicksColorPickerParams = chartMenuUtils.getDefaultColorPickerParams("tick.stroke");
const axisTicksWidthSliderParams = chartMenuUtils.getDefaultSliderParams("tick.width", "width", 10);
const axisTicksSizeSliderParams = chartMenuUtils.getDefaultSliderParams("tick.size", "length", 30);
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="axisTicksGroup">
<ag-color-picker data-ref="axisTicksColorPicker"></ag-color-picker>
<ag-slider data-ref="axisTicksWidthSlider"></ag-slider>
<ag-slider data-ref="axisTicksSizeSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, AgColorPickerSelector, AgSliderSelector],
{
axisTicksGroup: axisTicksGroupParams,
axisTicksColorPicker: axisTicksColorPickerParams,
axisTicksWidthSlider: axisTicksWidthSliderParams,
axisTicksSizeSlider: axisTicksSizeSliderParams
}
);
}
setTickSizeSliderDisplayed(displayed) {
this.axisTicksSizeSlider.setDisplayed(displayed);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/axis/gridLinePanel.ts
var import_ag_grid_community257 = require("ag-grid-community");
var GridLinePanel = class extends import_ag_grid_community257.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
this.chartOptions = chartMenuUtils.getChartOptions();
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const gridLineGroupParams = this.chartMenuUtils.addEnableParams("gridLine.enabled", {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: this.chartTranslation.translate("gridLines"),
suppressEnabledCheckbox: true,
useToggle: true
});
const gridLineColorPickerParams = this.getGridLineColorPickerParams("color");
const gridLineWidthSliderParams = this.getGridLineWidthSliderParams("thickness");
const gridLineLineDashSliderParams = this.getGridLineDashSliderParams("lineDash");
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="gridLineGroup">
<ag-color-picker data-ref="gridLineColorPicker"></ag-color-picker>
<ag-slider data-ref="gridLineWidthSlider"></ag-slider>
<ag-slider data-ref="gridLineLineDashSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, AgColorPickerSelector, AgSliderSelector],
{
gridLineGroup: gridLineGroupParams,
gridLineColorPicker: gridLineColorPickerParams,
gridLineWidthSlider: gridLineWidthSliderParams,
gridLineLineDashSlider: gridLineLineDashSliderParams
}
);
}
getGridLineColorPickerParams(labelKey) {
return this.chartMenuUtils.getDefaultColorPickerParams("gridLine.style", labelKey, {
formatInputValue: (value) => {
return value?.[0]?.stroke;
},
parseInputValue: (value) => {
const styles = this.chartOptions.getValue("gridLine.style") ?? [];
if (styles.length === 0)
return [{ stroke: value, lineDash: [] }];
return [{ ...styles[0], stroke: value }];
}
});
}
getGridLineWidthSliderParams(labelKey) {
return this.chartMenuUtils.getDefaultSliderParams("gridLine.width", labelKey, 10);
}
getGridLineDashSliderParams(labelKey) {
const initialStyles = this.chartOptions.getValue("gridLine.style");
const initialValue = initialStyles?.[0]?.lineDash?.[0];
const params = this.chartMenuUtils.getDefaultSliderParamsWithoutValueParams(initialValue ?? 0, labelKey, 30);
params.onValueChange = (value) => {
const stroke = this.chartOptions.getValue("gridLine.style.0.stroke");
this.chartOptions.setValue("gridLine.style", [
{ lineDash: [value], stroke }
]);
};
return params;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/axis/cartesianAxisPanel.ts
var DEFAULT_TIME_AXIS_FORMAT = "%d %B %Y";
var CartesianAxisPanel = class extends import_ag_grid_community258.Component {
constructor(axisType, options) {
super();
this.axisType = axisType;
this.options = options;
this.axisGroup = import_ag_grid_community258.RefPlaceholder;
this.axisTypeSelect = import_ag_grid_community258.RefPlaceholder;
this.axisPositionSelect = import_ag_grid_community258.RefPlaceholder;
this.axisTimeFormatSelect = import_ag_grid_community258.RefPlaceholder;
this.activePanels = [];
this.updateFuncs = [];
const { chartOptionsService, seriesType, chartController } = options;
this.chartOptionsService = chartOptionsService;
this.chartController = chartController;
this.chartOptionsSeriesProxy = chartOptionsService.getSeriesOptionsProxy(() => seriesType);
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const { isExpandedOnInit: expanded, chartOptionsService, registerGroupComponent } = this.options;
const labelKey = this.axisType;
const axisGroupParams = {
cssIdentifier: "charts-format-top-level",
direction: "vertical",
title: this.translate(labelKey),
expanded,
suppressEnabledCheckbox: true
};
const chartAxisOptionsProxy = chartOptionsService.getCartesianAxisOptionsProxy(this.axisType);
const chartAxisOptions = this.createManagedBean(new ChartMenuParamsFactory(chartAxisOptionsProxy));
const chartAxisThemeOverrides = this.createManagedBean(
new ChartMenuParamsFactory(chartOptionsService.getCartesianAxisThemeOverridesProxy(this.axisType))
);
const axisTypeSelectParams = this.getAxisTypeSelectParams(
chartAxisOptions,
chartOptionsService.getCartesianAxisAppliedThemeOverridesProxy(this.axisType)
);
const axisPositionSelectParams = this.getAxisPositionSelectParams(chartAxisOptions);
const axisTimeFormatSelectParams = this.getAxisTimeFormatSelectParams(chartAxisOptions);
const axisColorInputParams = this.getAxisColorInputParams(chartAxisThemeOverrides);
const axisLineWidthSliderParams = this.getAxisLineWidthSliderParams(chartAxisThemeOverrides);
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="axisGroup">
<ag-select data-ref="axisTypeSelect"></ag-select>
<ag-select data-ref="axisTimeFormatSelect"></ag-select>
<ag-select data-ref="axisPositionSelect"></ag-select>
<ag-color-picker data-ref="axisColorInput"></ag-color-picker>
<ag-slider data-ref="axisLineWidthSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, import_ag_grid_community258.AgSelectSelector, AgColorPickerSelector, AgSliderSelector],
{
axisGroup: axisGroupParams,
axisTypeSelect: axisTypeSelectParams ?? void 0,
axisPositionSelect: axisPositionSelectParams ?? void 0,
axisTimeFormatSelect: axisTimeFormatSelectParams ?? void 0,
axisColorInput: axisColorInputParams,
axisLineWidthSlider: axisLineWidthSliderParams
}
);
registerGroupComponent(this.axisGroup);
this.axisTypeSelect.setDisplayed(!!axisTypeSelectParams.options?.length);
if (!axisPositionSelectParams)
this.removeTemplateComponent(this.axisPositionSelect);
const updateTimeFormatVisibility = () => {
const isTimeAxis = chartAxisOptionsProxy.getValue("type") === "time";
(0, import_ag_grid_community258._setDisplayed)(this.axisTimeFormatSelect.getGui(), isTimeAxis);
};
if (!axisTimeFormatSelectParams) {
this.removeTemplateComponent(this.axisTimeFormatSelect);
} else {
updateTimeFormatVisibility();
this.addManagedEventListeners({
chartOptionsChanged: () => {
updateTimeFormatVisibility();
}
});
}
this.initGridLines(chartAxisThemeOverrides);
this.initAxisTicks(chartAxisThemeOverrides);
this.initAxisLabels(chartAxisThemeOverrides);
const updateFns = () => this.updateFuncs.forEach((func) => func());
this.addManagedListeners(this.chartController, {
chartUpdated: updateFns,
chartModelUpdate: () => setTimeout(() => {
if (!this.isAlive()) {
return;
}
this.refreshAxisTypeSelect(chartAxisOptions);
updateTimeFormatVisibility();
})
});
}
getAxisTypeSelectParams(chartAxisOptions, chartAxisAppliedThemeOverrides) {
const chartOptions = chartAxisOptions.getChartOptions();
const axisTypeSelectOptions = this.getAxisTypeSelectOptions();
const params = chartAxisOptions.getDefaultSelectParams("type", "axisType", axisTypeSelectOptions);
params.onValueChange = (value) => {
const previousAxisType = chartOptions.getValue("type");
if (value === previousAxisType)
return;
const previousAxisThemeOverrides = chartAxisAppliedThemeOverrides.getValue("*");
const previousAxisIsTimeAxis = previousAxisType === "time";
const updatedAxisIsTimeAxis = value === "time";
const updatedLabelFormat = previousAxisIsTimeAxis !== updatedAxisIsTimeAxis ? updatedAxisIsTimeAxis ? DEFAULT_TIME_AXIS_FORMAT : void 0 : null;
this.chartOptionsService.setCartesianCategoryAxisType(this.axisType, value);
if (updatedLabelFormat !== null) {
const existingLabel = chartOptions.getValue("label") ?? {};
chartOptions.setValue("label", {
...existingLabel,
format: updatedLabelFormat
});
}
chartAxisAppliedThemeOverrides.setValue("*", previousAxisThemeOverrides);
};
return params;
}
refreshAxisTypeSelect(chartAxisOptions) {
const options = this.getAxisTypeSelectOptions();
const hasOptions = !!options.length;
this.axisTypeSelect.setDisplayed(hasOptions);
if (!hasOptions) {
return;
}
this.axisTypeSelect.clearOptions().addOptions(options).setValue(chartAxisOptions.getChartOptions().getValue("type"));
}
getAxisTypeSelectOptions() {
const controller = this.chartController;
const chartType = controller.getChartType();
const supportsNumericalAxis = () => {
const testDatum = controller.getChartData()[0];
if (!testDatum) {
return false;
}
return controller.getSelectedDimensions().every((col) => !isNaN(parseFloat(testDatum[col.colId])));
};
if (["heatmap", "histogram", "boxPlot", "rangeBar", "scatter", "bubble"].includes(chartType) || controller.isGrouping() || !this.isCategoryAxis() || controller.isCategorySeriesSwitched() || !supportsNumericalAxis()) {
return [];
}
return ["category", "number", "time"].map((value) => ({
value,
text: this.translate(value)
}));
}
isCategoryAxis() {
const isHorizontal = this.chartOptionsSeriesProxy.getValue("direction") === "horizontal";
return isHorizontal && this.axisType === "yAxis" || !isHorizontal && this.axisType === "xAxis";
}
getAxisPositionSelectParams(chartAxisOptions) {
const axisPositionSelectOptions = ((chartType, axisType) => {
switch (chartType) {
case "heatmap":
return null;
default:
switch (axisType) {
case "xAxis":
return [
{ value: "top", text: this.translate("top") },
{ value: "bottom", text: this.translate("bottom") }
];
case "yAxis":
return [
{ value: "left", text: this.translate("left") },
{ value: "right", text: this.translate("right") }
];
}
}
})(this.chartController.getChartType(), this.axisType);
if (!axisPositionSelectOptions)
return null;
return chartAxisOptions.getDefaultSelectParams("position", "position", axisPositionSelectOptions);
}
getAxisTimeFormatSelectParams(chartAxisOptions) {
if (!this.isCategoryAxis()) {
return null;
}
const axisTimeFormatSelectOptions = [
{ value: "%d/%m/%Y", text: this.translate("timeFormatSlashesDDMMYYYY") },
{ value: "%m/%d/%Y", text: this.translate("timeFormatSlashesMMDDYYYY") },
{ value: "%d/%m/%y", text: this.translate("timeFormatSlashesDDMMYY") },
{ value: "%m/%d/%y", text: this.translate("timeFormatSlashesMMDDYY") },
{ value: "%d.%e.%y", text: this.translate("timeFormatDotsDDMYY") },
{ value: "%e.%d.%y", text: this.translate("timeFormatDotsMDDYY") },
{ value: "%Y-%m-%d", text: this.translate("timeFormatDashesYYYYMMDD") },
{ value: "%d %B %Y", text: this.translate("timeFormatSpacesDDMMMMYYYY") },
{ value: "%H:%M:%S", text: this.translate("timeFormatHHMMSS") },
{ value: "%I:%M:%S %p", text: this.translate("timeFormatHHMMSSAmPm") }
];
return chartAxisOptions.getDefaultSelectParams("label.format", "timeFormat", axisTimeFormatSelectOptions);
}
getAxisColorInputParams(chartAxisThemeOverrides) {
return chartAxisThemeOverrides.getDefaultColorPickerParams("line.stroke");
}
getAxisLineWidthSliderParams(chartAxisThemeOverrides) {
const chartOptions = chartAxisThemeOverrides.getChartOptions();
const getAxisLineWidth = () => {
const isAxisLineEnabled = chartOptions.getValue("line.enabled");
if (!isAxisLineEnabled)
return null;
return chartOptions.getValue("line.width");
};
const setAxisLineWidth = (value) => {
chartOptions.setValues([
{ expression: "line.enabled", value: value != null },
{ expression: "line.width", value: value ?? 0 }
]);
};
const axisLineWidthSliderParams = chartAxisThemeOverrides.getDefaultSliderParamsWithoutValueParams(
getAxisLineWidth() ?? 0,
"thickness",
10
);
axisLineWidthSliderParams.onValueChange = (newValue) => {
setAxisLineWidth(newValue === 0 ? null : newValue);
};
return axisLineWidthSliderParams;
}
initGridLines(chartAxisThemeOverrides) {
const chartType = this.chartController.getChartType();
if (chartType === "heatmap") {
return;
}
const gridLineComp = this.createBean(new GridLinePanel(chartAxisThemeOverrides));
this.axisGroup.addItem(gridLineComp);
this.activePanels.push(gridLineComp);
}
initAxisTicks(chartAxisThemeOverrides) {
if (!this.hasConfigurableAxisTicks())
return;
const axisTicksComp = this.createBean(new AxisTicksPanel(chartAxisThemeOverrides));
this.axisGroup.addItem(axisTicksComp);
this.activePanels.push(axisTicksComp);
const updateTickFn = () => axisTicksComp.setTickSizeSliderDisplayed(this.isGroupedCategoryAxis());
this.updateFuncs.push(updateTickFn);
updateTickFn();
}
hasConfigurableAxisTicks() {
const chartType = this.chartController.getChartType();
switch (chartType) {
case "radarLine":
case "radarArea":
case "rangeBar":
case "boxPlot":
case "waterfall":
return false;
default:
return true;
}
}
initAxisLabels(chartAxisThemeOverrides) {
const params = {
name: this.translate("labels"),
enabled: true,
suppressEnabledCheckbox: true,
chartMenuParamsFactory: chartAxisThemeOverrides,
keyMapper: (key) => `label.${key}`
};
const labelPanelComp = this.createBean(new FontPanel(params));
this.axisGroup.addItem(labelPanelComp);
this.activePanels.push(labelPanelComp);
this.addAdditionalLabelComps(labelPanelComp, chartAxisThemeOverrides);
}
addAdditionalLabelComps(labelPanelComp, chartAxisThemeOverrides) {
this.addLabelPadding(labelPanelComp, chartAxisThemeOverrides);
const rotationComp = this.createRotationWidget("labelRotation", chartAxisThemeOverrides);
const autoRotateCb = this.initLabelRotation(rotationComp, chartAxisThemeOverrides);
labelPanelComp.addItem(autoRotateCb);
labelPanelComp.addItem(rotationComp);
}
initLabelRotation(rotationComp, chartAxisThemeOverrides) {
const chartOptions = chartAxisThemeOverrides.getChartOptions();
const getLabelRotationValue = () => {
return chartOptions.getValue("label.rotation");
};
const getLabelAutoRotateValue = () => {
return chartOptions.getValue("label.autoRotate");
};
const updateAutoRotate = (autoRotate2) => {
if (autoRotate2)
this.prevRotation = getLabelRotationValue();
chartOptions.setValues([
{ expression: "label.autoRotate", value: autoRotate2 },
// Clear the rotation option when activating auto-rotate, reinstate the previous value when deactivating
{ expression: "label.rotation", value: autoRotate2 ? void 0 : this.prevRotation }
]);
rotationComp.setDisplayed(!autoRotate2);
};
const rotation = getLabelRotationValue();
const autoRotate = typeof rotation === "number" ? false : getLabelAutoRotateValue();
const autoRotateCheckbox = this.createBean(
new import_ag_grid_community258.AgCheckbox({
label: this.translate("autoRotate"),
value: autoRotate,
onValueChange: updateAutoRotate
})
);
rotationComp.setDisplayed(!autoRotate);
const autoRotateUpdateFn = () => autoRotateCheckbox.setDisplayed(this.isGroupedCategoryAxis());
this.updateFuncs.push(autoRotateUpdateFn);
autoRotateUpdateFn();
return autoRotateCheckbox;
}
createRotationWidget(labelKey, chartAxisThemeOverrides) {
const chartOptions = chartAxisThemeOverrides.getChartOptions();
const getLabelRotationValue = () => {
return chartOptions.getValue("label.rotation");
};
const setLabelRotationValue = (value) => {
return chartOptions.setValue("label.rotation", value);
};
const degreesSymbol = String.fromCharCode(176);
const label = `${this.chartTranslation.translate(labelKey)} ${degreesSymbol}`;
const angleSelect = new AgAngleSelect({
label,
labelWidth: "flex",
value: getLabelRotationValue() ?? 0,
onValueChange: setLabelRotationValue
});
this.updateFuncs.push(() => {
angleSelect.setValue(getLabelRotationValue() ?? 0);
});
return this.createBean(angleSelect);
}
isGroupedCategoryAxis() {
const axisOptionsType = this.chartOptionsService.getCartesianAxisOptionsProxy(this.axisType).getValue("type");
if (axisOptionsType === "grouped-category") {
return !this.isCategoryAxis();
}
return true;
}
addLabelPadding(labelPanelComp, chartAxisThemeOverrides) {
const labelPaddingSlider = this.createBean(
new AgSlider(chartAxisThemeOverrides.getDefaultSliderParams("label.spacing", "padding", 30))
);
labelPanelComp.addItem(labelPaddingSlider);
}
translate(key) {
return this.chartTranslation.translate(key);
}
removeTemplateComponent(component) {
(0, import_ag_grid_community258._removeFromParent)(component.getGui());
this.destroyBean(component);
}
destroyActivePanels() {
this.activePanels.forEach((panel) => {
(0, import_ag_grid_community258._removeFromParent)(panel.getGui());
this.destroyBean(panel);
});
}
destroy() {
this.destroyActivePanels();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/axis/polarAxisPanel.ts
var import_ag_grid_community259 = require("ag-grid-community");
var PolarAxisPanel = class extends import_ag_grid_community259.Component {
constructor(options) {
super();
this.options = options;
this.axisGroup = import_ag_grid_community259.RefPlaceholder;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const { isExpandedOnInit: expanded, chartAxisMenuParamsFactory, registerGroupComponent } = this.options;
const axisGroupParams = {
cssIdentifier: "charts-format-top-level",
direction: "vertical",
title: this.translate("polarAxis"),
expanded,
suppressEnabledCheckbox: true
};
const axisColorInputParams = chartAxisMenuParamsFactory.getDefaultColorPickerParams("line.stroke");
const axisLineWidthSliderParams = chartAxisMenuParamsFactory.getDefaultSliderParams(
"line.width",
"thickness",
10
);
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="axisGroup">
<ag-color-picker data-ref="axisColorInput"></ag-color-picker>
<ag-slider data-ref="axisLineWidthSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, AgColorPickerSelector, AgSliderSelector],
{
axisGroup: axisGroupParams,
axisColorInput: axisColorInputParams,
axisLineWidthSlider: axisLineWidthSliderParams
}
);
registerGroupComponent(this.axisGroup);
this.initAxis();
this.initAxisLabels();
this.initRadiusAxis();
}
initAxis() {
const chartType = this.options.chartController.getChartType();
const hasConfigurableAxisShape = ["radarLine", "radarArea"].includes(chartType);
if (hasConfigurableAxisShape) {
const options = [
{ value: "circle", text: this.translate("circle") },
{ value: "polygon", text: this.translate("polygon") }
];
this.axisGroup.addItem(
this.createSelect({
labelKey: "shape",
options,
property: "shape"
})
);
}
if (chartType !== "pie") {
this.axisGroup.addItem(
this.createSlider({
labelKey: "innerRadius",
defaultMaxValue: 1,
property: "innerRadiusRatio"
})
);
}
}
initAxisLabels() {
const params = {
name: this.translate("labels"),
enabled: true,
suppressEnabledCheckbox: true,
chartMenuParamsFactory: this.options.chartAxisMenuParamsFactory,
keyMapper: (key) => `label.${key}`
};
const labelPanelComp = this.createManagedBean(new FontPanel(params));
const labelOrientationComp = this.createOrientationWidget();
labelPanelComp.addItem(labelOrientationComp);
this.axisGroup.addItem(labelPanelComp);
}
createOrientationWidget() {
const options = [
{ value: "fixed", text: this.translate("fixed") },
{ value: "parallel", text: this.translate("parallel") },
{ value: "perpendicular", text: this.translate("perpendicular") }
];
return this.createSelect({
labelKey: "orientation",
options,
property: "label.orientation"
});
}
initRadiusAxis() {
const chartSeriesType = getSeriesType(this.options.chartController.getChartType());
if (!isRadial(chartSeriesType))
return;
const items = [
this.createSlider({
labelKey: "groupPadding",
defaultMaxValue: 1,
property: "paddingInner"
}),
this.createSlider({
labelKey: "seriesPadding",
defaultMaxValue: 1,
property: "groupPaddingInner"
})
];
const paddingPanelComp = this.createManagedBean(
new AgGroupComponent({
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
suppressOpenCloseIcons: true,
enabled: true,
suppressEnabledCheckbox: true,
title: this.translate("padding"),
items
})
).hideEnabledCheckbox(true).hideOpenCloseIcons(true);
this.axisGroup.addItem(paddingPanelComp);
}
createSlider(config) {
const { labelKey, defaultMaxValue, step = 0.05, property } = config;
const params = this.options.chartAxisMenuParamsFactory.getDefaultSliderParams(
property,
labelKey,
defaultMaxValue
);
params.step = step;
return this.createManagedBean(new AgSlider(params));
}
createSelect(config) {
const { labelKey, options, property } = config;
return this.createManagedBean(
new import_ag_grid_community259.AgSelect(this.options.chartAxisMenuParamsFactory.getDefaultSelectParams(property, labelKey, options))
);
}
translate(key) {
return this.chartTranslation.translate(key);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/chart/chartPanel.ts
var import_ag_grid_community262 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/chart/backgroundPanel.ts
var import_ag_grid_community260 = require("ag-grid-community");
var BackgroundPanel = class extends import_ag_grid_community260.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const chartBackgroundGroupParams = this.chartMenuUtils.addEnableParams(
"background.visible",
{
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: this.chartTranslation.translate("background"),
suppressEnabledCheckbox: true,
useToggle: true
}
);
const colorPickerParams = this.chartMenuUtils.getDefaultColorPickerParams("background.fill");
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="chartBackgroundGroup">
<ag-color-picker data-ref="colorPicker"></ag-color-picker>
</ag-group-component>
<div>`,
[AgGroupComponentSelector, AgColorPickerSelector],
{
chartBackgroundGroup: chartBackgroundGroupParams,
colorPicker: colorPickerParams
}
);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/chart/paddingPanel.ts
var import_ag_grid_community261 = require("ag-grid-community");
var PaddingPanel = class extends import_ag_grid_community261.Component {
constructor(chartMenuUtils, chartController) {
super();
this.chartMenuUtils = chartMenuUtils;
this.chartController = chartController;
this.paddingTopSlider = import_ag_grid_community261.RefPlaceholder;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const chartPaddingGroupParams = {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: this.chartTranslation.translate("padding"),
suppressEnabledCheckbox: true
};
const getSliderParams = (property) => this.chartMenuUtils.getDefaultSliderParams("padding." + property, property, 200);
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="chartPaddingGroup">
<ag-slider data-ref="paddingTopSlider"></ag-slider>
<ag-slider data-ref="paddingRightSlider"></ag-slider>
<ag-slider data-ref="paddingBottomSlider"></ag-slider>
<ag-slider data-ref="paddingLeftSlider"></ag-slider>
</ag-group-component>
<div>`,
[AgGroupComponentSelector, AgSliderSelector],
{
chartPaddingGroup: chartPaddingGroupParams,
paddingTopSlider: getSliderParams("top"),
paddingRightSlider: getSliderParams("right"),
paddingBottomSlider: getSliderParams("bottom"),
paddingLeftSlider: getSliderParams("left")
}
);
this.addManagedEventListeners({
chartOptionsChanged: (e) => {
this.updateTopPadding(e.chartOptions);
}
});
}
updateTopPadding(chartOptions) {
const topPadding = [...this.chartController.getChartSeriesTypes(), "common"].map((seriesType) => chartOptions?.[seriesType]?.padding?.top).find((value) => value != null);
if (topPadding != null) {
this.paddingTopSlider.setValue(`${topPadding}`);
}
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/chart/chartPanel.ts
var ChartPanel = class extends import_ag_grid_community262.Component {
constructor(options) {
super();
this.options = options;
this.chartGroup = import_ag_grid_community262.RefPlaceholder;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const {
chartController,
chartMenuParamsFactory,
isExpandedOnInit: expanded,
registerGroupComponent
} = this.options;
const chartGroupParams = {
cssIdentifier: "charts-format-top-level",
direction: "vertical",
title: this.chartTranslation.translate("chartStyle"),
expanded,
suppressEnabledCheckbox: true,
items: [
this.createManagedBean(new PaddingPanel(chartMenuParamsFactory, chartController)),
this.createManagedBean(new BackgroundPanel(chartMenuParamsFactory))
]
};
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="chartGroup"></ag-group-component>
</div>`,
[AgGroupComponentSelector],
{ chartGroup: chartGroupParams }
);
registerGroupComponent(this.chartGroup);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/groupExpansionFeature.ts
var import_ag_grid_community263 = require("ag-grid-community");
var GroupExpansionFeature = class extends import_ag_grid_community263.BeanStub {
constructor(groupContainer) {
super();
this.groupContainer = groupContainer;
this.id = 0;
this.groupComponents = /* @__PURE__ */ new Map();
}
addGroupComponent(groupComponent) {
const id = this.id++;
this.groupComponents.set(id, groupComponent);
if (groupComponent.isExpanded()) {
this.expandedGroupComponent = id;
}
groupComponent.onExpandedChange((expanded) => {
if (expanded) {
const previouslyExpandedGroupComponent = this.expandedGroupComponent;
this.expandedGroupComponent = id;
if (previouslyExpandedGroupComponent != null) {
const groupComponentGui = groupComponent.getGui();
const groupPositionInViewport = groupComponentGui.offsetTop - this.groupContainer.parentElement.scrollTop;
this.groupComponents.get(previouslyExpandedGroupComponent)?.toggleGroupExpand(false, true);
let newScrollTop = groupComponentGui.offsetTop - groupPositionInViewport;
if (newScrollTop < 0) {
newScrollTop = 0;
}
if (newScrollTop !== this.groupContainer.parentElement.scrollTop) {
this.groupContainer.parentElement.scrollTop = newScrollTop;
}
}
} else {
this.expandedGroupComponent = void 0;
}
});
}
destroy() {
this.groupComponents.clear();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/legend/legendPanel.ts
var import_ag_grid_community264 = require("ag-grid-community");
var LegendPanel = class extends import_ag_grid_community264.Component {
constructor(options, chartMenuContext) {
super();
this.options = options;
this.chartMenuContext = chartMenuContext;
this.legendGroup = import_ag_grid_community264.RefPlaceholder;
this.enabledGroup = import_ag_grid_community264.RefPlaceholder;
this.isGradient = ["treemap", "sunburst", "heatmap"].includes(options.seriesType);
this.key = this.isGradient ? "gradientLegend" : "legend";
this.chartController = chartMenuContext.chartController;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const { chartMenuParamsFactory, isExpandedOnInit: expanded, registerGroupComponent } = this.options;
const positionSelect = this.createManagedBean(
new import_ag_grid_community264.AgSelect(
chartMenuParamsFactory.getDefaultSelectParams(
`${this.key}.position`,
"position",
["top", "right", "bottom", "left"].map((position) => ({
value: position,
text: this.chartTranslation.translate(position)
}))
)
)
);
this.enabledGroup = this.createManagedBean(
new AgGroupComponent(
chartMenuParamsFactory.addEnableParams(`${this.key}.enabled`, {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: this.chartTranslation.translate("legendEnabled"),
suppressEnabledCheckbox: true,
useToggle: true,
items: [
this.createLabelPanel(chartMenuParamsFactory),
positionSelect,
...this.getItems(chartMenuParamsFactory)
]
})
)
);
const legendGroupParams = {
cssIdentifier: "charts-format-top-level",
direction: "vertical",
title: this.chartTranslation.translate("legend"),
suppressEnabledCheckbox: true,
expanded,
items: [this.enabledGroup]
};
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="legendGroup">
</ag-group-component>
</div>`,
[AgGroupComponentSelector],
{
legendGroup: legendGroupParams
}
);
registerGroupComponent(this.legendGroup);
const listener = this.updateLegendEnabledState.bind(this);
this.addManagedListeners(this.chartController, {
chartModelUpdate: listener,
chartApiUpdate: listener
});
}
updateLegendEnabledState() {
const { valueCols } = this.chartController.getColStateForMenu();
this.enabledGroup.setEnabled(valueCols.filter((vc) => vc.selected).length > 1);
}
getItems(chartMenuParamsFactory) {
const createSlider = (expression, labelKey, defaultMaxValue) => this.createManagedBean(
new AgSlider(
chartMenuParamsFactory.getDefaultSliderParams(
`${this.key}.${expression}`,
labelKey,
defaultMaxValue
)
)
);
if (this.isGradient) {
return [
this.createManagedBean(
new import_ag_grid_community264.AgCheckbox(
chartMenuParamsFactory.addValueParams("gradientLegend.reverseOrder", {
label: this.chartTranslation.translate("reverseDirection"),
labelWidth: "flex"
})
)
),
createSlider("gradient.thickness", "thickness", 40),
createSlider("gradient.preferredLength", "preferredLength", 300),
createSlider("spacing", "spacing", 200)
];
}
return [
createSlider("spacing", "spacing", 200),
createSlider("item.marker.size", "markerSize", 40),
createSlider("item.marker.strokeWidth", "markerStroke", 10),
createSlider("item.marker.padding", "itemSpacing", 20),
createSlider("item.paddingX", "layoutHorizontalSpacing", 50),
createSlider("item.paddingY", "layoutVerticalSpacing", 50)
];
}
createLabelPanel(chartMenuParamsFactory) {
const rootKey = this.isGradient ? "gradientLegend.scale.label" : "legend.item.label";
const params = {
enabled: true,
suppressEnabledCheckbox: true,
chartMenuParamsFactory,
keyMapper: (key) => `${rootKey}.${key}`,
cssIdentifier: "charts-format-sub-level-no-header"
};
return this.createManagedBean(new FontPanel(params));
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/seriesPanel.ts
var import_ag_grid_community275 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/toggleablePanel.ts
var import_ag_grid_community265 = require("ag-grid-community");
var ToggleablePanel = class extends import_ag_grid_community265.Component {
constructor(params) {
super();
this.params = params;
this.toggleableGroup = import_ag_grid_community265.RefPlaceholder;
this.activeComps = [];
this.chartOptions = params.chartMenuParamsFactory.getChartOptions();
}
postConstruct() {
const { tag, cssIdentifier = "charts-format-sub-level", title, suppressEnabledCheckbox } = this.params;
const groupParams = this.params.chartMenuParamsFactory.addEnableParams(`${tag}.enabled`, {
cssIdentifier,
direction: "vertical",
suppressOpenCloseIcons: true,
title,
suppressEnabledCheckbox: true,
useToggle: !suppressEnabledCheckbox
});
this.setTemplate(
/* html */
`<div class="ag-toggleable-group-panel">
<ag-group-component data-ref="toggleableGroup">
</ag-group-component>
</div>`,
[AgGroupComponentSelector],
{
toggleableGroup: groupParams
}
);
this.toggleCss(`ag-toggleable-group-panel-no-header`, !title);
}
addItem(comp, prepend) {
if (prepend) {
this.toggleableGroup.prependItem(comp);
} else {
this.toggleableGroup.addItem(comp);
}
this.activeComps.push(comp);
}
setEnabled(enabled) {
this.toggleableGroup.setEnabled(enabled);
}
destroyActiveComps() {
this.activeComps.forEach((comp) => {
(0, import_ag_grid_community265._removeFromParent)(comp.getGui());
this.destroyBean(comp);
});
}
destroy() {
this.destroyActiveComps();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/calloutPanel.ts
var import_ag_grid_community266 = require("ag-grid-community");
var CalloutPanel = class extends import_ag_grid_community266.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const calloutGroupParams = {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
title: this.chartTranslation.translate("callout"),
enabled: true,
suppressOpenCloseIcons: true,
suppressEnabledCheckbox: true
};
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="calloutGroup">
<ag-slider data-ref="calloutLengthSlider"></ag-slider>
<ag-slider data-ref="calloutStrokeWidthSlider"></ag-slider>
<ag-slider data-ref="labelOffsetSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, AgSliderSelector],
{
calloutGroup: calloutGroupParams,
calloutLengthSlider: this.chartMenuUtils.getDefaultSliderParams("calloutLine.length", "length", 40),
calloutStrokeWidthSlider: this.chartMenuUtils.getDefaultSliderParams(
"calloutLine.strokeWidth",
"strokeWidth",
10
),
labelOffsetSlider: this.chartMenuUtils.getDefaultSliderParams("calloutLabel.offset", "offset", 30)
}
);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/capsPanel.ts
var import_ag_grid_community267 = require("ag-grid-community");
var CapsPanel = class extends import_ag_grid_community267.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const capsGroupParams = {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
title: this.chartTranslation.translate("cap"),
enabled: true,
suppressOpenCloseIcons: true,
suppressEnabledCheckbox: true
};
const capLengthRatioSliderParams = this.chartMenuUtils.getDefaultSliderParams(
"cap.lengthRatio",
"capLengthRatio",
1
);
capLengthRatioSliderParams.step = 0.05;
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="capsGroup">
<ag-slider data-ref="capLengthRatioSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, AgSliderSelector],
{
capsGroup: capsGroupParams,
capLengthRatioSlider: capLengthRatioSliderParams
}
);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/connectorLinePanel.ts
var import_ag_grid_community268 = require("ag-grid-community");
var ConnectorLinePanel = class extends import_ag_grid_community268.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const lineGroupParams = {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
title: this.chartTranslation.translate("connectorLine"),
enabled: true,
suppressOpenCloseIcons: true,
suppressEnabledCheckbox: true
};
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="lineGroup">
<ag-color-picker data-ref="lineColorPicker"></ag-color-picker>
<ag-slider data-ref="lineStrokeWidthSlider"></ag-slider>
<ag-slider data-ref="lineOpacitySlider"></ag-slider>
<ag-slider data-ref="lineDashSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, AgColorPickerSelector, AgSliderSelector],
{
lineGroup: lineGroupParams,
lineColorPicker: this.chartMenuUtils.getDefaultColorPickerParams("line.stroke"),
lineStrokeWidthSlider: this.getSliderParams("strokeWidth", 10, "line.strokeWidth"),
lineDashSlider: this.getSliderParams("lineDash", 30, "line.lineDash", 1, true),
lineOpacitySlider: this.getSliderParams("strokeOpacity", 1, "line.strokeOpacity", 0.05)
}
);
}
getSliderParams(labelKey, maxValue, seriesOptionKey, step = 1, isArray = false) {
const params = this.chartMenuUtils.getDefaultSliderParams(seriesOptionKey, labelKey, maxValue, isArray);
params.step = step;
return params;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/markersPanel.ts
var import_ag_grid_community269 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/seriesUtils.ts
function getShapeSelectOptions(chartTranslation) {
return ["square", "circle", "cross", "diamond", "plus", "triangle", "heart"].map((value) => ({
value,
text: chartTranslation.translate(value)
}));
}
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/markersPanel.ts
var MarkersPanel = class extends import_ag_grid_community269.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const seriesMarkersGroupParams = this.chartMenuUtils.addEnableParams("marker.enabled", {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
title: this.chartTranslation.translate("markers"),
suppressEnabledCheckbox: true,
useToggle: true,
suppressOpenCloseIcons: true
});
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="seriesMarkersGroup">
<ag-select data-ref="seriesMarkerShapeSelect"></ag-select>
<ag-slider data-ref="seriesMarkerSizeSlider"></ag-slider>
<ag-slider data-ref="seriesMarkerStrokeWidthSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, import_ag_grid_community269.AgSelectSelector, AgSliderSelector],
{
seriesMarkersGroup: seriesMarkersGroupParams,
seriesMarkerShapeSelect: this.chartMenuUtils.getDefaultSelectParams(
"marker.shape",
"shape",
getShapeSelectOptions(this.chartTranslation)
),
seriesMarkerSizeSlider: this.chartMenuUtils.getDefaultSliderParams("marker.size", "size", 60),
seriesMarkerStrokeWidthSlider: this.chartMenuUtils.getDefaultSliderParams(
"marker.strokeWidth",
"strokeWidth",
10
)
}
);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/seriesItemsPanel.ts
var import_ag_grid_community270 = require("ag-grid-community");
var SeriesItemsPanel = class extends import_ag_grid_community270.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
this.seriesItemsGroup = import_ag_grid_community270.RefPlaceholder;
this.activePanels = [];
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const seriesItemsGroupParams = {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
title: this.chartTranslation.translate("seriesItems"),
enabled: true,
suppressOpenCloseIcons: true,
suppressEnabledCheckbox: true
};
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="seriesItemsGroup">
<ag-select data-ref="seriesItemSelect"></ag-select>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, import_ag_grid_community270.AgSelectSelector],
{
seriesItemsGroup: seriesItemsGroupParams,
seriesItemSelect: this.getSeriesItemsParams()
}
);
this.initSeriesControls();
}
getSeriesItemsParams() {
const options = [
{ value: "positive", text: this.chartTranslation.translate("seriesItemPositive") },
{ value: "negative", text: this.chartTranslation.translate("seriesItemNegative") }
];
const seriesItemChangedCallback = (newValue) => {
this.destroyActivePanels();
this.initSeriesControls(newValue);
};
return this.chartMenuUtils.getDefaultSelectParamsWithoutValueParams(
"seriesItemType",
options,
"positive",
seriesItemChangedCallback
);
}
initSeriesControls(itemType = "positive") {
this.initSlider("strokeWidth", 10, `item.${itemType}.strokeWidth`);
this.initSlider("lineDash", 30, `item.${itemType}.lineDash`, 1, true);
this.initSlider("strokeOpacity", 1, `item.${itemType}.strokeOpacity`, 0.05, false);
this.initSlider("fillOpacity", 1, `item.${itemType}.fillOpacity`, 0.05, false);
this.initItemLabels(itemType);
}
initSlider(labelKey, maxValue, seriesOptionKey, step = 1, isArray = false) {
const params = this.chartMenuUtils.getDefaultSliderParams(seriesOptionKey, labelKey, maxValue, isArray);
params.step = step;
const itemSlider = this.seriesItemsGroup.createManagedBean(new AgSlider(params));
this.seriesItemsGroup.addItem(itemSlider);
this.activePanels.push(itemSlider);
}
initItemLabels(itemType) {
const sectorParams = this.chartMenuUtils.getDefaultFontPanelParams(
`item.${itemType}.label`,
"seriesItemLabels"
);
const labelPanelComp = this.createBean(new FontPanel(sectorParams));
this.seriesItemsGroup.addItem(labelPanelComp);
this.activePanels.push(labelPanelComp);
}
destroyActivePanels() {
this.activePanels.forEach((panel) => {
(0, import_ag_grid_community270._removeFromParent)(panel.getGui());
this.destroyBean(panel);
});
}
destroy() {
this.destroyActivePanels();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/shadowPanel.ts
var import_ag_grid_community271 = require("ag-grid-community");
var ShadowPanel = class extends import_ag_grid_community271.Component {
constructor(chartMenuUtils, propertyKey = "shadow") {
super();
this.chartMenuUtils = chartMenuUtils;
this.propertyKey = propertyKey;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const propertyNamespace = this.propertyKey;
const shadowGroupParams = this.chartMenuUtils.addEnableParams(
`${propertyNamespace}.enabled`,
{
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: this.chartTranslation.translate("shadow"),
suppressEnabledCheckbox: true,
useToggle: true
}
);
const shadowColorPickerParams = this.chartMenuUtils.getDefaultColorPickerParams(`${propertyNamespace}.color`);
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="shadowGroup">
<ag-color-picker data-ref="shadowColorPicker"></ag-color-picker>
<ag-slider data-ref="shadowBlurSlider"></ag-slider>
<ag-slider data-ref="shadowXOffsetSlider"></ag-slider>
<ag-slider data-ref="shadowYOffsetSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, AgColorPickerSelector, AgSliderSelector],
{
shadowGroup: shadowGroupParams,
shadowColorPicker: shadowColorPickerParams,
shadowBlurSlider: this.getSliderParams("blur", 0, 20),
shadowXOffsetSlider: this.getSliderParams("xOffset", -10, 10),
shadowYOffsetSlider: this.getSliderParams("yOffset", -10, 10)
}
);
}
getSliderParams(property, minValue, defaultMaxValue) {
const expression = `${this.propertyKey}.${property}`;
const params = this.chartMenuUtils.getDefaultSliderParams(expression, property, defaultMaxValue);
params.minValue = minValue;
return params;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/tileSpacingPanel.ts
var import_ag_grid_community272 = require("ag-grid-community");
var TileSpacingPanel = class extends import_ag_grid_community272.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const groupParams = {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
enabled: true,
suppressOpenCloseIcons: true,
suppressEnabledCheckbox: true
};
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="groupSpacing">
<ag-slider data-ref="groupPaddingSlider"></ag-slider>
<ag-slider data-ref="groupSpacingSlider"></ag-slider>
</ag-group-component>
<ag-group-component data-ref="tileSpacing">
<ag-slider data-ref="tilePaddingSlider"></ag-slider>
<ag-slider data-ref="tileSpacingSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, AgSliderSelector],
{
groupSpacing: { ...groupParams, title: this.chartTranslation.translate("group") },
tileSpacing: { ...groupParams, title: this.chartTranslation.translate("tile") },
groupPaddingSlider: this.getSliderParams("padding", "group.padding"),
groupSpacingSlider: this.getSliderParams("spacing", "group.gap"),
tilePaddingSlider: this.getSliderParams("padding", "tile.padding"),
tileSpacingSlider: this.getSliderParams("spacing", "tile.gap")
}
);
}
getSliderParams(labelKey, key) {
return this.chartMenuUtils.getDefaultSliderParams(key, labelKey, 10);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/tooltipPanel.ts
var import_ag_grid_community273 = require("ag-grid-community");
function _capitalise2(str) {
return str[0].toUpperCase() + str.substring(1);
}
var TooltipPanel = class extends import_ag_grid_community273.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
this.tooltipMode = import_ag_grid_community273.RefPlaceholder;
}
postConstruct() {
const { chartMenuUtils, beans } = this;
const propertyKey = "tooltip";
const chartTranslation = beans.chartTranslation;
const tooltipGroupParams = chartMenuUtils.addEnableParams(`${propertyKey}.enabled`, {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
suppressOpenCloseIcons: true,
title: chartTranslation.translate("tooltips"),
suppressEnabledCheckbox: true,
useToggle: true
});
const tooltipModeLocaleKey = "tooltipMode";
const tooltipModeSelectionOptions = ["single", "shared", "compact"].map((value) => ({
value,
text: chartTranslation.translate(`${tooltipModeLocaleKey}${_capitalise2(value)}`)
}));
const tooltipModeExpression = `${propertyKey}.mode`;
const tooltipModeSelectParams = chartMenuUtils.getDefaultSelectParams(
tooltipModeExpression,
tooltipModeLocaleKey,
tooltipModeSelectionOptions
);
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="tooltipGroup">
<ag-select data-ref="tooltipMode"></ag-select>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, import_ag_grid_community273.AgSelectSelector],
{
tooltipGroup: tooltipGroupParams,
tooltipMode: tooltipModeSelectParams
}
);
this.addManagedEventListeners({
chartOptionsChanged: () => {
const tooltipModeValue = chartMenuUtils.getChartOptions().getValue(tooltipModeExpression);
this.tooltipMode.setValue(tooltipModeValue, true);
}
});
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/whiskersPanel.ts
var import_ag_grid_community274 = require("ag-grid-community");
var WhiskersPanel = class extends import_ag_grid_community274.Component {
constructor(chartMenuUtils) {
super();
this.chartMenuUtils = chartMenuUtils;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const whiskersGroupParams = {
cssIdentifier: "charts-format-sub-level",
direction: "vertical",
title: this.chartTranslation.translate("whisker"),
enabled: true,
suppressOpenCloseIcons: true,
suppressEnabledCheckbox: true
};
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="whiskersGroup">
<ag-color-picker data-ref="whiskerColorPicker"></ag-color-picker>
<ag-slider data-ref="whiskerThicknessSlider"></ag-slider>
<ag-slider data-ref="whiskerOpacitySlider"></ag-slider>
<ag-slider data-ref="whiskerLineDashSlider"></ag-slider>
<ag-slider data-ref="whiskerLineDashOffsetSlider"></ag-slider>
</ag-group-component>
</div>`,
[AgGroupComponentSelector, AgColorPickerSelector, AgSliderSelector],
{
whiskersGroup: whiskersGroupParams,
whiskerColorPicker: this.chartMenuUtils.getDefaultColorPickerParams("whisker.stroke"),
whiskerThicknessSlider: this.chartMenuUtils.getDefaultSliderParams(
"whisker.strokeWidth",
"strokeWidth",
10
),
whiskerOpacitySlider: this.chartMenuUtils.getDefaultSliderParams(
"whisker.strokeOpacity",
"strokeOpacity",
1
),
whiskerLineDashSlider: this.chartMenuUtils.getDefaultSliderParams(
"whisker.lineDash",
"lineDash",
30,
true
),
whiskerLineDashOffsetSlider: this.chartMenuUtils.getDefaultSliderParams(
"whisker.lineDashOffset",
"lineDashOffset",
30
)
}
);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/seriesPanel.ts
var tooltips = "tooltips";
var strokeWidth = "strokeWidth";
var lineWidth = "lineWidth";
var lineDash = "lineDash";
var lineOpacity = "lineOpacity";
var fillOpacity = "fillOpacity";
var labels = "labels";
var shadow = "shadow";
var stageLabels = "stageLabels";
var markers = "markers";
var SeriesPanel = class extends import_ag_grid_community275.Component {
constructor(options) {
super();
this.options = options;
this.seriesGroup = import_ag_grid_community275.RefPlaceholder;
this.activePanels = [];
this.widgetFuncs = {
lineWidth: () => this.initStrokeWidth(lineWidth),
[strokeWidth]: () => this.initStrokeWidth("strokeWidth"),
lineColor: () => this.initLineColor(),
[lineDash]: () => this.initLineDash(),
[lineOpacity]: () => this.initOpacity("strokeOpacity"),
[fillOpacity]: () => this.initOpacity("fillOpacity"),
markers: () => new MarkersPanel(this.chartMenuUtils),
[labels]: () => this.initLabels(),
sectorLabels: () => this.initSectorLabels(),
[shadow]: () => new ShadowPanel(this.chartMenuUtils),
[tooltips]: () => new TooltipPanel(this.options.chartMenuParamsFactory),
bins: () => this.initBins(),
whiskers: () => new WhiskersPanel(this.chartMenuUtils),
caps: () => new CapsPanel(this.chartMenuUtils),
connectorLine: () => new ConnectorLinePanel(this.chartMenuUtils),
seriesItems: () => new SeriesItemsPanel(this.chartMenuUtils),
tileSpacing: () => new TileSpacingPanel(this.chartMenuUtils),
shape: () => this.initShape(),
size: () => this.initSize("size", "size"),
minSize: () => this.initSize("size", "minSize"),
maxSize: () => this.initSize("maxSize", "maxSize"),
dropoff: () => this.initDropOff(),
stageLabels: () => this.initStageLabels()
};
this.seriesWidgetMappings = {
bar: [tooltips, strokeWidth, lineDash, lineOpacity, fillOpacity, labels, shadow],
pie: [tooltips, strokeWidth, lineOpacity, fillOpacity, labels, "sectorLabels", shadow],
donut: [tooltips, strokeWidth, lineOpacity, fillOpacity, labels, "sectorLabels", shadow],
line: [tooltips, lineWidth, lineDash, lineOpacity, markers, labels],
scatter: [tooltips, "shape", "size", strokeWidth, labels],
bubble: [tooltips, "shape", "minSize", "maxSize", strokeWidth, labels],
area: [tooltips, lineWidth, lineDash, lineOpacity, fillOpacity, markers, labels, shadow],
histogram: [tooltips, "bins", strokeWidth, lineDash, lineOpacity, fillOpacity, labels, shadow],
"radial-column": [tooltips, strokeWidth, lineDash, lineOpacity, fillOpacity, labels],
"radial-bar": [tooltips, strokeWidth, lineDash, lineOpacity, fillOpacity, labels],
"radar-line": [tooltips, strokeWidth, lineDash, lineOpacity, markers, labels],
"radar-area": [tooltips, strokeWidth, lineDash, lineOpacity, fillOpacity, markers, labels],
nightingale: [tooltips, strokeWidth, lineDash, lineOpacity, fillOpacity, labels],
"box-plot": [tooltips, strokeWidth, lineDash, lineOpacity, fillOpacity, "whiskers", "caps"],
"range-bar": [tooltips, strokeWidth, lineDash, lineOpacity, fillOpacity, labels],
"range-area": [tooltips, lineWidth, lineDash, lineOpacity, fillOpacity, markers, labels, shadow],
treemap: [tooltips, "tileSpacing"],
sunburst: [tooltips],
heatmap: [tooltips, labels, "lineColor", lineWidth, lineOpacity],
waterfall: [tooltips, "connectorLine", "seriesItems"],
funnel: [tooltips, strokeWidth, lineDash, lineOpacity, fillOpacity, labels, "dropoff", stageLabels, shadow],
"cone-funnel": [tooltips, strokeWidth, lineDash, lineOpacity, fillOpacity, labels, stageLabels],
pyramid: [tooltips, strokeWidth, lineDash, lineOpacity, fillOpacity, labels, stageLabels, shadow]
};
this.seriesType = options.seriesType;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const {
isExpandedOnInit: expanded,
chartOptionsService,
chartController,
registerGroupComponent
} = this.options;
const seriesGroupParams = {
cssIdentifier: "charts-format-top-level",
direction: "vertical",
title: this.translate("series"),
expanded,
suppressEnabledCheckbox: true
};
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="seriesGroup">
</ag-group-component>
</div>`,
[AgGroupComponentSelector],
{ seriesGroup: seriesGroupParams }
);
registerGroupComponent(this.seriesGroup);
this.chartMenuUtils = this.createManagedBean(
new ChartMenuParamsFactory(chartOptionsService.getSeriesOptionsProxy(() => this.seriesType))
);
this.addManagedListeners(chartController, { chartSeriesChartTypeChanged: this.refreshWidgets.bind(this) });
this.refreshWidgets();
}
refreshWidgets() {
const { chartController } = this.options;
this.destroyActivePanels();
const chart = chartController.getChartProxy().getChart();
chart.waitForUpdate().then(() => {
const componentWasRemoved = !this.isAlive();
if (componentWasRemoved) {
return;
}
if (chartController.isComboChart()) {
this.updateSeriesType();
this.initSeriesSelect();
}
(this.seriesWidgetMappings[this.seriesType] ?? []).forEach((w) => {
const widgetFuncResult = this.widgetFuncs[w]();
let widget;
if (Array.isArray(widgetFuncResult)) {
const comp = this.createBean(widgetFuncResult[0]);
widget = comp;
widgetFuncResult[1](comp);
} else {
widget = this.createBean(widgetFuncResult);
}
this.seriesGroup.addItem(widget);
this.activePanels.push(widget);
});
}).catch((e) => (0, import_ag_grid_community275._error)(105, { e }));
}
initSeriesSelect() {
const seriesSelect = this.createBean(
new import_ag_grid_community275.AgSelect(
this.chartMenuUtils.getDefaultSelectParamsWithoutValueParams(
"seriesType",
this.getSeriesSelectOptions(),
`${this.seriesType}`,
(newValue) => {
this.seriesType = newValue;
this.refreshWidgets();
}
)
)
);
this.seriesGroup.addItem(seriesSelect);
this.activePanels.push(seriesSelect);
}
initLineColor() {
return new AgColorPicker(this.chartMenuUtils.getDefaultColorPickerParams("stroke", "strokeColor"));
}
initStrokeWidth(labelKey, expression) {
return new AgSlider(
this.chartMenuUtils.getDefaultSliderParams(
expression ? `${expression}.${labelKey}` : "strokeWidth",
labelKey,
10
)
);
}
initLineDash(expression) {
return new AgSlider(
this.chartMenuUtils.getDefaultSliderParams(
expression ? `${expression}.lineDash` : "lineDash",
"lineDash",
30,
true
)
);
}
initOpacity(type, expression) {
const params = this.chartMenuUtils.getDefaultSliderParams(expression ? `${expression}.${type}` : type, type, 1);
params.step = 0.05;
return new AgSlider(params);
}
initDropOff() {
const dropOffGroup = new ToggleablePanel({
tag: "dropOff",
cssIdentifier: "charts-format-sub-level",
title: this.translate("dropOff"),
suppressEnabledCheckbox: false,
chartMenuParamsFactory: this.chartMenuUtils
});
const addItems = (groupComponent) => {
[
this.initStrokeWidth("strokeWidth", "dropOff"),
this.initLineDash("dropOff"),
this.initOpacity("strokeOpacity", "dropOff"),
this.initOpacity("fillOpacity", "dropOff")
].forEach((comp) => {
const managed = groupComponent.createManagedBean(comp);
groupComponent.addItem(managed);
this.activePanels.push(managed);
});
};
return [dropOffGroup, addItems];
}
initLabels() {
const isPieChart = isPieChartSeries(this.seriesType);
const seriesOptionLabelProperty = isPieChart ? "calloutLabel" : "label";
const labelKey = isPieChart ? "calloutLabels" : "labels";
const labelParams = this.chartMenuUtils.getDefaultFontPanelParams(seriesOptionLabelProperty, labelKey);
const fontPanel = new FontPanel(labelParams);
const addItems = (labelPanelComp) => {
if (isPieChart) {
const calloutPanelComp = labelPanelComp.createManagedBean(new CalloutPanel(this.chartMenuUtils));
labelPanelComp.addItem(calloutPanelComp);
this.activePanels.push(calloutPanelComp);
}
if (this.seriesType === "range-bar") {
const options = [
{ value: "inside", text: this.translate("inside") },
{ value: "outside", text: this.translate("outside") }
];
const placementSelect = labelPanelComp.createManagedBean(
new import_ag_grid_community275.AgSelect(
this.chartMenuUtils.getDefaultSelectParams("label.placement", "labelPlacement", options)
)
);
labelPanelComp.addItem(placementSelect);
this.activePanels.push(placementSelect);
const paddingSlider = labelPanelComp.createManagedBean(
new AgSlider(this.chartMenuUtils.getDefaultSliderParams("label.padding", "padding", 200))
);
labelPanelComp.addItem(paddingSlider);
this.activePanels.push(paddingSlider);
}
};
return [fontPanel, addItems];
}
initSectorLabels() {
const sectorParams = this.chartMenuUtils.getDefaultFontPanelParams("sectorLabel", "sectorLabels");
const fontPanel = new FontPanel(sectorParams);
const addItems = (sectorPanelComp) => {
const positionRatioParams = this.chartMenuUtils.getDefaultSliderParams(
"sectorLabel.positionRatio",
"positionRatio",
1
);
positionRatioParams.step = 0.05;
const positionRatioComp = sectorPanelComp.createManagedBean(new AgSlider(positionRatioParams));
sectorPanelComp.addItem(positionRatioComp);
};
return [fontPanel, addItems];
}
initStageLabels() {
return new FontPanel(this.chartMenuUtils.getDefaultFontPanelParams("stageLabel", stageLabels));
}
initBins() {
const params = this.chartMenuUtils.getDefaultSliderParams("binCount", "histogramBinCount", 20);
const chartOptions = this.chartMenuUtils.getChartOptions();
const value = (chartOptions.getValue("bins") ?? chartOptions.getValue("calculatedBins", true)).length;
params.value = `${value}`;
params.maxValue = Math.max(value, 20);
return new AgSlider(params);
}
initShape() {
return new import_ag_grid_community275.AgSelect(
this.chartMenuUtils.getDefaultSelectParams("shape", "shape", getShapeSelectOptions(this.chartTranslation))
);
}
initSize(expression, labelKey) {
return new AgSlider(this.chartMenuUtils.getDefaultSliderParams(expression, labelKey, 60));
}
getSeriesSelectOptions() {
const activeSeriesTypes = this.getActiveSeriesTypes();
return ["area", "bar", "line"].filter((seriesType) => activeSeriesTypes.includes(seriesType)).map((value) => ({ value, text: this.translate(value) }));
}
updateSeriesType() {
const activeSeriesTypes = this.getActiveSeriesTypes();
const invalidSeriesType = !activeSeriesTypes.includes(this.seriesType);
if (invalidSeriesType && activeSeriesTypes.length > 0) {
this.seriesType = activeSeriesTypes[0];
}
}
getActiveSeriesTypes() {
return this.options.chartController.getActiveSeriesChartTypes().map((s) => getSeriesType(s.chartType));
}
translate(key) {
return this.chartTranslation.translate(key);
}
destroyActivePanels() {
this.activePanels.forEach((panel) => {
(0, import_ag_grid_community275._removeFromParent)(panel.getGui());
this.destroyBean(panel);
});
}
destroy() {
this.destroyActivePanels();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/titles/titlesPanel.ts
var import_ag_grid_community277 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/titles/titlePanel.ts
var import_ag_grid_community276 = require("ag-grid-community");
var TitlePanel = class extends import_ag_grid_community276.Component {
constructor(chartMenuUtils, name, key) {
super(
/* html */
`<div></div>`
);
this.chartMenuUtils = chartMenuUtils;
this.name = name;
this.key = key;
this.chartOptions = chartMenuUtils.getChartOptions();
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
this.initFontPanel();
}
hasTitle() {
const title = this.chartOptions.getValue(this.key);
return title && title.enabled && title.text && title.text.length > 0;
}
initFontPanel() {
const hasTitle = this.hasTitle();
const fontPanelParams = {
name: this.chartTranslation.translate(this.name),
enabled: hasTitle,
suppressEnabledCheckbox: false,
chartMenuParamsFactory: this.chartMenuUtils,
keyMapper: (key) => `${this.key}.${key}`,
onEnableChange: (enabled) => this.onEnableChange(enabled)
};
this.fontPanel = this.createManagedBean(new FontPanel(fontPanelParams));
this.fontPanel.addItem(this.createBean(new import_ag_grid_community276.AgInputTextField(this.getTextInputParams())), true);
this.fontPanel.addItem(this.createBean(new AgSlider(this.getSpacingSliderParams())));
this.getGui().appendChild(this.fontPanel.getGui());
}
getTextInputParams() {
return this.chartMenuUtils.addValueParams(`${this.key}.text`, {
label: this.chartTranslation.translate("title"),
labelAlignment: "top"
});
}
getSpacingSliderParams() {
return this.chartMenuUtils.getDefaultSliderParams(`${this.key}.spacing`, "spacing", 100);
}
onEnableChange(enabled) {
this.chartOptions.setValue(`${this.key}.enabled`, enabled);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/titles/chartTitlePanel.ts
var ChartTitlePanel = class extends TitlePanel {
wireBeans(beans) {
super.wireBeans(beans);
this.chartMenuSvc = beans.chartMenuSvc;
}
postConstruct() {
this.titlePlaceholder = this.chartTranslation.translate("titlePlaceholder");
super.postConstruct();
this.addManagedEventListeners({
chartTitleEdit: () => {
this.fontPanel.setEnabled(this.hasTitle());
}
});
}
getTextInputParams() {
const params = super.getTextInputParams();
if (this.shouldOverrideTextWithPlaceholder(params.value)) {
params.value = this.titlePlaceholder;
}
return params;
}
getSpacingSliderParams() {
const params = super.getSpacingSliderParams();
params.value = "10";
return params;
}
onEnableChange(enabled) {
if (this.chartMenuSvc.doesChartToolbarExist()) {
const topPadding = this.chartOptions.getValue("padding.top");
this.chartOptions.setValue("padding.top", enabled ? topPadding - 20 : topPadding + 20);
}
this.chartOptions.setValue(`${this.key}.enabled`, enabled);
const currentTitleText = this.chartOptions.getValue(`${this.key}.text`);
if (enabled && this.shouldOverrideTextWithPlaceholder(currentTitleText)) {
this.chartOptions.setValue(`${this.key}.text`, this.titlePlaceholder);
}
}
shouldOverrideTextWithPlaceholder(currentTitleText) {
return currentTitleText === "Title" || currentTitleText?.trim().length === 0;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/titles/titlesPanel.ts
var TitlesPanel = class extends import_ag_grid_community277.Component {
constructor(options) {
super();
this.options = options;
this.titleGroup = import_ag_grid_community277.RefPlaceholder;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
const {
chartMenuParamsFactory,
chartAxisMenuParamsFactory,
chartOptionsService,
seriesType,
isExpandedOnInit: expanded = false,
registerGroupComponent
} = this.options;
const axisTitlePanels = [];
if (isCartesian(seriesType) && seriesType !== "pyramid") {
const createAxisParamsFactory = (axisType) => this.createManagedBean(
new ChartMenuParamsFactory(chartOptionsService.getCartesianAxisThemeOverridesProxy(axisType))
);
axisTitlePanels.push(
this.createManagedBean(new TitlePanel(createAxisParamsFactory("xAxis"), "horizontalAxisTitle", "title"))
);
axisTitlePanels.push(
this.createManagedBean(new TitlePanel(createAxisParamsFactory("yAxis"), "verticalAxisTitle", "title"))
);
} else if (isPolar(seriesType)) {
axisTitlePanels.push(
this.createManagedBean(new TitlePanel(chartAxisMenuParamsFactory, "polarAxisTitle", "title"))
);
}
const titleGroupParams = {
cssIdentifier: "charts-format-top-level",
direction: "vertical",
title: this.chartTranslation.translate("chartTitles"),
expanded,
suppressEnabledCheckbox: true,
items: [
this.createManagedBean(new ChartTitlePanel(chartMenuParamsFactory, "chartTitle", "title")),
this.createManagedBean(new TitlePanel(chartMenuParamsFactory, "chartSubtitle", "subtitle")),
...axisTitlePanels
]
};
this.setTemplate(
/* html */
`<div>
<ag-group-component data-ref="titleGroup"></ag-group-component>
</div>`,
[AgGroupComponentSelector],
{ titleGroup: titleGroupParams }
);
registerGroupComponent(this.titleGroup);
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/format/formatPanel.ts
var DefaultFormatPanelDef = {
groups: [{ type: "chart" }, { type: "titles" }, { type: "legend" }, { type: "series" }, { type: "axis" }]
};
var AXIS_KEYS = ["axis", "horizontalAxis", "verticalAxis"];
var FormatPanel = class extends import_ag_grid_community278.Component {
constructor(chartMenuContext) {
super(
/* html */
`<div class="ag-chart-format-wrapper"></div>`
);
this.chartMenuContext = chartMenuContext;
}
postConstruct() {
this.groupExpansionFeature = this.createManagedBean(new GroupExpansionFeature(this.getGui()));
this.chartPanelFeature = this.createManagedBean(
new ChartPanelFeature(
this.chartMenuContext.chartController,
this.getGui(),
"ag-chart-format-section",
(_chartType, seriesType) => this.createPanels(seriesType)
)
);
this.chartPanelFeature.refreshPanels();
}
createPanels(seriesType) {
let panelExpandedOnInit = false;
this.getFormatPanelDef().groups?.forEach(({ type: group, isOpen: isExpandedOnInit = false }) => {
if (!this.isGroupPanelShownInSeries(group, seriesType)) {
return;
}
if (isExpandedOnInit) {
if (panelExpandedOnInit) {
(0, import_ag_grid_community278._warn)(145, { group });
}
panelExpandedOnInit = true;
}
const registerGroupComponent = (groupComponent) => this.groupExpansionFeature.addGroupComponent(groupComponent);
const opts = {
...this.chartMenuContext,
isExpandedOnInit,
seriesType,
registerGroupComponent
};
switch (group) {
case "chart":
this.chartPanelFeature.addComponent(new ChartPanel(opts));
break;
case "titles":
this.chartPanelFeature.addComponent(new TitlesPanel(opts));
break;
case "legend":
this.chartPanelFeature.addComponent(new LegendPanel(opts, this.chartMenuContext));
break;
case "axis":
if (isPolar(seriesType)) {
this.chartPanelFeature.addComponent(new PolarAxisPanel(opts));
} else if (isCartesian(seriesType)) {
this.chartPanelFeature.addComponent(new CartesianAxisPanel("xAxis", opts));
this.chartPanelFeature.addComponent(new CartesianAxisPanel("yAxis", opts));
}
break;
case "horizontalAxis":
this.chartPanelFeature.addComponent(new CartesianAxisPanel("xAxis", opts));
break;
case "verticalAxis":
this.chartPanelFeature.addComponent(new CartesianAxisPanel("yAxis", opts));
break;
case "series":
this.chartPanelFeature.addComponent(new SeriesPanel(opts));
break;
default:
(0, import_ag_grid_community278._warn)(147, { group });
}
});
}
getFormatPanelDef() {
const userProvidedFormatPanelDef = this.gos.get("chartToolPanelsDef")?.formatPanel;
return userProvidedFormatPanelDef ? userProvidedFormatPanelDef : DefaultFormatPanelDef;
}
isGroupPanelShownInSeries(group, seriesType) {
const enable = ["chart", "titles", "legend", "series"].includes(group) || isCartesian(seriesType) && AXIS_KEYS.includes(group) || isPolar(seriesType) && group === "axis";
const disable = isFunnel(seriesType) && group === "legend" || isFunnel(seriesType) && AXIS_KEYS.includes(group);
return enable && !disable;
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/chartSettingsPanel.ts
var import_ag_grid_community284 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniChartsContainer.ts
var import_ag_grid_community283 = require("ag-grid-community");
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/miniChart.ts
var import_ag_grid_community279 = require("ag-grid-community");
var CANVAS_CLASS = "ag-chart-mini-thumbnail-canvas";
var MiniChart = class extends import_ag_grid_community279.Component {
constructor(container, agChartsExports, tooltipName) {
super();
this.agChartsExports = agChartsExports;
this.tooltipName = tooltipName;
this.size = 58;
this.padding = 5;
const { _Scene } = agChartsExports;
this.root = new _Scene.Group();
const scene = new _Scene.Scene({
width: this.size,
height: this.size
});
scene.canvas.element.classList.add(CANVAS_CLASS);
scene.setRoot(this.root);
scene.setContainer(container);
this.scene = scene;
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
this.scene.canvas.element.title = this.chartTranslation.translate(this.tooltipName);
try {
this.scene.render();
} catch (e) {
(0, import_ag_grid_community279._error)(108, { e });
}
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/miniChartHelpers.ts
var import_ag_grid_community280 = require("ag-grid-community");
function createColumnRects(params) {
const {
stacked,
size,
padding,
xScalePadding,
xScaleDomain,
yScaleDomain,
agChartsExports: { _Scene }
} = params;
const xScale = new _Scene.CategoryScale();
xScale.domain = xScaleDomain;
xScale.range = [padding, size - padding];
xScale.paddingInner = xScalePadding;
xScale.paddingOuter = xScalePadding;
const yScale = new _Scene.LinearScale();
yScale.domain = yScaleDomain;
yScale.range = [size - padding, padding];
const createBars = (series, xScale2, yScale2) => {
return series.map((datum, i) => {
const top = yScale2.convert(datum);
const rect = new _Scene.Rect();
rect.x = xScale2.convert(i);
rect.y = top;
rect.width = xScale2.bandwidth;
rect.height = yScale2.convert(0) - top;
rect.strokeWidth = 0;
rect.crisp = true;
return rect;
});
};
if (stacked) {
return params.data.map((d) => createBars(d, xScale, yScale));
}
return createBars(params.data, xScale, yScale);
}
function prepareXYScales(_Scene, data, size, padding) {
const xDomain = [];
const yDomain = [];
data.forEach((item) => {
item.forEach(([x, y]) => {
xDomain.push(x);
yDomain.push(y);
});
});
const xScale = new _Scene.LinearScale();
xScale.domain = [Math.min(...xDomain), Math.max(...xDomain)];
xScale.range = [padding, size - padding];
const yScale = new _Scene.LinearScale();
yScale.domain = [Math.min(...yDomain), Math.max(...yDomain)];
yScale.range = [size - padding, padding];
return { xScale, yScale };
}
function prepareLinearScene(_Scene, data, size, padding) {
const xDomain = [0, data[0].length - 1];
const yDomain = data.reduce(
(acc, curr) => {
curr.forEach((datum) => {
if (datum < acc[0]) {
acc[0] = datum;
}
if (datum > acc[1]) {
acc[1] = datum;
}
});
return acc;
},
[Infinity, -Infinity]
);
yDomain[0]--;
yDomain[yDomain.length - 1]++;
const xScale = new _Scene.LinearScale();
xScale.domain = xDomain;
xScale.range = [padding, size - padding];
const yScale = new _Scene.LinearScale();
yScale.domain = yDomain;
yScale.range = [size - padding, padding];
return { xScale, yScale };
}
function createXPathCommands(data, xScale, yScale) {
return data.map(
(series) => series.map((datum, i) => [
i > 0 ? "lineTo" : "moveTo",
xScale.convert(i),
yScale.convert(datum)
])
);
}
function createXYPathCommands(shape, xScale, yScale) {
return shape.map(([x, y], i) => [i > 0 ? "lineTo" : "moveTo", xScale.convert(x), yScale.convert(y)]);
}
function closePath(commandSegments) {
const closingCommand = commandSegments[0];
const first = commandSegments[1];
const last = (0, import_ag_grid_community280._last)(commandSegments);
if (first[1] !== last[1] || first[2] !== last[2]) {
commandSegments.push([closingCommand[0], first[1], first[2]]);
}
return commandSegments;
}
function createPath(_Scene, commands) {
const path = new _Scene.Path();
commands.forEach(([command, x, y]) => path.path[command](x, y));
return path;
}
function createAreaPathCommands(commands, yScale, stacked) {
return commands.map((pathCommands, index, all) => {
const closingPath = stacked ? closePathViaPreviousSeries(all, index, yScale) : closePathViaOrigin(pathCommands, yScale);
const closingPathCommands = [...closingPath].reverse().map(([_, x, y]) => ["lineTo", x, y]);
const first = pathCommands[0];
const last = (0, import_ag_grid_community280._last)(closingPathCommands);
if (first[1] !== last[1] || first[2] !== last[2]) {
closingPathCommands.push(["lineTo", first[1], first[2]]);
}
return [...pathCommands, ...closingPathCommands];
});
}
function closePathViaPreviousSeries(all, index, yScale) {
if (index === 0) {
return closePathViaOrigin(all[index], yScale);
}
return [...all[index - 1]];
}
function closePathViaOrigin(pathCommands, yScale) {
return pathCommands.map(([c, x]) => [c, x, yScale.convert(0)]);
}
function commandsToPath(_Scene, commands) {
const path = createPath(_Scene, commands);
path.fill = void 0;
path.lineCap = "round";
path.strokeWidth = 3;
return path;
}
function createShapePaths({ _Scene }, root, shapes, size, padding) {
const { xScale, yScale } = prepareXYScales(_Scene, shapes, size, padding);
const openPathsCommands = shapes.map((shape) => createXYPathCommands(shape, xScale, yScale));
const shapesCommands = openPathsCommands.map((path) => closePath(path));
const shapePaths = shapesCommands.map((shapeCommands) => commandsToPath(_Scene, shapeCommands));
const paths = shapePaths.reduce((acc, curr) => acc.concat(curr), []);
const pathsGroup = new _Scene.Group();
pathsGroup.setClipRect(new _Scene.BBox(padding, padding, size - padding * 2, size - padding * 2));
pathsGroup.append(paths);
root.append(pathsGroup);
return paths;
}
function createLinePaths({ _Scene }, root, data, size, padding) {
const { xScale, yScale } = prepareLinearScene(_Scene, data, size, padding);
const pathCommands = createXPathCommands(data, xScale, yScale);
const paths = pathCommands.map((commands) => commandsToPath(_Scene, commands));
const pathsGroup = new _Scene.Group();
pathsGroup.setClipRect(new _Scene.BBox(padding, padding, size - padding * 2, size - padding * 2));
pathsGroup.append(paths);
root.append(pathsGroup);
return paths;
}
function createAreaPaths(_Scene, root, data, size, padding, stacked = false) {
const { xScale, yScale } = prepareLinearScene(_Scene, data, size, padding);
const pathCommands = createAreaPathCommands(createXPathCommands(data, xScale, yScale), yScale, stacked);
const areasGroup = new _Scene.Group();
areasGroup.setClipRect(new _Scene.BBox(padding, padding, size - padding * 2, size - padding * 2));
const paths = pathCommands.map((commands) => createPath(_Scene, commands));
areasGroup.append(paths);
root.append(areasGroup);
return paths;
}
function stackData(data) {
return data.map(
(stack, sindex, array) => stack.map((_y, i) => array.slice(0, sindex + 1).reduce((p, c) => p + c[i], 0))
);
}
function normalizeStackData(data) {
const colSum = data.map((_, index) => data.reduce((acc, cur) => Math.max(acc, cur[index]), 0));
return data.map((stack) => stack.map((y, index) => y / colSum[index] * 19));
}
function createPolarPaths(agChartsExports, root, data, size, radius, innerRadius, markerSize = 0) {
const { _Scene } = agChartsExports;
const angleScale = new _Scene.LinearScale();
angleScale.domain = [0, 7];
angleScale.range = [-Math.PI, Math.PI].map((angle) => angle + Math.PI / 2);
const radiusScale = new _Scene.LinearScale();
radiusScale.domain = [0, 10];
radiusScale.range = [radius, innerRadius];
const markers2 = [];
const center = size / 2;
const paths = data.map((series) => {
const path = new _Scene.Path();
path.strokeWidth = 1;
path.strokeOpacity = 0.5;
path.lineCap = "round";
path.fill = void 0;
path.fillOpacity = 0.8;
series.forEach((datum, i) => {
const angle = angleScale.convert(i);
const r = radius + innerRadius - radiusScale.convert(datum);
const x = r * Math.cos(angle) + center;
const y = r * Math.sin(angle) + center;
path.path[i > 0 ? "lineTo" : "moveTo"](x, y);
if (markerSize > 0) {
const marker = new _Scene.Marker({ shape: "circle" });
marker.x = x;
marker.y = y;
marker.size = markerSize;
markers2.push(marker);
}
});
path.path.closePath();
return path;
});
const group = new _Scene.Group();
group.append([...paths, ...markers2]);
root.append(group);
return { paths, markers: markers2 };
}
function accumulateData(data) {
let [min, max] = [Infinity, -Infinity];
const processedData = data.reduce((acc, curr, currIndex) => {
const previous = currIndex > 0 ? acc[currIndex - 1] : void 0;
acc[currIndex] ?? (acc[currIndex] = []);
const current = acc[currIndex];
curr.forEach((datum, datumIndex) => {
if (previous) {
datum += previous[datumIndex];
}
current[datumIndex] = datum;
if (current[datumIndex] < min) {
min = current[datumIndex];
}
if (current[datumIndex] > max) {
max = current[datumIndex];
}
});
return acc;
}, []);
return { processedData, min, max };
}
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/funnel/miniFunnel.ts
var FUNNEL_SHAPES = [
[
[13, 16],
[13, 12],
[3, 12],
[3, 16]
],
[
[12, 11],
[12, 7],
[4, 7],
[4, 11]
],
[
[10.125, 6],
[10.125, 1.5],
[5.875, 1.5],
[5.875, 6]
]
];
var MiniFunnelClass = class extends MiniChart {
constructor(container, agChartsExports, fills, strokes, _isCustomTheme, tooltipName = "funnelTooltip", data = FUNNEL_SHAPES) {
super(container, agChartsExports, tooltipName);
this.shapes = createShapePaths(agChartsExports, this.root, data, this.size, this.padding);
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.shapes.forEach((bar) => {
bar.fill = fills[0];
bar.stroke = strokes[0];
bar.strokeWidth = 0;
});
}
};
var MiniFunnel = {
chartType: "funnel",
miniChart: MiniFunnelClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/funnel/miniConeFunnel.ts
var CONE_FUNNEL_SHAPES = [
[
[13, 16],
[10.75, 11.5],
[5.25, 11.5],
[3, 16]
],
[
[10.75, 11.5],
[8.875, 6],
[7.125, 6],
[5.25, 11.5]
],
[
[8.875, 6],
[8.875, 1.5],
[7.125, 1.5],
[7.125, 6]
]
];
var MiniConeFunnelClass = class extends MiniFunnelClass {
constructor(container, agChartsExports, fills, strokes, _isCustomTheme, tooltipName = "coneFunnelTooltip") {
super(container, agChartsExports, fills, strokes, _isCustomTheme, tooltipName, CONE_FUNNEL_SHAPES);
}
updateColors(fills, strokes) {
this.shapes.forEach((bar, i) => {
bar.fill = fills[0];
bar.fillOpacity = 1 - i * 0.2;
bar.stroke = strokes[0];
bar.strokeWidth = 0;
});
}
};
var MiniConeFunnel = {
chartType: "coneFunnel",
miniChart: MiniConeFunnelClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/funnel/miniPyramid.ts
var PYRAMID_SHAPES = [
[
[8, 16],
[10, 12],
[6, 12]
],
[
[10.5, 11],
[12.5, 7],
[3.5, 7],
[5.5, 11]
],
[
[13, 6],
[15.5, 1.5],
[0.5, 1.5],
[3, 6]
]
];
var MiniPyramidClass = class extends MiniFunnelClass {
constructor(container, agChartsExports, fills, strokes, _isCustomTheme, tooltipName = "pyramidTooltip") {
super(container, agChartsExports, fills, strokes, _isCustomTheme, tooltipName, PYRAMID_SHAPES);
}
updateColors(fills, strokes) {
this.shapes.forEach((bar, i) => {
bar.fill = fills[i];
bar.stroke = strokes[i];
bar.strokeWidth = 0;
});
}
};
var MiniPyramid = {
chartType: "pyramid",
miniChart: MiniPyramidClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/miniChartWithAxes.ts
var MiniChartWithAxes = class extends MiniChart {
constructor(container, agChartsExports, tooltipName) {
super(container, agChartsExports, tooltipName);
this.stroke = "gray";
this.axisOvershoot = 3;
}
postConstruct() {
const { _Scene } = this.agChartsExports;
const size = this.size;
const padding = this.padding;
const leftAxis = new _Scene.Line();
leftAxis.x1 = padding;
leftAxis.y1 = padding;
leftAxis.x2 = padding;
leftAxis.y2 = size - padding + this.axisOvershoot;
leftAxis.stroke = this.stroke;
const bottomAxis = new _Scene.Line();
bottomAxis.x1 = padding - this.axisOvershoot + 1;
bottomAxis.y1 = size - padding;
bottomAxis.x2 = size - padding + 1;
bottomAxis.y2 = size - padding;
bottomAxis.stroke = this.stroke;
const root = this.root;
root.append(leftAxis);
root.append(bottomAxis);
super.postConstruct();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/column/miniColumn.ts
var MiniColumnClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "groupedColumnTooltip");
this.columnData = [2, 3, 4];
const { root, columnData, size, padding } = this;
this.columns = createColumnRects({
stacked: false,
root,
data: columnData,
size,
padding,
xScaleDomain: [0, 1, 2],
yScaleDomain: [0, 4],
xScalePadding: 0.3,
agChartsExports
});
root.append(this.columns);
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.columns.forEach((column, i) => {
column.fill = fills[i];
column.stroke = strokes[i];
});
}
};
var MiniColumn = {
chartType: "groupedColumn",
miniChart: MiniColumnClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/column/miniStackedColumn.ts
var import_ag_grid_community281 = require("ag-grid-community");
var miniStackedColumnData = [
[8, 12, 16],
[6, 9, 12],
[2, 3, 4]
];
var MiniStackedColumnClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes, _isCustomTheme, data = miniStackedColumnData, yScaleDomain = [0, 16], tooltipName = "stackedColumnTooltip") {
super(container, agChartsExports, tooltipName);
const { root, size, padding } = this;
this.stackedColumns = createColumnRects({
stacked: true,
root,
data,
size,
padding,
xScaleDomain: [0, 1, 2],
yScaleDomain,
xScalePadding: 0.3,
agChartsExports
});
root.append((0, import_ag_grid_community281._flatten)(this.stackedColumns));
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.stackedColumns.forEach(
(series, i) => series.forEach((column) => {
column.fill = fills[i];
column.stroke = strokes[i];
})
);
}
};
var MiniStackedColumn = {
chartType: "stackedColumn",
miniChart: MiniStackedColumnClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/column/miniNormalizedColumn.ts
var miniNormalizedColumnData = [
[10, 10, 10],
[6, 7, 8],
[2, 4, 6]
];
var MiniNormalizedColumnClass = class extends MiniStackedColumnClass {
constructor(container, agChartsExports, fills, strokes, isCustomTheme) {
super(
container,
agChartsExports,
fills,
strokes,
isCustomTheme,
miniNormalizedColumnData,
[0, 10],
"normalizedColumnTooltip"
);
}
};
var MiniNormalizedColumn = {
chartType: "normalizedColumn",
miniChart: MiniNormalizedColumnClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/bar/miniBar.ts
var MiniBarClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "groupedBarTooltip");
const { _Scene } = agChartsExports;
const padding = this.padding;
const size = this.size;
const data = [2, 3, 4];
const yScale = new _Scene.CategoryScale();
yScale.domain = [0, 1, 2];
yScale.range = [padding, size - padding];
yScale.paddingInner = 0.3;
yScale.paddingOuter = 0.3;
const xScale = new _Scene.LinearScale();
xScale.domain = [0, 4];
xScale.range = [size - padding, padding];
const bottom = xScale.convert(0);
const height = yScale.bandwidth;
this.bars = data.map((datum, i) => {
const rect = new _Scene.Rect();
rect.x = padding;
rect.y = yScale.convert(i);
rect.width = bottom - xScale.convert(datum);
rect.height = height;
rect.strokeWidth = 0;
rect.crisp = true;
return rect;
});
this.updateColors(fills, strokes);
this.root.append(this.bars);
}
updateColors(fills, strokes) {
this.bars.forEach((bar, i) => {
bar.fill = fills[i];
bar.stroke = strokes[i];
});
}
};
var MiniBar = {
chartType: "groupedBar",
miniChart: MiniBarClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/bar/miniStackedBar.ts
var import_ag_grid_community282 = require("ag-grid-community");
var miniStackedBarData = [
[8, 12, 16],
[6, 9, 12],
[2, 3, 4]
];
var MiniStackedBarClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes, _isCustomTheme, data = miniStackedBarData, xScaleDomain = [0, 16], tooltipName = "stackedBarTooltip") {
super(container, agChartsExports, tooltipName);
const { _Scene } = agChartsExports;
const size = this.size;
const padding = this.padding;
const yScale = new _Scene.CategoryScale();
yScale.domain = [0, 1, 2];
yScale.range = [padding, size - padding];
yScale.paddingInner = 0.3;
yScale.paddingOuter = 0.3;
const xScale = new _Scene.LinearScale();
xScale.domain = xScaleDomain;
xScale.range = [size - padding, padding];
const bottom = xScale.convert(0);
const height = yScale.bandwidth;
this.bars = data.map(
(series) => series.map((datum, i) => {
const rect = new _Scene.Rect();
rect.x = padding;
rect.y = yScale.convert(i);
rect.width = bottom - xScale.convert(datum);
rect.height = height;
rect.strokeWidth = 0;
rect.crisp = true;
return rect;
})
);
this.updateColors(fills, strokes);
this.root.append((0, import_ag_grid_community282._flatten)(this.bars));
}
updateColors(fills, strokes) {
this.bars.forEach(
(series, i) => series.forEach((bar) => {
bar.fill = fills[i];
bar.stroke = strokes[i];
})
);
}
};
var MiniStackedBar = {
chartType: "stackedBar",
miniChart: MiniStackedBarClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/bar/miniNormalizedBar.ts
var miniNormalizedBarData = [
[10, 10, 10],
[6, 7, 8],
[2, 4, 6]
];
var MiniNormalizedBarClass = class extends MiniStackedBarClass {
constructor(container, agChartsExports, fills, strokes, isCustomTheme) {
super(
container,
agChartsExports,
fills,
strokes,
isCustomTheme,
miniNormalizedBarData,
[0, 10],
"normalizedBarTooltip"
);
}
};
var MiniNormalizedBar = {
chartType: "normalizedBar",
miniChart: MiniNormalizedBarClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/pie/miniDonut.ts
var MiniDonutClass = class extends MiniChart {
constructor(container, agChartsExports, fills, strokes, _isCustomTheme, centerRadiusScaler = 0.6, tooltipName = "donutTooltip") {
super(container, agChartsExports, tooltipName);
const {
size,
padding,
agChartsExports: { _Scene }
} = this;
const radius = (size - padding * 2) / 2;
const center = radius + padding;
const toRadians = _Scene.toRadians;
const angles = [
[toRadians(-90), toRadians(30)],
[toRadians(30), toRadians(120)],
[toRadians(120), toRadians(180)],
[toRadians(180), toRadians(210)],
[toRadians(210), toRadians(240)],
[toRadians(240), toRadians(270)]
];
this.sectors = angles.map(([startAngle, endAngle]) => {
const sector = new _Scene.Sector();
sector.centerX = center;
sector.centerY = center;
sector.innerRadius = radius * centerRadiusScaler;
sector.outerRadius = radius;
sector.startAngle = startAngle;
sector.endAngle = endAngle;
sector.stroke = void 0;
sector.strokeWidth = 0;
sector.inset = 0.75;
return sector;
});
this.updateColors(fills, strokes);
this.root.append(this.sectors);
}
updateColors(fills, strokes) {
this.sectors.forEach((sector, i) => {
sector.fill = fills[i % fills.length];
sector.stroke = strokes[i % strokes.length];
});
}
};
var MiniDonut = {
chartType: "donut",
miniChart: MiniDonutClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/pie/miniPie.ts
var MiniPieClass = class extends MiniDonutClass {
constructor(container, agChartsExports, fills, strokes, isCustomTheme) {
super(container, agChartsExports, fills, strokes, isCustomTheme, 0, "pieTooltip");
}
};
var MiniPie = {
chartType: "pie",
miniChart: MiniPieClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/line/miniLine.ts
var miniLineData = [
[1, 3, 5],
[2, 6, 4],
[5, 3, 1]
];
var MiniLineClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes, _isCustomTheme, data = miniLineData, tooltipName = "lineTooltip") {
super(container, agChartsExports, tooltipName);
const { size, padding, root } = this;
this.lines = createLinePaths(agChartsExports, root, data, size, padding);
this.updateColors(fills, strokes);
}
updateColors(fills, _strokes) {
this.lines.forEach((line, i) => {
line.stroke = fills[i];
});
}
};
var MiniLine = {
chartType: "line",
miniChart: MiniLineClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/line/miniStackedLine.ts
var miniStackedLineData = stackData(miniLineData);
var MiniStackedLineClass = class extends MiniLineClass {
constructor(container, agChartsExports, fills, strokes, _isCustomTheme, data = miniStackedLineData, tooltipName = "stackedLineTooltip") {
super(container, agChartsExports, fills, strokes, _isCustomTheme, data, tooltipName);
}
};
var MiniStackedLine = {
chartType: "stackedLine",
miniChart: MiniStackedLineClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/line/miniNormalizedLine.ts
var miniNormalizedLineData = normalizeStackData(miniStackedLineData);
var MiniNormalizedLineClass = class extends MiniLineClass {
constructor(container, agChartsExports, fills, strokes, isCustomTheme, data = miniNormalizedLineData, tooltipName = "normalizedLineTooltip") {
super(container, agChartsExports, fills, strokes, isCustomTheme, data, tooltipName);
}
};
var MiniNormalizedLine = {
chartType: "normalizedLine",
miniChart: MiniNormalizedLineClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/scatter/miniScatter.ts
var MiniScatterClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "scatterTooltip");
const {
size,
padding,
agChartsExports: { _Scene }
} = this;
const data = [
[
[0.3, 3],
[1.1, 0.9],
[2, 0.4],
[3.4, 2.4]
],
[
[0, 0.3],
[1, 2],
[2.4, 1.4],
[3, 0]
]
];
const xScale = new _Scene.LinearScale();
xScale.domain = [-0.5, 4];
xScale.range = [padding * 2, size - padding];
const yScale = new _Scene.LinearScale();
yScale.domain = [-0.5, 3.5];
yScale.range = [size - padding, padding];
const points = [];
data.forEach((series) => {
series.forEach(([x, y]) => {
const arc = new _Scene.Arc();
arc.strokeWidth = 0;
arc.centerX = xScale.convert(x);
arc.centerY = yScale.convert(y);
arc.radius = 2.5;
points.push(arc);
});
});
this.points = points;
this.updateColors(fills, strokes);
const pointsGroup = new _Scene.Group();
pointsGroup.setClipRect(new _Scene.BBox(padding, padding, size - padding * 2, size - padding * 2));
pointsGroup.append(this.points);
this.root.append(pointsGroup);
}
updateColors(fills, strokes) {
this.points.forEach((line, i) => {
line.stroke = strokes[i % strokes.length];
line.fill = fills[i % fills.length];
});
}
};
var MiniScatter = {
chartType: "scatter",
miniChart: MiniScatterClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/scatter/miniBubble.ts
var MiniBubbleClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "bubbleTooltip");
const {
size,
padding,
agChartsExports: { _Scene }
} = this;
const data = [
[
[0.1, 0.3, 5],
[0.5, 0.4, 7],
[0.2, 0.8, 7]
],
[
[0.8, 0.7, 5],
[0.7, 0.3, 9]
]
];
const xScale = new _Scene.LinearScale();
xScale.domain = [0, 1];
xScale.range = [padding * 2, size - padding];
const yScale = new _Scene.LinearScale();
yScale.domain = [0, 1];
yScale.range = [size - padding, padding];
const points = [];
data.forEach((series) => {
series.forEach(([x, y, radius]) => {
const arc = new _Scene.Arc();
arc.strokeWidth = 0;
arc.centerX = xScale.convert(x);
arc.centerY = yScale.convert(y);
arc.radius = radius;
arc.fillOpacity = 0.7;
points.push(arc);
});
});
this.points = points;
this.updateColors(fills, strokes);
const pointsGroup = new _Scene.Group();
pointsGroup.setClipRect(new _Scene.BBox(padding, padding, size - padding * 2, size - padding * 2));
pointsGroup.append(this.points);
this.root.append(pointsGroup);
}
updateColors(fills, strokes) {
this.points.forEach((line, i) => {
line.stroke = strokes[i % strokes.length];
line.fill = fills[i % fills.length];
});
}
};
var MiniBubble = {
chartType: "bubble",
miniChart: MiniBubbleClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/area/miniArea.ts
var miniAreaData = miniLineData;
var MiniAreaClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes, _isCustomTheme, data = miniAreaData, tooltipName = "groupedAreaTooltip", stacked = false) {
super(container, agChartsExports, tooltipName);
this.areas = createAreaPaths(agChartsExports._Scene, this.root, data, this.size, this.padding, stacked);
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.areas.forEach((area, i) => {
area.fill = fills[i];
area.stroke = strokes[i];
area.strokeWidth = 1;
area.strokeOpacity = 0.75;
area.fillOpacity = 0.7;
});
}
};
var MiniArea = {
chartType: "area",
miniChart: MiniAreaClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/area/miniStackedArea.ts
var miniStackedAreaData = stackData(miniAreaData);
var MiniStackedAreaClass = class extends MiniAreaClass {
constructor(container, agChartsExports, fills, strokes, _isCustomTheme, data = miniStackedAreaData, tooltipName = "stackedAreaTooltip") {
super(container, agChartsExports, fills, strokes, _isCustomTheme, data, tooltipName, true);
}
updateColors(fills, strokes) {
this.areas.forEach((area, i) => {
area.fill = fills[i];
area.stroke = strokes[i];
});
}
};
var MiniStackedArea = {
chartType: "stackedArea",
miniChart: MiniStackedAreaClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/area/miniNormalizedArea.ts
var miniNormalizedAreaData = normalizeStackData(miniStackedAreaData);
var MiniNormalizedAreaClass = class extends MiniStackedAreaClass {
constructor(container, agChartsExports, fills, strokes, isCustomTheme, data = miniNormalizedAreaData, tooltipName = "normalizedAreaTooltip") {
super(container, agChartsExports, fills, strokes, isCustomTheme, data, tooltipName);
}
};
var MiniNormalizedArea = {
chartType: "normalizedArea",
miniChart: MiniNormalizedAreaClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/histogram/miniHistogram.ts
var MiniHistogramClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "histogramTooltip");
const {
padding,
size,
agChartsExports: { _Scene }
} = this;
const data = [2, 5, 11, 13, 10, 6, 1];
const xScale = new _Scene.LinearScale();
xScale.domain = [0, data.length];
xScale.range = [padding, size - padding];
const yScale = new _Scene.LinearScale();
yScale.domain = [0, data.reduce((a, b) => Math.max(a, b), 0)];
yScale.range = [size - padding, padding];
const bottom = yScale.convert(0);
this.bars = data.map((datum, i) => {
const top = yScale.convert(datum);
const left = xScale.convert(i);
const right = xScale.convert(i + 1);
const rect = new _Scene.Rect();
rect.x = left;
rect.y = top;
rect.width = right - left;
rect.height = bottom - top;
rect.strokeWidth = 1;
rect.strokeOpacity = 0.75;
rect.crisp = true;
return rect;
});
this.updateColors(fills, strokes);
this.root.append(this.bars);
}
updateColors([fill], [stroke]) {
this.bars.forEach((bar) => {
bar.fill = fill;
bar.stroke = stroke;
});
}
};
var MiniHistogram = {
chartType: "histogram",
miniChart: MiniHistogramClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/miniChartWithPolarAxes.ts
var MiniChartWithPolarAxes = class extends MiniChart {
constructor(container, agChartsExports, tooltipName) {
super(container, agChartsExports, tooltipName);
this.stroke = "gray";
this.showRadiusAxisLine = true;
this.showAngleAxisLines = true;
}
postConstruct() {
const { _Scene } = this.agChartsExports;
const size = this.size;
const padding = this.padding;
const combinedPadding = padding * 2;
const axisLineRadius = (size - combinedPadding) / 2;
const gridRadii = this.showAngleAxisLines ? [axisLineRadius, axisLineRadius * 0.8, axisLineRadius * 0.6, axisLineRadius * 0.4] : [];
const radiusAxisLine = new _Scene.Line();
radiusAxisLine.x1 = size / 2;
radiusAxisLine.y1 = padding;
radiusAxisLine.x2 = size / 2;
radiusAxisLine.y2 = size - padding - axisLineRadius - gridRadii[gridRadii.length - 1];
radiusAxisLine.stroke = this.stroke;
radiusAxisLine.strokeOpacity = 0.5;
radiusAxisLine.fill = void 0;
radiusAxisLine.visible = this.showRadiusAxisLine;
const x = padding + axisLineRadius;
this.gridLines = gridRadii.map((radius, index) => {
const gridLine = new _Scene.Path();
gridLine.path.arc(x, x, radius, 0, 2 * Math.PI);
gridLine.strokeWidth = 1;
gridLine.stroke = this.stroke;
gridLine.strokeOpacity = index === 0 ? 0.5 : 0.2;
gridLine.fill = void 0;
return gridLine;
});
const root = this.root;
root.append(radiusAxisLine);
if (this.gridLines.length > 0)
root.append(this.gridLines);
super.postConstruct();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/polar/miniRadialColumn.ts
var MiniRadialColumnClass = class extends MiniChartWithPolarAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "radialColumnTooltip");
this.data = [
[6, 8, 10, 2, 6, 5],
[4, 4, 3, 6, 4, 4],
[5, 4, 2, 9, 8, 9]
];
this.showRadiusAxisLine = false;
const {
padding,
size,
data,
agChartsExports: { _Scene }
} = this;
const radius = (size - padding * 2) / 2;
const innerRadiusRatio = 0.4;
const axisInnerRadius = radius * innerRadiusRatio;
const angleScale = new _Scene.CategoryScale();
angleScale.domain = data[0].map((_, index) => index);
angleScale.range = [0, 2 * Math.PI];
angleScale.paddingInner = 0;
angleScale.paddingOuter = 0;
const bandwidth = angleScale.bandwidth * 0.7;
const { processedData, max } = accumulateData(data);
const radiusScale = new _Scene.LinearScale();
radiusScale.domain = [0, max];
radiusScale.range = [axisInnerRadius, radius];
const center = this.size / 2;
this.series = processedData.map((series, seriesIndex) => {
const firstSeries = seriesIndex === 0;
const previousSeries = firstSeries ? void 0 : processedData[seriesIndex - 1];
const seriesGroup = new _Scene.TranslatableGroup({ zIndex: 1e6 });
const seriesColumns = series.map((datum, i) => {
const previousDatum = previousSeries?.[i];
const outerRadius = radiusScale.convert(datum);
const innerRadius = radiusScale.convert(previousDatum ?? 0);
const startAngle = angleScale.convert(i);
const endAngle = startAngle + bandwidth;
const columnWidth = _Scene.getRadialColumnWidth(startAngle, endAngle, radius, 0.5, 0.5);
const column = new _Scene.RadialColumnShape();
column.columnWidth = columnWidth;
column.innerRadius = innerRadius;
column.outerRadius = outerRadius;
column.startAngle = startAngle;
column.endAngle = endAngle;
column.isBeveled = true;
column.axisInnerRadius = axisInnerRadius;
column.axisOuterRadius = radius;
column.stroke = void 0;
column.strokeWidth = 0;
return column;
});
seriesGroup.append(seriesColumns);
seriesGroup.translationX = center;
seriesGroup.translationY = center;
return seriesGroup;
});
this.root.append(this.series);
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.series.forEach((group, i) => {
for (const sector of group.children()) {
sector.fill = fills[i % fills.length];
sector.stroke = strokes[i % strokes.length];
}
});
}
};
var MiniRadialColumn = {
chartType: "radialColumn",
miniChart: MiniRadialColumnClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/polar/miniRadialBar.ts
var MiniRadialBarClass = class extends MiniChartWithPolarAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "radialBarTooltip");
this.data = [
[6, 8, 10],
[4, 4, 3],
[5, 4, 2]
];
this.showRadiusAxisLine = false;
const {
size,
padding,
data,
agChartsExports: { _Scene }
} = this;
const radius = (size - padding) / 2;
const innerRadiusRatio = 0.4;
const innerRadius = radius * innerRadiusRatio;
const radiusScale = new _Scene.CategoryScale();
radiusScale.domain = data[0].map((_, index) => index);
radiusScale.range = [innerRadius, radius];
radiusScale.paddingInner = 0.5;
radiusScale.paddingOuter = 0;
const bandwidth = radiusScale.bandwidth;
const { processedData, max } = accumulateData(data);
const angleScale = new _Scene.LinearScale();
angleScale.domain = [0, Math.ceil(max * 1.5)];
const start = 3 / 2 * Math.PI;
const end = start + 2 * Math.PI;
angleScale.range = [start, end];
const center = size / 2;
this.series = processedData.map((series, index) => {
const previousSeries = index < 0 ? void 0 : processedData[index - 1];
const seriesGroup = new _Scene.Group({ zIndex: 1e6 });
const seriesSectors = series.map((datum, i) => {
const previousDatum = previousSeries?.[i] ?? 0;
const outerRadius = radiusScale.convert(i);
const innerRadius2 = outerRadius - bandwidth;
const startAngle = angleScale.convert(previousDatum);
const endAngle = angleScale.convert(datum);
const sector = new _Scene.Sector();
sector.centerX = center;
sector.centerY = center;
sector.innerRadius = innerRadius2;
sector.outerRadius = outerRadius;
sector.startAngle = startAngle;
sector.endAngle = endAngle;
sector.stroke = void 0;
sector.strokeWidth = 0;
return sector;
});
seriesGroup.append(seriesSectors);
return seriesGroup;
});
this.root.append(this.series);
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.series.forEach((group, i) => {
for (const sector of group.children()) {
sector.fill = fills[i % fills.length];
sector.stroke = strokes[i % strokes.length];
}
});
}
};
var MiniRadialBar = {
chartType: "radialBar",
miniChart: MiniRadialBarClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/polar/miniRadarLine.ts
var MiniRadarLineClass = class extends MiniChartWithPolarAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "radarLineTooltip");
this.markerSize = 4;
this.data = [
[8, 7, 8, 7, 8, 8, 7, 8],
[6, 8, 5, 10, 6, 7, 4, 6],
[0, 3, 3, 5, 4, 4, 2, 0]
];
this.showRadiusAxisLine = false;
const { size, padding, root, data } = this;
const radius = (size - padding * 2) / 2;
const innerRadius = 0;
const { paths, markers: markers2 } = createPolarPaths(
agChartsExports,
root,
data,
size,
radius,
innerRadius,
this.markerSize
);
this.lines = paths;
this.markers = markers2;
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.lines.forEach((line, i) => {
const n = this.data[i].length;
line.stroke = fills[i];
const startIdx = i * n;
const endIdx = startIdx + n;
const markers2 = this.markers.slice(startIdx, endIdx);
markers2.forEach((marker) => {
marker.stroke = strokes[i];
marker.fill = fills[i];
});
});
}
};
var MiniRadarLine = {
chartType: "radarLine",
miniChart: MiniRadarLineClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/polar/miniRadarArea.ts
var MiniRadarAreaClass = class extends MiniChartWithPolarAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "radarAreaTooltip");
this.data = [
[8, 10, 5, 7, 4, 1, 5, 8],
[1, 1, 2, 7, 7, 8, 10, 1],
[4, 5, 9, 9, 4, 2, 3, 4]
];
const { size, padding, root, data } = this;
this.showRadiusAxisLine = false;
const radius = (size - padding * 2) / 2;
const innerRadius = radius - size * 0.3;
this.areas = createPolarPaths(agChartsExports, root, data, size, radius, innerRadius).paths;
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.areas.forEach((area, i) => {
area.fill = fills[i];
area.stroke = strokes[i];
});
}
};
var MiniRadarArea = {
chartType: "radarArea",
miniChart: MiniRadarAreaClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/polar/miniNightingale.ts
var MiniNightingaleClass = class extends MiniChartWithPolarAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "nightingaleTooltip");
this.data = [
[6, 10, 9, 8, 7, 8],
[4, 6, 5, 4, 5, 5],
[3, 5, 4, 3, 4, 7]
];
this.showRadiusAxisLine = false;
const {
size,
padding,
data,
agChartsExports: { _Scene }
} = this;
const radius = (size - padding * 2) / 2;
const angleScale = new _Scene.CategoryScale();
angleScale.domain = data[0].map((_, index) => index);
angleScale.range = [-Math.PI, Math.PI];
angleScale.paddingInner = 0;
angleScale.paddingOuter = 0;
const bandwidth = angleScale.bandwidth * 0.7;
const { processedData, max } = accumulateData(data);
const radiusScale = new _Scene.LinearScale();
radiusScale.domain = [0, max];
radiusScale.range = [0, radius];
const center = size / 2;
this.series = processedData.map((series, index) => {
const previousSeries = index < 0 ? void 0 : processedData[index - 1];
const seriesGroup = new _Scene.Group({ zIndex: 1e6 });
const seriesSectors = series.map((datum, i) => {
const previousDatum = previousSeries?.[i];
const outerRadius = radiusScale.convert(datum);
const innerRadius = radiusScale.convert(previousDatum ?? 0);
const startAngle = angleScale.convert(i);
const endAngle = startAngle + bandwidth;
const sector = new _Scene.Sector();
sector.centerX = center;
sector.centerY = center;
sector.innerRadius = innerRadius;
sector.outerRadius = outerRadius;
sector.startAngle = startAngle;
sector.endAngle = endAngle;
sector.stroke = void 0;
sector.strokeWidth = 0;
return sector;
});
seriesGroup.append(seriesSectors);
return seriesGroup;
});
this.root.append(this.series);
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.series.forEach((group, i) => {
for (const sector of group.children()) {
sector.fill = fills[i % fills.length];
sector.stroke = strokes[i % strokes.length];
}
});
}
};
var MiniNightingale = {
chartType: "nightingale",
miniChart: MiniNightingaleClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/statistical/miniRangeBar.ts
var MiniRangeBarClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "rangeBarTooltip");
const data = [3, 3.5, 3];
this.bars = this.createRangeBar(this.root, data, this.size, this.padding, "vertical");
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.bars.forEach((bar, i) => {
bar.fill = fills[i];
bar.stroke = strokes[i];
});
}
createRangeBar(root, data, size, padding, direction) {
const barAlongX = direction === "horizontal";
const scalePadding = 2 * padding;
const { _Scene } = this.agChartsExports;
const xScale = new _Scene.CategoryScale();
xScale.domain = data.map((_, index) => index);
xScale.range = [padding, size - padding];
xScale.paddingInner = 0.3;
xScale.paddingOuter = 0.3;
const lowRatio = 0.7;
const highRatio = 1.3;
const yScale = new _Scene.LinearScale();
yScale.domain = [
data.reduce((a, b) => Math.min(a, b), Infinity) * lowRatio,
data.reduce((a, b) => Math.max(a, b), 0) * highRatio
];
yScale.range = [scalePadding, size - scalePadding];
const width = xScale.bandwidth;
const bars = data.map((datum, i) => {
const [low, high] = [datum * lowRatio, datum * highRatio];
const x = xScale.convert(i);
const y = yScale.convert(low);
const height = yScale.convert(high) - y;
const rect = new _Scene.Rect();
rect.x = barAlongX ? y : x;
rect.y = barAlongX ? x : y;
rect.width = barAlongX ? height : width;
rect.height = barAlongX ? width : height;
rect.strokeWidth = 0;
rect.crisp = true;
return rect;
});
root.append(bars);
return bars;
}
};
var MiniRangeBar = {
chartType: "rangeBar",
miniChart: MiniRangeBarClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/statistical/miniRangeArea.ts
var MiniRangeAreaClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "rangeAreaTooltip");
const period = 4;
const dataSeriesMidpoints = [
zigzag({ offset: 0.375 * period, length: period, pattern: { low: 3, high: 5, period } }),
zigzag({ offset: 0.375 * period, length: period, pattern: { low: 2.25, high: 4.25, period } }),
zigzag({ offset: 0.75 * period, length: period, pattern: { low: 2.5, high: 4.5, period } })
];
const dataSeriesWidth = 1.75;
const data = dataSeriesMidpoints.map(
(series) => series.map(([x, y]) => ({
x,
low: y - 0.5 * dataSeriesWidth,
high: y + 0.5 * dataSeriesWidth
}))
);
const { lines, areas } = this.createRangeArea(this.root, data, this.size, this.padding);
this.lines = lines;
this.areas = areas;
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
fills = swapArrayItems(fills, 1, 2);
strokes = swapArrayItems(strokes, 1, 2);
this.lines.forEach(([highLine, lowLine], i) => {
highLine.fill = void 0;
highLine.stroke = strokes[i];
lowLine.fill = void 0;
lowLine.stroke = strokes[i];
});
this.areas.forEach((area, i) => {
area.fill = fills[i];
});
}
createRangeArea(root, data, size, padding) {
const xMin = data.reduce((acc, series) => series.reduce((acc2, { x }) => Math.min(acc2, x), acc), Infinity);
const xMax = data.reduce((acc, series) => series.reduce((acc2, { x }) => Math.max(acc2, x), acc), -Infinity);
const yMin = data.reduce((acc, series) => series.reduce((acc2, { low }) => Math.min(acc2, low), acc), Infinity);
const yMax = data.reduce(
(acc, series) => series.reduce((acc2, { high }) => Math.max(acc2, high), acc),
-Infinity
);
const { _Scene } = this.agChartsExports;
const xScale = new _Scene.LinearScale();
xScale.domain = [xMin, xMax];
xScale.range = [padding, size - padding];
const scalePadding = 2 * padding;
const yScale = new _Scene.LinearScale();
yScale.domain = [yMin, yMax];
yScale.range = [size - scalePadding, scalePadding];
const lines = [];
const areas = [];
const lowPoints = data.map((series) => {
const highLine = new _Scene.Path();
const lowLine = new _Scene.Path();
const area = new _Scene.Path();
lines.push([highLine, lowLine]);
areas.push(area);
highLine.strokeWidth = 0;
lowLine.strokeWidth = 0;
area.strokeWidth = 0;
area.fillOpacity = 0.8;
highLine.path.clear();
lowLine.path.clear();
area.path.clear();
return series.map((datum, datumIndex) => {
const { x, low, high } = datum;
const scaledX = xScale.convert(x);
const yLow = yScale.convert(low);
const yHigh = yScale.convert(high);
const command = datumIndex > 0 ? "lineTo" : "moveTo";
highLine.path[command](scaledX, yHigh);
lowLine.path[command](scaledX, yLow);
area.path[command](scaledX, yHigh);
return [scaledX, yLow];
});
});
lowPoints.forEach((seriesLowPoints, seriesIndex) => {
const n = seriesLowPoints.length - 1;
const area = areas[seriesIndex];
for (let datumIndex = n; datumIndex >= 0; datumIndex--) {
const [x, y] = seriesLowPoints[datumIndex];
area.path["lineTo"](x, y);
}
});
root.append(areas.concat(...lines));
return { lines, areas };
}
};
function zigzag(options) {
const { offset, length, pattern } = options;
const points = getZigzagInflectionPoints(offset, length, pattern);
const xMin = 0;
const xMax = length;
if (points.length === 0 || points[0][0] !== xMin)
points.unshift(getZigzagPoint(xMin, offset, pattern));
if (points[points.length - 1][0] !== xMax)
points.push(getZigzagPoint(xMax, offset, pattern));
return points;
function getZigzagInflectionPoints(offset2, length2, pattern2) {
const { period } = pattern2;
const scaledOffset = offset2 / period;
const patternInflectionPoints = [0, 0.5];
const inflectionPoints = patternInflectionPoints.map((x) => x - scaledOffset).map(getRemainderAbs).sort((a, b) => a - b);
const repeatedPoints = Array.from(
{ length: Math.floor(inflectionPoints.length * (period / length2)) },
(_, i) => inflectionPoints[i % inflectionPoints.length] + Math.floor(i / inflectionPoints.length)
);
return repeatedPoints.map((x) => x * period).map((x) => getZigzagPoint(x, offset2, pattern2));
}
function getZigzagPoint(x, offset2, pattern2) {
return [x, getZigzagValue(offset2 + x, pattern2)];
}
function getZigzagValue(x, pattern2) {
const { low, high, period } = pattern2;
const scaledX = getRemainderAbs(x / period);
const y = scaledX > 0.5 ? 1 - 2 * (scaledX - 0.5) : 2 * scaledX;
return low + (high - low) * y;
}
}
function getRemainderAbs(value) {
const remainder = value % 1;
return remainder < 0 ? remainder + 1 : remainder;
}
function swapArrayItems(items, leftIndex, rightIndex) {
const results = [...items];
const temp = results[leftIndex];
results[leftIndex] = results[rightIndex];
results[rightIndex] = temp;
return results;
}
var MiniRangeArea = {
chartType: "rangeArea",
miniChart: MiniRangeAreaClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/statistical/miniBoxPlot.ts
var MiniBoxPlotClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes, isCustomTheme) {
super(container, agChartsExports, "boxPlotTooltip");
const {
size,
padding,
agChartsExports: { _Scene }
} = this;
const data = [11, 11.5, 10.5];
const maxRatio = 1.2;
const q3Ratio = 1.1;
const q1Ratio = 0.9;
const minRatio = 0.8;
const yScale = new _Scene.LinearScale();
yScale.domain = [
data.reduce((a, b) => Math.min(a, b), Infinity) * minRatio,
data.reduce((a, b) => Math.max(a, b), 0) * maxRatio
];
yScale.range = [size - 1.5 * padding, padding];
const xScale = new _Scene.CategoryScale();
xScale.domain = data.map((_, index) => index);
xScale.range = [padding, size - padding];
xScale.paddingInner = 0.4;
xScale.paddingOuter = 0.2;
const bandwidth = Math.round(xScale.bandwidth);
const halfBandWidth = Math.round(xScale.bandwidth / 2);
this.boxPlotGroups = data.map((datum, i) => {
const [minValue, q1Value, q3Value, maxValue] = [
datum * minRatio,
datum * q1Ratio,
datum * q3Ratio,
datum * maxRatio
];
const top = Math.round(yScale.convert(q3Value));
const left = Math.round(xScale.convert(i));
const right = Math.round(left + bandwidth);
const bottom = Math.round(yScale.convert(q1Value));
const min = Math.round(yScale.convert(minValue));
const mid = Math.round(yScale.convert(datum));
const max = Math.round(yScale.convert(maxValue));
const whiskerX = left + halfBandWidth;
const boxPlotGroup = new _Scene.Group();
const box = new _Scene.Rect();
const median = new _Scene.Line();
const topWhisker = new _Scene.Line();
const bottomWhisker = new _Scene.Line();
const topCap = new _Scene.Line();
const bottomCap = new _Scene.Line();
box.x = left;
box.y = top;
box.width = bandwidth;
box.height = bottom - top;
box.strokeWidth = 1;
box.strokeOpacity = 0.75;
box.crisp = true;
this.setLineProperties(median, left, right, mid, mid);
this.setLineProperties(topWhisker, whiskerX, whiskerX, max, top);
this.setLineProperties(bottomWhisker, whiskerX, whiskerX, min, bottom);
this.setLineProperties(topCap, left, right, max, max);
this.setLineProperties(bottomCap, left, right, min, min);
boxPlotGroup.append([box, median, topWhisker, bottomWhisker, topCap, bottomCap]);
return boxPlotGroup;
});
this.updateColors(fills, strokes, isCustomTheme);
this.root.append(this.boxPlotGroups);
}
updateColors(fills, strokes, isCustomTheme) {
const { _Theme } = this.agChartsExports;
this.boxPlotGroups.forEach((group, i) => {
for (const node of group.children()) {
const fill = fills[i % fills.length];
node.fill = isCustomTheme ? fill : _Theme.resolveOperation({ $mix: [fill, { $ref: "backgroundColor" }, 0.7] });
node.stroke = strokes[i % strokes.length];
}
});
}
setLineProperties(line, x1, x2, y1, y2) {
line.x1 = x1;
line.x2 = x2;
line.y1 = y1;
line.y2 = y2;
line.strokeOpacity = 0.75;
}
};
var MiniBoxPlot = {
chartType: "boxPlot",
miniChart: MiniBoxPlotClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/hierarchical/miniTreemap.ts
var MiniTreemapClass = class extends MiniChart {
constructor(container, agChartsExports, fills, strokes, isCustomTheme) {
super(container, agChartsExports, "treemapTooltip");
const {
size,
padding,
agChartsExports: { _Scene }
} = this;
const data = [
[1, 1],
[3, 2, 1]
];
const treeSize = data.length;
const treePadding = treeSize % 2 === 0 ? 0.3 : 0.2;
const range = [padding, size - padding];
const columns = data.length;
const columnParts = columns * (columns + 1) / 2;
const columnPadding = treePadding / (columns - 1);
const availableRange = range[1] - range[0];
const availableWidth = availableRange - treePadding;
let previousX = range[0];
this.rects = data.reduce((rects, d, columnIndex) => {
rects ?? (rects = []);
const widthRatio = (columns - columnIndex) / columnParts;
const width = availableWidth * widthRatio;
const rows = d.length;
const rowParts = d.reduce((parts, ratio) => parts += ratio, 0);
const rowPadding = treePadding / (rows - 1 || 1);
const availableHeight = rows > 1 ? availableRange - treePadding : availableRange;
let previousY = range[0];
const xRects = d.map((ratio) => {
const rect = new _Scene.Rect();
const height = availableHeight * ratio / rowParts;
rect.x = previousX;
rect.y = previousY;
rect.width = width;
rect.height = height;
rect.strokeWidth = 0.75;
rect.crisp = true;
previousY += height + rowPadding;
return rect;
});
previousX += width + columnPadding;
rects.push(...xRects);
return rects;
}, []);
this.updateColors(fills, strokes, isCustomTheme);
const rectGroup = new _Scene.Group();
rectGroup.setClipRect(new _Scene.BBox(padding, padding, size - padding, size - padding));
rectGroup.append(this.rects);
this.root.append(rectGroup);
}
updateColors(fills, strokes, isCustomTheme) {
const { _Theme } = this.agChartsExports;
this.rects.forEach((rect, i) => {
rect.fill = fills[i % strokes.length];
rect.stroke = isCustomTheme ? strokes[i % strokes.length] : _Theme.resolveOperation({ $ref: "backgroundColor" });
});
}
};
var MiniTreemap = {
chartType: "treemap",
miniChart: MiniTreemapClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/hierarchical/miniSunburst.ts
var MiniSunburstClass = class extends MiniChartWithPolarAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "sunburstTooltip");
// Hierarchical data using multidimensional array
this.data = [
[[], []],
[[], []],
[[], []]
];
// Rotate the chart by the given angle (-90 degrees)
this.angleOffset = -Math.PI / 2;
this.innerRadiusRatio = 0;
this.showRadiusAxisLine = false;
this.showAngleAxisLines = false;
const {
data,
size,
padding,
angleOffset,
innerRadiusRatio,
agChartsExports: { _Scene }
} = this;
const radius = (size - padding * 2) / 2;
const angleRange = [angleOffset + 0, angleOffset + 2 * Math.PI];
const angleExtent = Math.abs(angleRange[1] - angleRange[0]);
const radiusRange = [radius * innerRadiusRatio, radius];
const radiusExtent = Math.abs(radiusRange[1] - radiusRange[0]);
let maxDepth = 0;
const findMaxDepth = (data2, parentDepth) => {
data2.forEach((child) => {
const depth = parentDepth + 1;
maxDepth = Math.max(maxDepth, depth);
findMaxDepth(child, depth);
});
};
findMaxDepth(data, 0);
const radiusRatio = radiusExtent / maxDepth;
const center = this.size / 2;
const startAngle = angleRange[0];
this.series = [];
const createSectors = (data2, depth, startAngle2, availableAngle, group) => {
const isArray = Array.isArray(data2);
if (!isArray) {
return;
}
const childDepth = depth + 1;
let previousAngle = startAngle2;
data2.forEach((child, childIndex, children) => {
let childGroup = group;
if (!childGroup) {
childGroup = new _Scene.Group();
this.series.push(childGroup);
}
const innerRadius = radiusRange[0] + depth * radiusRatio;
const outerRadius = radiusRange[0] + childDepth * radiusRatio;
const angleRatio = 1 / children.length;
const start = previousAngle;
const end = start + availableAngle * angleRatio;
const sector = new _Scene.Sector();
sector.centerX = center;
sector.centerY = center;
sector.innerRadius = innerRadius;
sector.outerRadius = outerRadius;
sector.startAngle = start;
sector.endAngle = end;
sector.stroke = void 0;
sector.strokeWidth = 0;
sector.inset = 0.75;
previousAngle = end;
childGroup.append(sector);
createSectors(child, childDepth, start, Math.abs(end - start), childGroup);
});
};
createSectors(data, 0, startAngle, angleExtent);
this.root.append(this.series);
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.series.forEach((group, i) => {
for (const sector of group.children()) {
sector.fill = fills[i % fills.length];
sector.stroke = strokes[i % strokes.length];
}
});
}
};
var MiniSunburst = {
chartType: "sunburst",
miniChart: MiniSunburstClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/specialized/miniHeatmap.ts
var MiniHeatmapClass = class extends MiniChart {
constructor(container, agChartsExports, fills, strokes, isCustomTheme) {
super(container, agChartsExports, "heatmapTooltip");
const {
size,
padding,
agChartsExports: { _Scene }
} = this;
const heatmapSize = 3;
const data = Array.from(
{ length: heatmapSize },
(_, __) => Array.from({ length: heatmapSize }, (_2, yIndex) => yIndex)
);
const domain = data.map((_, index) => index);
const xScale = new _Scene.CategoryScale();
xScale.domain = domain;
xScale.range = [padding, size - padding];
xScale.paddingInner = 0.01;
xScale.paddingOuter = 0.1;
const yScale = new _Scene.CategoryScale();
yScale.domain = domain;
yScale.range = [padding, size - padding];
yScale.paddingInner = 0.01;
yScale.paddingOuter = 0.1;
const width = xScale.bandwidth ?? 0;
const height = yScale.bandwidth ?? 0;
this.rects = data.reduce((rects, d, index) => {
rects ?? (rects = []);
const xRects = d.map((_, yIndex) => {
const rect = new _Scene.Rect();
rect.x = xScale.convert(index);
rect.y = yScale.convert(yIndex);
rect.width = width;
rect.height = height;
rect.strokeWidth = 0;
rect.crisp = true;
return rect;
});
rects.push(...xRects);
return rects;
}, []);
this.updateColors(fills, strokes, isCustomTheme);
const rectGroup = new _Scene.Group();
rectGroup.setClipRect(new _Scene.BBox(padding, padding, size - padding, size - padding));
rectGroup.append(this.rects);
this.root.append(rectGroup);
}
updateColors(fills, strokes, isCustomTheme) {
const { _Theme, _Util } = this.agChartsExports;
const colorRange = isCustomTheme ? [fills[0], fills[1]] : _Theme.resolveOperation({ $palette: "divergingColors" });
const stroke = isCustomTheme ? strokes[0] : _Theme.resolveOperation({ $ref: "backgroundColor" });
const fillFn = _Util.interpolateColor(colorRange[0], colorRange[1]);
this.rects.forEach((rect, i) => {
rect.fill = fillFn(i * 0.2);
rect.stroke = stroke;
});
}
};
var MiniHeatmap = {
chartType: "heatmap",
miniChart: MiniHeatmapClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/specialized/miniWaterfall.ts
var MiniWaterfallClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes, isCustomTheme) {
super(container, agChartsExports, "waterfallTooltip");
this.data = [4, 3, -3, 6, -3];
this.bars = this.createWaterfall(this.root, this.data, this.size, this.padding, "vertical").bars;
this.updateColors(fills, strokes, isCustomTheme);
}
updateColors(fills, strokes, isCustomTheme) {
const {
data,
agChartsExports: { _Theme }
} = this;
const positive = {
fill: isCustomTheme ? fills[0] : _Theme.resolveOperation({ $palette: "altUp.fill" }),
stroke: isCustomTheme ? strokes[0] : _Theme.resolveOperation({ $palette: "altUp.stroke" })
};
const negative = {
fill: isCustomTheme ? fills[1] : _Theme.resolveOperation({ $palette: "altDown.fill" }),
stroke: isCustomTheme ? strokes[1] : _Theme.resolveOperation({ $palette: "altDown.stroke" })
};
this.bars.forEach((bar, i) => {
const isPositive = data[i] >= 0;
bar.fill = isPositive ? positive.fill : negative.fill;
bar.stroke = isPositive ? positive.stroke : negative.stroke;
});
}
createWaterfall(root, data, size, padding, direction) {
const scalePadding = 2 * padding;
const { processedData, min, max } = accumulateData(data.map((d) => [d]));
const flatData = processedData.reduce((flat, d) => flat.concat(d), []);
const { _Scene } = this.agChartsExports;
const yScale = new _Scene.LinearScale();
yScale.domain = [Math.min(min, 0), max];
yScale.range = [size - scalePadding, scalePadding];
const xScale = new _Scene.CategoryScale();
xScale.domain = data.map((_, index) => index);
xScale.range = [padding, size - padding];
xScale.paddingInner = 0.2;
xScale.paddingOuter = 0.3;
const width = xScale.bandwidth;
const connectorLine = new _Scene.Path();
connectorLine.stroke = "#575757";
connectorLine.strokeWidth = 0;
const pixelAlignmentOffset = Math.floor(connectorLine.strokeWidth) % 2 / 2;
const connectorPath = connectorLine.path;
connectorPath.clear();
const barAlongX = direction === "horizontal";
const bars = flatData.map((datum, i) => {
const previousDatum = i > 0 ? flatData[i - 1] : 0;
const rawValue = data[i];
const isPositive = rawValue > 0;
const currY = Math.round(yScale.convert(datum));
const trailY = Math.round(yScale.convert(previousDatum));
const y = (isPositive ? currY : trailY) - pixelAlignmentOffset;
const bottomY = (isPositive ? trailY : currY) + pixelAlignmentOffset;
const height = Math.abs(bottomY - y);
const x = xScale.convert(i);
const rect = new _Scene.Rect();
rect.x = barAlongX ? y : x;
rect.y = barAlongX ? x : y;
rect.width = barAlongX ? height : width;
rect.height = barAlongX ? width : height;
rect.strokeWidth = 0;
rect.crisp = true;
const moveTo = currY + pixelAlignmentOffset;
const lineTo = trailY + pixelAlignmentOffset;
if (i > 0) {
const lineToX = barAlongX ? lineTo : rect.x;
const lineToY = barAlongX ? rect.y : lineTo;
connectorPath.lineTo(lineToX, lineToY);
}
const moveToX = barAlongX ? moveTo : rect.x;
const moveToY = barAlongX ? rect.y : moveTo;
connectorPath.moveTo(moveToX, moveToY);
return rect;
});
root.append([connectorLine, ...bars]);
return { bars };
}
};
var MiniWaterfall = {
chartType: "waterfall",
miniChart: MiniWaterfallClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/combo/miniColumnLineCombo.ts
var MiniColumnLineComboClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "columnLineComboTooltip");
this.columnData = [3, 4];
this.lineData = [[5, 4, 6, 5, 4]];
const { root, columnData, lineData, size, padding } = this;
this.columns = createColumnRects({
stacked: false,
root,
data: columnData,
size,
padding,
xScaleDomain: [0, 1],
yScaleDomain: [0, 4],
xScalePadding: 0.5,
agChartsExports
});
root.append(this.columns);
this.lines = createLinePaths(agChartsExports, root, lineData, size, padding);
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.columns.forEach((bar, i) => {
bar.fill = fills[i];
bar.stroke = strokes[i];
});
this.lines.forEach((line, i) => {
line.stroke = fills[i + 2];
});
}
};
var MiniColumnLineCombo = {
chartType: "columnLineCombo",
miniChart: MiniColumnLineComboClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/combo/miniAreaColumnCombo.ts
var MiniAreaColumnComboClass = class extends MiniChartWithAxes {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "areaColumnComboTooltip");
this.columnData = [3, 4.5];
this.areaData = [[5, 4, 6, 5, 4]];
const {
root,
columnData,
areaData,
size,
padding,
agChartsExports: { _Scene }
} = this;
this.columns = createColumnRects({
stacked: false,
root,
data: columnData,
size,
padding,
xScaleDomain: [0, 1],
yScaleDomain: [0, 6],
xScalePadding: 0.5,
agChartsExports
});
const xScale = new _Scene.CategoryScale();
xScale.range = [padding, size - padding];
xScale.domain = [0, 1, 2, 3, 4];
xScale.paddingInner = 1;
xScale.paddingOuter = 0;
const yScale = new _Scene.LinearScale();
yScale.range = [size - padding, padding];
yScale.domain = [0, 6];
const pathData = [];
const yZero = yScale.convert(0);
const firstX = xScale.convert(0);
areaData.forEach((series, i) => {
const points = pathData[i] || (pathData[i] = []);
series.forEach((data, j) => {
const yDatum = data;
const xDatum = j;
const x = xScale.convert(xDatum);
const y = yScale.convert(yDatum);
points[j] = { x, y };
});
const lastX = xScale.convert(series.length - 1);
pathData[i].push(
{
x: lastX,
y: yZero
},
{
x: firstX,
y: yZero
}
);
});
this.areas = pathData.map((points) => {
const area = new _Scene.Path();
area.strokeWidth = 0;
area.fillOpacity = 0.8;
const path = area.path;
points.forEach((point, i) => path[i > 0 ? "lineTo" : "moveTo"](point.x, point.y));
return area;
});
const areaGroup = new _Scene.Group();
areaGroup.setClipRect(new _Scene.BBox(padding, padding, size - padding * 2, size - padding * 2));
const columnGroup = new _Scene.Group();
columnGroup.setClipRect(new _Scene.BBox(padding, padding, size - padding * 2, size - padding * 2));
areaGroup.append(this.areas);
columnGroup.append(this.columns);
root.append(areaGroup);
root.append(columnGroup);
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.areas.forEach((area, i) => {
area.fill = fills[i];
area.stroke = strokes[i];
});
this.columns.forEach((bar, i) => {
bar.fill = fills[i + 1];
bar.stroke = strokes[i + 1];
});
}
};
var MiniAreaColumnCombo = {
chartType: "areaColumnCombo",
miniChart: MiniAreaColumnComboClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/combo/miniCustomCombo.ts
var MiniCustomComboClass = class extends MiniChart {
constructor(container, agChartsExports, fills, strokes) {
super(container, agChartsExports, "customComboTooltip");
this.columnData = [3, 4];
this.lineData = [[5, 4, 6, 5, 4]];
const {
root,
columnData,
lineData,
size,
padding,
agChartsExports: { _Scene }
} = this;
this.columns = createColumnRects({
stacked: false,
root,
data: columnData,
size,
padding,
xScaleDomain: [0, 1],
yScaleDomain: [0, 4],
xScalePadding: 0.5,
agChartsExports
});
root.append(this.columns);
this.lines = createLinePaths(this.agChartsExports, root, lineData, size, padding);
const axisStroke = "grey";
const axisOvershoot = 3;
const leftAxis = new _Scene.Line();
leftAxis.x1 = padding;
leftAxis.y1 = padding;
leftAxis.x2 = padding;
leftAxis.y2 = size - padding + axisOvershoot;
leftAxis.stroke = axisStroke;
const bottomAxis = new _Scene.Line();
bottomAxis.x1 = padding - axisOvershoot + 1;
bottomAxis.y1 = size - padding;
bottomAxis.x2 = size - padding + 1;
bottomAxis.y2 = size - padding;
bottomAxis.stroke = axisStroke;
const penIcon = new _Scene.Path();
this.buildPenIconPath(penIcon);
penIcon.fill = "whitesmoke";
penIcon.stroke = "darkslategrey";
penIcon.strokeWidth = 1;
root.append([bottomAxis, leftAxis, penIcon]);
this.updateColors(fills, strokes);
}
updateColors(fills, strokes) {
this.columns.forEach((bar, i) => {
bar.fill = fills[i];
bar.stroke = strokes[i];
});
this.lines.forEach((line, i) => {
line.stroke = fills[i + 2];
});
}
buildPenIconPath(penIcon) {
const { path } = penIcon;
path.moveTo(25.76, 43.46);
path.lineTo(31.27, 48.53);
path.moveTo(49.86, 22);
path.lineTo(49.86, 22);
path.cubicCurveTo(49.01994659053345, 21.317514933510974, 47.89593834348529, 21.09645997825817, 46.86, 21.41);
path.lineTo(46.86, 21.41);
path.cubicCurveTo(45.55460035985361, 21.77260167850787, 44.38777081121966, 22.517979360321792, 43.51, 23.55);
path.lineTo(25.51, 43.8);
path.lineTo(25.43, 43.89);
path.lineTo(23.01, 51.89);
path.lineTo(22.83, 52.46);
path.lineTo(31.02, 48.86);
path.lineTo(49.02, 28.52);
path.lineTo(49.02, 28.52);
path.cubicCurveTo(49.940716461596224, 27.521914221246085, 50.54302631059587, 26.2720342455763, 50.75, 24.93);
path.lineTo(50.75, 24.93);
path.cubicCurveTo(50.95363374988308, 23.866379846512814, 50.62080640232334, 22.77066734274871, 49.86, 22);
path.closePath();
path.moveTo(41.76, 25.5);
path.lineTo(47.34, 30.5);
path.moveTo(40.74, 26.65);
path.lineTo(46.25, 31.71);
}
};
var MiniCustomCombo = {
chartType: "customCombo",
miniChart: MiniCustomComboClass
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniChartsContainer.ts
var miniChartMapping = {
columnGroup: {
column: { range: true, pivot: true, enterprise: false, icon: MiniColumn },
stackedColumn: { range: true, pivot: true, enterprise: false, icon: MiniStackedColumn },
normalizedColumn: { range: true, pivot: true, enterprise: false, icon: MiniNormalizedColumn }
},
barGroup: {
bar: { range: true, pivot: true, enterprise: false, icon: MiniBar },
stackedBar: { range: true, pivot: true, enterprise: false, icon: MiniStackedBar },
normalizedBar: { range: true, pivot: true, enterprise: false, icon: MiniNormalizedBar }
},
pieGroup: {
pie: { range: true, pivot: true, enterprise: false, icon: MiniPie },
donut: { range: true, pivot: true, enterprise: false, icon: MiniDonut },
doughnut: { range: true, pivot: true, enterprise: false, icon: MiniDonut }
},
lineGroup: {
line: { range: true, pivot: true, enterprise: false, icon: MiniLine },
stackedLine: { range: true, pivot: true, enterprise: false, icon: MiniStackedLine },
normalizedLine: { range: true, pivot: true, enterprise: false, icon: MiniNormalizedLine }
},
scatterGroup: {
scatter: { range: true, pivot: true, enterprise: false, icon: MiniScatter },
bubble: { range: true, pivot: true, enterprise: false, icon: MiniBubble }
},
areaGroup: {
area: { range: true, pivot: true, enterprise: false, icon: MiniArea },
stackedArea: { range: true, pivot: true, enterprise: false, icon: MiniStackedArea },
normalizedArea: { range: true, pivot: true, enterprise: false, icon: MiniNormalizedArea }
},
polarGroup: {
radarLine: { range: true, pivot: false, enterprise: true, icon: MiniRadarLine },
radarArea: { range: true, pivot: false, enterprise: true, icon: MiniRadarArea },
nightingale: { range: true, pivot: false, enterprise: true, icon: MiniNightingale },
radialColumn: { range: true, pivot: false, enterprise: true, icon: MiniRadialColumn },
radialBar: { range: true, pivot: false, enterprise: true, icon: MiniRadialBar }
},
statisticalGroup: {
boxPlot: { range: true, pivot: false, enterprise: true, icon: MiniBoxPlot },
histogram: { range: true, pivot: false, enterprise: false, icon: MiniHistogram },
rangeBar: { range: true, pivot: false, enterprise: true, icon: MiniRangeBar },
rangeArea: { range: true, pivot: false, enterprise: true, icon: MiniRangeArea }
},
hierarchicalGroup: {
treemap: { range: true, pivot: true, enterprise: true, icon: MiniTreemap },
sunburst: { range: true, pivot: true, enterprise: true, icon: MiniSunburst }
},
specializedGroup: {
heatmap: { range: true, pivot: false, enterprise: true, icon: MiniHeatmap },
waterfall: { range: true, pivot: false, enterprise: true, icon: MiniWaterfall }
},
combinationGroup: {
columnLineCombo: { range: true, pivot: true, enterprise: false, icon: MiniColumnLineCombo },
areaColumnCombo: { range: true, pivot: true, enterprise: false, icon: MiniAreaColumnCombo },
customCombo: { range: true, pivot: true, enterprise: false, icon: MiniCustomCombo }
},
funnelGroup: {
funnel: { range: true, pivot: false, enterprise: true, icon: MiniFunnel },
coneFunnel: { range: true, pivot: false, enterprise: true, icon: MiniConeFunnel },
pyramid: { range: true, pivot: false, enterprise: true, icon: MiniPyramid }
}
};
var DEFAULT_CHART_GROUPS = {
columnGroup: ["column", "stackedColumn", "normalizedColumn"],
barGroup: ["bar", "stackedBar", "normalizedBar"],
pieGroup: ["pie", "donut"],
lineGroup: ["line", "stackedLine", "normalizedLine"],
areaGroup: ["area", "stackedArea", "normalizedArea"],
scatterGroup: ["scatter", "bubble"],
polarGroup: ["radarLine", "radarArea", "nightingale", "radialColumn", "radialBar"],
statisticalGroup: ["boxPlot", "histogram", "rangeBar", "rangeArea"],
hierarchicalGroup: ["treemap", "sunburst"],
specializedGroup: ["heatmap", "waterfall"],
funnelGroup: ["funnel", "coneFunnel", "pyramid"],
combinationGroup: ["columnLineCombo", "areaColumnCombo", "customCombo"]
};
var MiniChartsContainer = class extends import_ag_grid_community283.Component {
constructor(chartController, fills, strokes, isCustomTheme, chartGroups = DEFAULT_CHART_GROUPS) {
super(
/* html */
`<div class="ag-chart-settings-mini-wrapper"></div>`
);
this.wrappers = /* @__PURE__ */ new Map();
this.chartController = chartController;
this.fills = fills;
this.strokes = strokes;
this.isCustomTheme = isCustomTheme;
this.chartGroups = { ...chartGroups };
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
if (!this.chartController.customComboExists() && this.chartGroups.combinationGroup) {
this.chartGroups.combinationGroup = this.chartGroups.combinationGroup.filter(
(chartType) => chartType !== "customCombo"
);
}
const eGui = this.getGui();
const isEnterprise = this.chartController.isEnterprise();
const isPivotChart = this.chartController.isPivotChart();
const isRangeChart = !isPivotChart;
const displayedMenuGroups = Object.keys(this.chartGroups).map((group) => {
const menuGroup = group in miniChartMapping ? miniChartMapping[group] : void 0;
if (!menuGroup) {
(0, import_ag_grid_community283._warn)(148, { group });
return null;
}
const chartGroupValues = this.chartGroups[group] ?? [];
const menuItems = chartGroupValues.map((chartType) => {
const menuItem = chartType in menuGroup ? menuGroup[chartType] : void 0;
if (!menuItem) {
(0, import_ag_grid_community283._warn)(149, { group, chartType });
return null;
}
if (!isEnterprise && menuItem.enterprise) {
return null;
}
if (isRangeChart && menuItem.range)
return menuItem;
if (isPivotChart && menuItem.pivot)
return menuItem;
return null;
}).filter((menuItem) => menuItem != null);
if (menuItems.length === 0)
return null;
return {
label: this.chartTranslation.translate(group),
items: menuItems
};
}).filter((menuGroup) => menuGroup != null);
for (const { label, items } of displayedMenuGroups) {
const groupComponent = this.createBean(
new AgGroupComponent({
title: label,
suppressEnabledCheckbox: true,
enabled: true,
suppressOpenCloseIcons: true,
cssIdentifier: "charts-settings",
direction: "horizontal",
suppressKeyboardNavigation: true
})
);
for (const menuItem of items) {
const { miniChart: MiniClass, chartType } = menuItem.icon;
const miniWrapper = document.createElement("div");
miniWrapper.classList.add("ag-chart-mini-thumbnail");
miniWrapper.setAttribute("tabindex", "0");
miniWrapper.setAttribute("role", "button");
const miniClassChartType = chartType;
const listener = () => {
this.chartController.setChartType(miniClassChartType);
this.updateSelectedMiniChart();
};
this.addManagedListeners(miniWrapper, {
click: listener,
keydown: (event) => {
if (event.key == import_ag_grid_community283.KeyCode.ENTER || event.key === import_ag_grid_community283.KeyCode.SPACE) {
event.preventDefault();
listener();
}
}
});
this.wrappers.set(miniClassChartType, miniWrapper);
this.createBean(
new MiniClass(miniWrapper, this.beans.agChartsExports, this.fills, this.strokes, this.isCustomTheme)
);
groupComponent.addItem(miniWrapper);
}
eGui.appendChild(groupComponent.getGui());
}
this.updateSelectedMiniChart();
}
updateSelectedMiniChart() {
const selectedChartType = this.chartController.getChartType();
this.wrappers.forEach((miniChart, miniChartType) => {
const selected = miniChartType === selectedChartType;
miniChart.classList.toggle("ag-selected", selected);
const chartName = this.chartTranslation.translate(getFullChartNameTranslationKey(miniChartType));
const ariaLabel = selected ? `${chartName}. ${this.chartTranslation.translate("ariaChartSelected")}` : chartName;
(0, import_ag_grid_community283._setAriaLabel)(miniChart, ariaLabel);
});
}
destroy() {
this.wrappers.clear();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/chartSettingsPanel.ts
var ChartSettingsPanel = class extends import_ag_grid_community284.Component {
constructor(chartController) {
super(
/* html */
`<div class="ag-chart-settings-wrapper">
<div data-ref="eMiniChartsContainer" class="ag-chart-settings-mini-charts-container ag-scrollable-container"></div>
<div data-ref="eNavBar" class="ag-chart-settings-nav-bar">
<div data-ref="ePrevBtn" class="ag-chart-settings-prev">
<button type="button" class="ag-button ag-chart-settings-prev-button"></button>
</div>
<div data-ref="eCardSelector" class="ag-chart-settings-card-selector"></div>
<div data-ref="eNextBtn" class="ag-chart-settings-next">
<button type="button" class="ag-button ag-chart-settings-next-button"></button>
</div>
</div>
</div>`
);
this.chartController = chartController;
this.eMiniChartsContainer = import_ag_grid_community284.RefPlaceholder;
this.eNavBar = import_ag_grid_community284.RefPlaceholder;
this.eCardSelector = import_ag_grid_community284.RefPlaceholder;
this.ePrevBtn = import_ag_grid_community284.RefPlaceholder;
this.eNextBtn = import_ag_grid_community284.RefPlaceholder;
this.miniChartsContainers = [];
this.cardItems = [];
this.activePaletteIndex = 0;
this.palettes = [];
this.themes = [];
}
postConstruct() {
this.resetPalettes();
this.ePrevBtn.insertAdjacentElement("afterbegin", (0, import_ag_grid_community284._createIconNoSpan)("chartsThemePrevious", this.beans));
this.eNextBtn.insertAdjacentElement("afterbegin", (0, import_ag_grid_community284._createIconNoSpan)("chartsThemeNext", this.beans));
this.addManagedElementListeners(this.ePrevBtn, { click: () => this.setActivePalette(this.getPrev(), "left") });
this.addManagedElementListeners(this.eNextBtn, { click: () => this.setActivePalette(this.getNext(), "right") });
const reset = () => this.resetPalettes(true);
this.addManagedListeners(this.chartController, {
chartTypeChanged: reset,
chartApiUpdate: reset
});
this.scrollSelectedIntoView();
}
scrollSelectedIntoView() {
setTimeout(() => {
const isMiniChartsContainerVisible = (miniChartsContainers) => {
return !miniChartsContainers.getGui().classList.contains("ag-hidden");
};
const currentMiniChartContainer = this.miniChartsContainers.find(isMiniChartsContainerVisible);
const currentChart = currentMiniChartContainer.getGui().querySelector(".ag-selected");
if (currentChart) {
const parent = currentChart.offsetParent;
if (parent) {
this.eMiniChartsContainer.scrollTo(0, parent.offsetTop);
}
}
}, 250);
}
resetPalettes(forceReset) {
const palettes = this.chartController.getPalettes();
const chartGroups = this.gos.get("chartToolPanelsDef")?.settingsPanel?.chartGroupsDef;
if ((0, import_ag_grid_community284._areEqual)(palettes, this.palettes) && !forceReset || this.isAnimating) {
return;
}
this.palettes = palettes;
this.themes = this.chartController.getThemeNames();
this.activePaletteIndex = this.themes.findIndex((name) => name === this.chartController.getChartThemeName());
this.cardItems = [];
(0, import_ag_grid_community284._clearElement)(this.eCardSelector);
this.destroyMiniCharts();
const { themes } = this;
this.palettes.forEach((palette, index) => {
const isActivePalette = this.activePaletteIndex === index;
const { fills = [], strokes = [] } = palette;
const themeName = themes[index];
const isCustomTheme = !isStockTheme(themeName, this.beans.agChartsExports._Theme);
const miniChartsContainer = this.createBean(
new MiniChartsContainer(this.chartController, fills, strokes, isCustomTheme, chartGroups)
);
this.miniChartsContainers.push(miniChartsContainer);
this.eMiniChartsContainer.appendChild(miniChartsContainer.getGui());
this.addCardLink(index);
if (isActivePalette) {
miniChartsContainer.updateSelectedMiniChart();
} else {
miniChartsContainer.setDisplayed(false);
}
});
(0, import_ag_grid_community284._setDisplayed)(this.eNavBar, this.palettes.length > 1);
(0, import_ag_grid_community284._radioCssClass)(this.cardItems[this.activePaletteIndex], "ag-selected", "ag-not-selected");
}
addCardLink(index) {
const link = document.createElement("div");
link.classList.add("ag-chart-settings-card-item");
this.addManagedElementListeners(link, {
click: () => {
this.setActivePalette(index, index < this.activePaletteIndex ? "left" : "right");
}
});
this.eCardSelector.appendChild(link);
this.cardItems.push(link);
}
getPrev() {
let prev = this.activePaletteIndex - 1;
if (prev < 0) {
prev = this.palettes.length - 1;
}
return prev;
}
getNext() {
let next = this.activePaletteIndex + 1;
if (next >= this.palettes.length) {
next = 0;
}
return next;
}
setActivePalette(index, animationDirection) {
if (this.isAnimating || this.activePaletteIndex === index) {
return;
}
(0, import_ag_grid_community284._radioCssClass)(this.cardItems[index], "ag-selected", "ag-not-selected");
const currentPalette = this.miniChartsContainers[this.activePaletteIndex];
const currentGui = currentPalette.getGui();
const futurePalette = this.miniChartsContainers[index];
const nextGui = futurePalette.getGui();
currentPalette.updateSelectedMiniChart();
futurePalette.updateSelectedMiniChart();
const multiplier = animationDirection === "left" ? -1 : 1;
const final = nextGui.style.left = `${(0, import_ag_grid_community284._getAbsoluteWidth)(this.getGui()) * multiplier}px`;
this.activePaletteIndex = index;
this.isAnimating = true;
const animatingClass = "ag-animating";
futurePalette.setDisplayed(true);
currentPalette.addCss(animatingClass);
futurePalette.addCss(animatingClass);
this.chartController.setChartThemeName(this.themes[index]);
window.setTimeout(() => {
currentGui.style.left = `${-parseFloat(final)}px`;
nextGui.style.left = "0px";
}, 0);
window.setTimeout(() => {
this.isAnimating = false;
currentPalette.removeCss(animatingClass);
futurePalette.removeCss(animatingClass);
currentPalette.setDisplayed(false);
}, 300);
}
destroyMiniCharts() {
(0, import_ag_grid_community284._clearElement)(this.eMiniChartsContainer);
this.miniChartsContainers = this.destroyBeans(this.miniChartsContainers);
}
destroy() {
this.destroyMiniCharts();
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/tabbedChartMenu.ts
var TAB_DATA = "data";
var TAB_FORMAT = "format";
var TabbedChartMenu = class extends import_ag_grid_community285.Component {
constructor(panels, chartMenuContext) {
super();
this.panels = panels;
this.chartMenuContext = chartMenuContext;
this.tabs = [];
}
wireBeans(beans) {
this.chartTranslation = beans.chartTranslation;
}
postConstruct() {
this.panels.forEach((panel) => {
const panelType = panel.replace("chart", "").toLowerCase();
const panelComp = this.createPanel(panelType);
const tabItem = this.createTab(panel, panelType, panelComp);
this.tabs.push(tabItem);
this.addDestroyFunc(() => this.destroyBean(panelComp));
});
this.tabbedLayout = new TabbedLayout({
items: this.tabs,
cssClass: "ag-chart-tabbed-menu",
keepScrollPosition: true,
suppressFocusBodyOnOpen: true,
suppressTrapFocus: true,
enableCloseButton: true,
closeButtonAriaLabel: this.chartTranslation.translate("ariaChartMenuClose"),
onCloseClicked: () => {
this.eventSource?.focus({ preventScroll: true });
this.dispatchLocalEvent({ type: "closed" });
}
});
this.createBean(this.tabbedLayout);
}
createTab(name, title, panelComp) {
const eWrapperDiv = (0, import_ag_grid_community285._createElement)({ tag: "div", cls: `ag-chart-tab ag-chart-${title}` });
this.createBean(panelComp);
eWrapperDiv.appendChild(panelComp.getGui());
const translatedTitle = this.chartTranslation.translate(title);
const titleEl = (0, import_ag_grid_community285._createElement)({ tag: "div", children: translatedTitle });
return {
title: titleEl,
titleLabel: translatedTitle,
bodyPromise: import_ag_grid_community285.AgPromise.resolve(eWrapperDiv),
getScrollableContainer: () => {
const scrollableContainer = eWrapperDiv.querySelector(".ag-scrollable-container");
return scrollableContainer || eWrapperDiv;
},
name
};
}
showTab(tab) {
const tabItem = this.tabs[tab];
this.tabbedLayout.showItem(tabItem);
}
getGui() {
return this.tabbedLayout && this.tabbedLayout.getGui();
}
showMenu(eventSource, suppressFocus) {
this.eventSource = eventSource;
if (!suppressFocus) {
this.tabbedLayout?.focusHeader(true);
}
}
destroy() {
if (this.parentComponent && this.parentComponent.isAlive()) {
this.destroyBean(this.parentComponent);
}
super.destroy();
}
createPanel(panelType) {
switch (panelType) {
case TAB_DATA:
return new ChartDataPanel(this.chartMenuContext);
case TAB_FORMAT:
return new FormatPanel(this.chartMenuContext);
default:
return new ChartSettingsPanel(this.chartMenuContext.chartController);
}
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/menu/chartMenu.ts
var ChartMenu = class extends import_ag_grid_community286.Component {
constructor(eChartContainer, eMenuPanelContainer, chartMenuContext) {
super(
/* html */
`<div class="ag-chart-menu-wrapper"></div>`
);
this.eChartContainer = eChartContainer;
this.eMenuPanelContainer = eMenuPanelContainer;
this.chartMenuContext = chartMenuContext;
this.buttons = {
chartLink: { iconName: "linked", callback: () => this.chartMenuSvc.toggleLinked(this.chartMenuContext) },
chartUnlink: {
iconName: "unlinked",
callback: () => this.chartMenuSvc.toggleLinked(this.chartMenuContext)
},
chartDownload: {
iconName: "chartsDownload",
callback: () => this.chartMenuSvc.downloadChart(this.chartMenuContext)
},
chartMenu: { iconName: "chartsMenu", callback: (eventSource) => this.showMenuList(eventSource) }
};
this.panels = [];
this.menuVisible = false;
this.chartController = chartMenuContext.chartController;
}
wireBeans(beans) {
this.chartMenuSvc = beans.chartMenuSvc;
this.chartMenuListFactory = beans.chartMenuListFactory;
this.environment = beans.environment;
}
postConstruct() {
this.chartToolbar = this.createManagedBean(new ChartToolbar());
this.getGui().appendChild(this.chartToolbar.getGui());
this.refreshToolbarAndPanels();
this.addManagedEventListeners({
chartCreated: (e) => {
if (e.chartId === this.chartController.getChartId()) {
const showDefaultToolPanel = Boolean(this.gos.get("chartToolPanelsDef")?.defaultToolPanel);
if (showDefaultToolPanel) {
this.showMenu({ panel: this.defaultPanel, suppressFocus: true });
}
}
}
});
this.addManagedListeners(this.chartController, {
chartLinkedChanged: this.refreshToolbarAndPanels.bind(this)
});
this.refreshMenuClasses();
this.addManagedListeners(this.chartController, { chartApiUpdate: this.refreshToolbarAndPanels.bind(this) });
}
isVisible() {
return this.menuVisible;
}
getExtraPaddingDirections() {
return ["chartMenu", "chartLink", "chartUnlink", "chartDownload"].some(
(v) => this.chartToolbarOptions.includes(v)
) ? ["top"] : [];
}
refreshToolbarAndPanels() {
this.initToolbarOptionsAndPanels();
this.updateToolbar();
}
initToolbarOptionsAndPanels() {
const { panels, defaultPanel } = this.chartMenuSvc.getChartToolPanels(this.chartController);
this.panels = panels;
this.defaultPanel = defaultPanel;
this.chartToolbarOptions = this.chartMenuSvc.getChartToolbarOptions();
}
updateToolbar() {
const buttons = this.chartToolbarOptions.map((buttonName) => {
const { iconName, callback } = this.buttons[buttonName];
return {
buttonName,
iconName,
callback
};
});
this.chartToolbar.updateParams({ buttons });
}
createMenuPanel(defaultTab) {
const menuPanel = this.menuPanel = this.createBean(
new AgPanel({
height: "100%",
closable: true,
hideTitleBar: true,
cssIdentifier: "chart-menu"
})
);
menuPanel.setParentComponent(this);
this.eMenuPanelContainer.appendChild(menuPanel.getGui());
this.tabbedMenu = this.createBean(new TabbedChartMenu(this.panels, this.chartMenuContext));
this.addManagedListeners(this.tabbedMenu, {
closed: () => {
this.hideMenu();
}
});
this.addManagedListeners(menuPanel, { destroyed: () => this.destroyBean(this.tabbedMenu) });
return new import_ag_grid_community286.AgPromise((res) => {
window.setTimeout(() => {
menuPanel.setBodyComponent(this.tabbedMenu);
this.tabbedMenu.showTab(defaultTab);
res(menuPanel);
}, 100);
});
}
showContainer(eventSource, suppressFocus) {
if (!this.menuPanel) {
return;
}
this.menuVisible = true;
this.refreshMenuClasses();
this.tabbedMenu.showMenu(eventSource, suppressFocus);
}
showMenu(params) {
const { panel, eventSource, suppressFocus } = params ?? {};
if (this.menuPanel && !panel) {
this.showContainer(eventSource, suppressFocus);
} else {
const menuPanel = panel || this.defaultPanel;
let tab = this.panels.indexOf(menuPanel);
if (tab < 0) {
(0, import_ag_grid_community286._warn)(143, { panel });
tab = this.panels.indexOf(this.defaultPanel);
}
if (this.menuPanel) {
this.tabbedMenu.showTab(tab);
this.showContainer(eventSource, suppressFocus);
} else {
this.createMenuPanel(tab).then(() => this.showContainer(eventSource, suppressFocus));
}
}
}
hideMenu() {
this.menuVisible = false;
this.refreshMenuClasses();
}
refreshMenuClasses() {
this.eChartContainer.classList.toggle("ag-chart-menu-visible", this.menuVisible);
this.eChartContainer.classList.toggle("ag-chart-menu-hidden", !this.menuVisible);
}
showMenuList(eventSource) {
this.chartMenuListFactory.showMenuList({
eventSource,
showMenu: () => this.showMenu({ eventSource }),
chartMenuContext: this.chartMenuContext
});
}
destroy() {
super.destroy();
if (this.menuPanel && this.menuPanel.isAlive()) {
this.destroyBean(this.menuPanel);
}
if (this.tabbedMenu && this.tabbedMenu.isAlive()) {
this.destroyBean(this.tabbedMenu);
}
}
};
// packages/ag-grid-enterprise/src/charts/chartComp/services/chartOptionsService.ts
var import_ag_grid_community287 = require("ag-grid-community");
var CARTESIAN_AXIS_TYPES = ["number", "category", "time", "grouped-category"];
var POLAR_AXIS_TYPES = ["angle-category", "angle-number", "radius-category", "radius-number"];
var VALID_AXIS_TYPES = [...CARTESIAN_AXIS_TYPES, ...POLAR_AXIS_TYPES];
var ChartOptionsService = class extends import_ag_grid_community287.BeanStub {
constructor(chartController) {
super();
this.chartController = chartController;
}
getChartThemeOverridesProxy() {
return {
getValue: (expression) => this.getChartOption(expression),
setValue: (expression, value) => this.setChartThemeOverrides([{ expression, value }]),
setValues: (properties) => this.setChartThemeOverrides(properties)
};
}
getAxisThemeOverridesProxy() {
return {
getValue: (expression) => this.getAxisProperty(expression),
setValue: (expression, value) => this.setAxisThemeOverrides([{ expression, value }]),
setValues: (properties) => this.setAxisThemeOverrides(properties)
};
}
getCartesianAxisOptionsProxy(axisType) {
return {
getValue: (expression) => this.getCartesianAxisProperty(axisType, expression),
setValue: (expression, value) => this.setCartesianAxisOptions(axisType, [{ expression, value }]),
setValues: (properties) => this.setCartesianAxisOptions(axisType, properties)
};
}
getCartesianAxisThemeOverridesProxy(axisType) {
return {
getValue: (expression) => this.getCartesianAxisProperty(axisType, expression),
setValue: (expression, value) => this.setCartesianAxisThemeOverrides(axisType, [{ expression, value }]),
setValues: (properties) => this.setCartesianAxisThemeOverrides(axisType, properties)
};
}
getCartesianAxisAppliedThemeOverridesProxy(axisType) {
return {
getValue: (expression) => this.getCartesianAxisThemeOverride(
axisType,
// Allow the caller to specify a wildcard expression to retrieve the whole set of overrides
expression === "*" ? null : expression
),
setValue: (expression, value) => this.setCartesianAxisThemeOverrides(
axisType,
// Allow the caller to specify a wildcard expression to set the whole set of overrides
[{ expression: expression === "*" ? null : expression, value }]
),
setValues: (properties) => this.setCartesianAxisThemeOverrides(axisType, properties)
};
}
getSeriesOptionsProxy(getSelectedSeries) {
return {
getValue: (expression, calculated) => this.getSeriesOption(getSelectedSeries(), expression, calculated),
setValue: (expression, value) => this.setSeriesOptions(getSelectedSeries(), [{ expression, value }]),
setValues: (properties) => this.setSeriesOptions(getSelectedSeries(), properties)
};
}
/**
* Determine the set of theme overrides that should be retained when transitioning from one chart type to another.
*/
getPersistedChartThemeOverrides(existingChartOptions, existingAxes, existingChartType, targetChartType) {
const retainedThemeOverrideKeys = this.getRetainedChartThemeOverrideKeys(existingChartType, targetChartType);
const retainedChartAxisThemeOverrideKeys = this.getRetainedChartAxisThemeOverrideKeys(
null,
existingChartType,
targetChartType
);
const targetChartOptions = this.createChartOptions();
for (const expression of retainedThemeOverrideKeys) {
const value = this.retrieveChartOptionsThemeOverride(existingChartOptions, existingChartType, expression);
if (value !== void 0) {
this.assignChartOptionsThemeOverride(targetChartOptions, targetChartType, expression, value);
}
}
if (existingAxes) {
this.assignPersistedAxisOverrides({
existingAxes,
retainedChartAxisThemeOverrideKeys,
existingChartOptions,
targetChartOptions,
existingChartType,
targetChartType
});
}
return targetChartOptions.theme.overrides;
}
assignPersistedAxisOverrides(params) {
const {
existingAxes,
retainedChartAxisThemeOverrideKeys,
existingChartOptions,
targetChartOptions,
existingChartType,
targetChartType
} = params;
for (const { expression, targetAxisTypes } of retainedChartAxisThemeOverrideKeys) {
for (const existingAxisType of existingAxes.map((axis) => axis.type)) {
const value = this.retrieveChartOptionsThemeOverride(
existingChartOptions,
existingChartType,
["axes", existingAxisType, expression].join(".")
);
if (value !== void 0) {
for (const targetAxisType of targetAxisTypes) {
this.assignChartOptionsThemeOverride(
targetChartOptions,
targetChartType,
["axes", targetAxisType, expression].join("."),
value
);
}
}
}
}
}
getRetainedChartThemeOverrideKeys(existingChartType, targetChartType) {
const UNIVERSAL_PERSISTED_THEME_OVERRIDES = ["animation"];
const PERSISTED_CARTESIAN_CHART_THEME_OVERRIDES = ["zoom", "navigator"];
const chartSpecificThemeOverrideKeys = ((previousChartType, updatedChartType) => {
const expressions = new Array();
if (isCartesian(getSeriesType(previousChartType)) && isCartesian(getSeriesType(updatedChartType))) {
expressions.push(...PERSISTED_CARTESIAN_CHART_THEME_OVERRIDES);
}
return expressions;
})(existingChartType, targetChartType);
return [...UNIVERSAL_PERSISTED_THEME_OVERRIDES, ...chartSpecificThemeOverrideKeys];
}
getRetainedChartAxisThemeOverrideKeys(axisType, existingChartType, targetChartType) {
if (isCartesian(getSeriesType(existingChartType)) && isCartesian(getSeriesType(targetChartType))) {
const retainedKeys = this.getRetainedCartesianAxisThemeOverrideKeys(axisType);
return retainedKeys.map((expression) => ({ expression, targetAxisTypes: CARTESIAN_AXIS_TYPES }));
}
return [];
}
getRetainedCartesianAxisThemeOverrideKeys(axisType) {
const axisPositionSuffixes = axisType === "xAxis" ? ["", ".top", ".bottom"] : axisType === "yAxis" ? ["", ".left", ".right"] : ["", ".left", ".right", ".top", ".bottom"];
const PERSISTED_CARTESIAN_AXIS_THEME_OVERRIDES = ["crosshair"];
const expressions = new Array();
for (const expression of PERSISTED_CARTESIAN_AXIS_THEME_OVERRIDES) {
for (const axisPositionSuffix of axisPositionSuffixes) {
expressions.push(`${expression}${axisPositionSuffix}`);
}
}
return expressions;
}
getChartOption(expression) {
return get(this.getChart(), expression, void 0);
}
setChartThemeOverrides(properties) {
const chartType = this.getChartType();
const chartOptions = this.createChartOptions();
for (const { expression, value } of properties) {
this.assignChartOptionsThemeOverride(chartOptions, chartType, expression, value);
}
this.applyChartOptions(chartOptions);
}
applyChartOptions(chartOptions, options) {
if (Object.keys(chartOptions).length === 0)
return;
this.updateChart(chartOptions);
const shouldRaiseEvent = !options?.silent;
if (shouldRaiseEvent)
this.raiseChartOptionsChangedEvent();
}
awaitChartOptionUpdate(func) {
const chart = this.chartController.getChartProxy().getChart();
chart.waitForUpdate().then(() => func()).catch((e) => (0, import_ag_grid_community287._error)(108, { e }));
}
getAxisProperty(expression) {
return get(this.getChart().axes?.[0], expression, void 0);
}
setAxisThemeOverrides(properties) {
const chart = this.getChart();
const chartType = this.getChartType();
const chartOptions = this.createChartOptions();
for (const { expression, value } of properties) {
const relevantAxes = chart.axes?.filter((axis) => {
const parts = expression.split(".");
let current = axis;
for (const part of parts) {
if (!(part in current)) {
return false;
}
current = current[part];
}
return true;
});
if (!relevantAxes)
continue;
for (const axis of relevantAxes) {
if (!this.isValidAxisType(axis))
continue;
this.assignChartAxisThemeOverride(chartOptions, chartType, axis.type, null, expression, value);
}
}
this.applyChartOptions(chartOptions);
}
getCartesianAxisProperty(axisType, expression) {
const axes = this.getChartAxes();
const axis = this.getCartesianAxis(axes, axisType);
return get(axis, expression, void 0);
}
getCartesianAxisThemeOverride(axisType, expression) {
const axes = this.getChartAxes();
const chartAxis = this.getCartesianAxis(axes, axisType);
if (!chartAxis || !this.isValidAxisType(chartAxis))
return void 0;
const chartType = this.getChartType();
const chartOptions = this.getChart().getOptions();
return this.retrieveChartAxisThemeOverride(
chartOptions,
chartType,
chartAxis.type,
axisType === "yAxis" ? ["left", "right"] : ["bottom", "top"],
expression
);
}
setCartesianAxisThemeOverrides(axisType, properties) {
const axes = this.getChartAxes();
const chartAxis = this.getCartesianAxis(axes, axisType);
if (!chartAxis || !this.isValidAxisType(chartAxis))
return;
const chartType = this.getChartType();
const chartOptions = this.createChartOptions();
for (const { expression, value } of properties) {
this.assignChartAxisThemeOverride(
chartOptions,
chartType,
chartAxis.type,
axisType === "yAxis" ? ["left", "right"] : ["bottom", "top"],
expression,
value
);
}
this.applyChartOptions(chartOptions);
}
setCartesianAxisOptions(axisType, properties) {
this.updateCartesianAxisOptions(axisType, (chartOptions, axes, chartAxis) => {
const axisIndex = axes.indexOf(chartAxis);
for (const { expression, value } of properties) {
this.assignChartOption(chartOptions, `axes.${axisIndex}.${expression}`, value);
}
});
}
updateCartesianAxisOptions(axisType, updateFunc) {
const existingChartOptions = this.getChart().getOptions();
const axisOptions = "axes" in existingChartOptions ? existingChartOptions.axes : void 0;
if (!existingChartOptions || !axisOptions)
return;
const axes = this.getChartAxes();
const chartAxis = this.getCartesianAxis(axes, axisType);
if (!chartAxis)
return;
const chartOptions = this.createChartOptions();
chartOptions.axes = axisOptions;
updateFunc(chartOptions, axes, chartAxis, existingChartOptions);
this.applyChartOptions(chartOptions);
}
setCartesianCategoryAxisType(axisType, value) {
this.updateCartesianAxisOptions(axisType, (chartOptions, _axes, chartAxis, existingChartOptions) => {
const chartType = this.getChartType();
this.assignPersistedAxisOverrides({
existingAxes: [chartAxis],
retainedChartAxisThemeOverrideKeys: this.getRetainedChartAxisThemeOverrideKeys(
axisType,
chartType,
chartType
),
existingChartOptions,
targetChartOptions: chartOptions,
existingChartType: chartType,
targetChartType: chartType
});
this.assignChartOption(chartOptions, `axes.0.type`, value);
this.chartController.setCategoryAxisType(value);
});
}
getCartesianAxis(axes, axisType) {
if (axes.length < 2) {
return void 0;
}
switch (axisType) {
case "xAxis":
return axes[0].direction === "x" ? axes[0] : axes[1];
case "yAxis":
return axes[1].direction === "y" ? axes[1] : axes[0];
}
}
getSeriesOption(seriesType, expression, calculated) {
const series = this.getChart().series.find((s) => isMatchingSeries(seriesType, s));
return get(calculated ? series : series?.properties.toJson(), expression, void 0);
}
setSeriesOptions(seriesType, properties) {
const chartOptions = this.createChartOptions();
for (const { expression, value } of properties) {
this.assignChartOptionsSeriesThemeOverride(chartOptions, seriesType, `series.${expression}`, value);
}
this.applyChartOptions(chartOptions);
}
getPairedMode() {
return this.chartController.getChartProxy().isPaired();
}
setPairedMode(paired) {
this.chartController.getChartProxy().setPaired(paired);
}
getChartAxes() {
const chart = this.getChart();
return chart.axes ?? [];
}
retrieveChartAxisThemeOverride(chartOptions, chartType, axisType, axisPositions, expression) {
if (axisPositions) {
for (const axisPosition of axisPositions) {
const value = this.retrieveChartOptionsThemeOverride(
chartOptions,
chartType,
["axes", axisType, axisPosition, ...expression ? [expression] : []].join(".")
);
if (value === void 0)
continue;
return value;
}
} else {
return this.retrieveChartOptionsThemeOverride(
chartOptions,
chartType,
["axes", axisType, ...expression ? [expression] : []].join(".")
);
}
}
assignChartAxisThemeOverride(chartOptions, chartType, axisType, axisPositions, expression, value) {
if (axisPositions) {
for (const axisPosition of axisPositions) {
this.assignChartOptionsThemeOverride(
chartOptions,
chartType,
["axes", axisType, axisPosition, ...expression ? [expression] : []].join("."),
value
);
}
} else {
this.assignChartOptionsThemeOverride(
chartOptions,
chartType,
["axes", axisType, ...expression ? [expression] : []].join("."),
value
);
}
}
isValidAxisType(chartAxis) {
return VALID_AXIS_TYPES.includes(chartAxis.type);
}
getChartType() {
return this.chartController.getChartType();
}
getChart() {
return this.chartController.getChartProxy().getChart();
}
updateChart(chartOptions) {
const chartRef = this.chartController.getChartProxy().getChartRef();
chartRef.skipAnimations();
chartRef.updateDelta(chartOptions);
}
createChartOptions() {
const chartOptions = {
theme: {
overrides: {}
}
};
return chartOptions;
}
retrieveChartOptionsThemeOverride(chartOptions, chartType, expression) {
const chartSeriesTypes = this.getChartThemeOverridesSeriesTypeKeys(chartType);
for (const seriesType of chartSeriesTypes) {
const value = this.retrieveChartOptionsSeriesThemeOverride(chartOptions, seriesType, expression);
if (value === void 0)
continue;
return value;
}
return void 0;
}
assignChartOptionsThemeOverride(chartOptions, chartType, expression, value) {
const chartSeriesTypes = this.getChartThemeOverridesSeriesTypeKeys(chartType);
for (const seriesType of chartSeriesTypes) {
this.assignChartOptionsSeriesThemeOverride(chartOptions, seriesType, expression, value);
}
}
retrieveChartOptionsSeriesThemeOverride(chartOptions, seriesType, expression) {
return this.retrieveChartOption(
chartOptions,
["theme", "overrides", seriesType, ...expression ? [expression] : []].join(".")
);
}
assignChartOptionsSeriesThemeOverride(chartOptions, seriesType, expression, value) {
this.assignChartOption(
chartOptions,
["theme", "overrides", seriesType, ...expression ? [expression] : []].join("."),
value
);
}
getChartThemeOverridesSeriesTypeKeys(chartType) {
const chartSeriesTypes = this.chartController.getChartSeriesTypes(chartType);
if (this.chartController.isComboChart()) {
chartSeriesTypes.push("common");
}
return chartSeriesTypes;
}
retrieveChartOption(chartOptions, expression) {
return get(chartOptions, expression, void 0);
}
assignChartOption(chartOptions, expression, value) {
set(chartOptions, expression, value);
}
raiseChartOptionsChangedEvent() {
const chartModel = this.chartController.getChartModel();
this.eventSvc.dispatchEvent({
type: "chartOptionsChanged",
chartId: chartModel.chartId,
chartType: chartModel.chartType,
chartThemeName: this.chartController.getChartThemeName(),
chartOptions: chartModel.chartOptions
});
}
};
function isMatchingSeries(seriesType, series) {
return isSeriesType(seriesType) && series.type === seriesType;
}
// packages/ag-grid-enterprise/src/charts/chartComp/gridChartComp.ts
var GridChartComp = class extends import_ag_grid_community288.Component {
constructor(params) {
super(
/* html */
`
<div style="height: 100%; width: 100%;">
<div class="ag-chart" data-ref="eWrapper">
<div data-ref="eChartContainer" class="ag-chart-components-wrapper ag-chart-menu-hidden">
<div data-ref="eChart" class="ag-chart-canvas-wrapper"></div>
<div data-ref="eEmpty" class="ag-chart-empty-text ag-unselectable"></div>
</div>
<div data-ref="eMenuContainer" class="ag-chart-docked-container"></div>
</div>
</div>
`
);
this.eChart = import_ag_grid_community288.RefPlaceholder;
this.eWrapper = import_ag_grid_community288.RefPlaceholder;
this.eChartContainer = import_ag_grid_community288.RefPlaceholder;
this.eMenuContainer = import_ag_grid_community288.RefPlaceholder;
this.eEmpty = import_ag_grid_community288.RefPlaceholder;
this.params = params;
}
wireBeans(beans) {
this.crossFilterService = beans.chartCrossFilterSvc;
this.chartTranslation = beans.chartTranslation;
this.chartMenuSvc = beans.chartMenuSvc;
this.focusSvc = beans.focusSvc;
this.popupSvc = beans.popupSvc;
this.enterpriseChartProxyFactory = beans.enterpriseChartProxyFactory;
this.environment = beans.environment;
}
postConstruct() {
const modelParams = {
...this.params,
chartType: getCanonicalChartType(this.params.chartType),
chartThemeName: this.getThemeName()
};
const isRtl = this.gos.get("enableRtl");
this.eWrapper.classList.add(isRtl ? "ag-rtl" : "ag-ltr");
const model = this.createBean(new ChartDataModel(modelParams));
this.chartController = this.createManagedBean(new ChartController(model));
this.chartOptionsService = this.createManagedBean(new ChartOptionsService(this.chartController));
this.validateCustomThemes();
this.createChart();
if (this.params.insideDialog) {
this.addDialog();
} else {
this.addManagedEventListeners({
gridStylesChanged: this.updateTheme.bind(this)
});
this.updateTheme();
}
this.addMenu();
this.addManagedElementListeners(this.getGui(), { focusin: this.setActiveChartCellRange.bind(this) });
this.addManagedListeners(this.chartController, { chartModelUpdate: this.update.bind(this) });
this.addManagedPropertyListeners(
["chartThemeOverrides", "chartThemes"],
this.reactivePropertyUpdate.bind(this)
);
this.update();
this.raiseChartCreatedEvent();
}
updateTheme() {
this.environment.applyThemeClasses(this.getGui());
}
createChart() {
let chartInstance = void 0;
if (this.chartProxy) {
chartInstance = this.chartProxy.destroy({ keepChartInstance: true });
}
const crossFilterCallback = (event, reset) => {
const ctx = this.params.crossFilteringContext;
ctx.lastSelectedChartId = reset ? "" : this.chartController.getChartId();
if (reset) {
this.params.crossFilteringResetCallback();
}
this.crossFilterService.filter(event, reset);
};
const chartType = this.chartController.getChartType();
const chartProxyParams = {
agChartsExports: this.beans.agChartsExports,
chartType,
chartInstance,
getChartThemeName: this.getChartThemeName.bind(this),
getChartThemes: this.getChartThemes.bind(this),
customChartThemes: this.gos.get("customChartThemes"),
styleNonce: this.gos.get("styleNonce"),
getGridOptionsChartThemeOverrides: () => this.getGridOptionsChartThemeOverrides(),
getExtraPaddingDirections: () => this.chartMenu?.getExtraPaddingDirections() ?? [],
apiChartThemeOverrides: this.params.chartThemeOverrides,
crossFiltering: this.params.crossFiltering ?? false,
crossFilterCallback,
parentElement: this.eChart,
grouping: this.chartController.isGrouping(),
chartThemeToRestore: this.params.chartThemeName,
chartOptionsToRestore: this.params.chartOptionsToRestore,
chartPaletteToRestore: this.params.chartPaletteToRestore,
seriesChartTypes: this.chartController.getSeriesChartTypes(),
suppressFieldDotNotation: this.gos.get("suppressFieldDotNotation"),
translate: (toTranslate) => this.chartTranslation.translate(toTranslate),
context: (0, import_ag_grid_community288._addGridCommonParams)(this.gos, {})
};
this.params.chartOptionsToRestore = void 0;
this.chartType = chartType;
this.chartProxy = this.createChartProxy(chartProxyParams);
if (!this.chartProxy) {
(0, import_ag_grid_community288._warn)(138, { chartType: chartProxyParams.chartType });
return;
}
this.chartController.setChartProxy(this.chartProxy);
this.createMenuContext();
}
createMenuContext() {
if (this.chartMenuContext) {
return;
}
const chartMenuParamsFactory = this.createManagedBean(
new ChartMenuParamsFactory(this.chartOptionsService.getChartThemeOverridesProxy())
);
const chartAxisMenuParamsFactory = this.createManagedBean(
new ChartMenuParamsFactory(this.chartOptionsService.getAxisThemeOverridesProxy())
);
this.chartMenuContext = {
chartController: this.chartController,
chartOptionsService: this.chartOptionsService,
chartMenuParamsFactory,
chartAxisMenuParamsFactory
};
}
getChartThemeName() {
return this.chartController.getChartThemeName();
}
getChartThemes() {
return this.chartController.getThemeNames();
}
getGridOptionsChartThemeOverrides() {
return this.gos.get("chartThemeOverrides");
}
createChartProxy(chartProxyParams) {
const { chartType } = chartProxyParams;
switch (chartType) {
case "column":
case "bar":
case "groupedColumn":
case "stackedColumn":
case "normalizedColumn":
case "groupedBar":
case "stackedBar":
case "normalizedBar":
return new BarChartProxy(chartProxyParams);
case "pie":
case "donut":
case "doughnut":
return new PieChartProxy(chartProxyParams);
case "area":
case "stackedArea":
case "normalizedArea":
return new AreaChartProxy(chartProxyParams);
case "line":
case "stackedLine":
case "normalizedLine":
return new LineChartProxy(chartProxyParams);
case "scatter":
case "bubble":
return new ScatterChartProxy(chartProxyParams);
case "columnLineCombo":
case "areaColumnCombo":
case "customCombo":
return new ComboChartProxy(chartProxyParams);
}
const enterpriseChartProxy = this.enterpriseChartProxyFactory?.createChartProxy(chartProxyParams);
if (!enterpriseChartProxy) {
throw (0, import_ag_grid_community288._errMsg)(251, { chartType });
}
return enterpriseChartProxy;
}
addDialog() {
const title = this.chartTranslation.translate(this.params.pivotChart ? "pivotChartTitle" : "rangeChartTitle");
const { width, height } = this.getBestDialogSize();
const afterGuiAttached = this.params.focusDialogOnOpen ? () => setTimeout(() => (0, import_ag_grid_community288._focusInto)(this.getGui())) : void 0;
this.chartDialog = new AgDialog({
resizable: true,
movable: true,
maximizable: true,
title,
width,
height,
component: this,
centered: true,
closable: true,
afterGuiAttached,
postProcessPopupParams: {
type: "chart"
}
});
this.createBean(this.chartDialog);
this.chartDialog.addEventListener("destroyed", () => {
this.destroy();
this.chartMenuSvc.hideAdvancedSettings();
const lastFocusedCell = this.focusSvc.getFocusedCell();
setTimeout(() => {
if (this.focusSvc.isAlive()) {
if (lastFocusedCell) {
this.focusSvc.setFocusedCell({ ...lastFocusedCell, forceBrowserFocus: true });
} else {
(0, import_ag_grid_community288._focusGridInnerElement)(this.beans);
}
}
});
});
}
getBestDialogSize() {
const popupParent = this.popupSvc.getPopupParent();
const maxWidth = (0, import_ag_grid_community288._getAbsoluteWidth)(popupParent) * 0.75;
const maxHeight = (0, import_ag_grid_community288._getAbsoluteHeight)(popupParent) * 0.75;
const ratio = 0.553;
const chart = this.chartProxy.getChart();
let width = this.params.insideDialog ? 850 : chart.width;
let height = this.params.insideDialog ? 470 : chart.height;
if (width > maxWidth || height > maxHeight) {
width = Math.min(width, maxWidth);
height = Math.round(width * ratio);
if (height > maxHeight) {
height = maxHeight;
width = Math.min(width, Math.round(height / ratio));
}
}
return { width, height };
}
addMenu() {
if (!this.params.crossFiltering) {
this.chartMenu = this.createBean(
new ChartMenu(this.eChartContainer, this.eMenuContainer, this.chartMenuContext)
);
this.eChartContainer.appendChild(this.chartMenu.getGui());
}
}
update(params) {
if (params?.chartId) {
const validUpdate = this.chartController.update(params);
if (!validUpdate) {
return;
}
}
const updatedChartType = this.chartTypeChanged(params);
const persistedThemeOverrides = updatedChartType || this.chartEmpty ? ((updatedChartType2) => {
const currentChartType = this.chartType;
const targetChartType = updatedChartType2;
const existingChartInstance = this.chartProxy.getChart();
const existingChartOptions = existingChartInstance?.getOptions();
const existingAxes = existingChartInstance?.axes;
return this.chartOptionsService.getPersistedChartThemeOverrides(
existingChartOptions,
existingAxes,
currentChartType,
targetChartType ?? currentChartType
);
})(updatedChartType) : void 0;
if (updatedChartType)
this.createChart();
if (persistedThemeOverrides && params?.chartThemeOverrides) {
(0, import_ag_grid_community288._mergeDeep)(persistedThemeOverrides, params.chartThemeOverrides);
}
const updatedThemeOverrides = persistedThemeOverrides ?? params?.chartThemeOverrides;
this.updateChart(updatedThemeOverrides);
if (params?.chartId) {
this.chartProxy.getChart().waitForUpdate().then(() => {
this.chartController.raiseChartApiUpdateEvent();
});
}
}
updateChart(updatedOverrides) {
const { chartProxy } = this;
const selectedCols = this.chartController.getSelectedValueColState();
const data = this.chartController.getChartData();
const chartEmpty = this.handleEmptyChart(data, selectedCols.length);
this.chartEmpty = chartEmpty;
if (chartEmpty) {
if (updatedOverrides)
this.chartController.updateThemeOverrides(updatedOverrides);
return;
}
const chartUpdateParams = this.chartController.getChartUpdateParams(updatedOverrides);
chartProxy.update(chartUpdateParams);
this.chartProxy.getChart().waitForUpdate().then(() => {
this.chartController.raiseChartUpdatedEvent();
});
}
chartTypeChanged(updateParams) {
const [currentType, updatedChartType] = [this.chartController.getChartType(), updateParams?.chartType];
const targetChartType = updatedChartType ? getCanonicalChartType(updatedChartType) : void 0;
if (this.chartType !== currentType)
return targetChartType ?? currentType;
if (targetChartType && currentType !== targetChartType)
return targetChartType;
return null;
}
getChartModel() {
return this.chartController.getChartModel();
}
getChartImageDataURL(fileFormat) {
return this.chartProxy.getChartImageDataURL(fileFormat);
}
handleEmptyChart(data, numFields) {
const pivotModeDisabled = this.chartController.isPivotChart() && !this.chartController.isPivotMode();
const chartType = this.chartController.getChartType();
let minFieldsRequired = 1;
if (this.chartController.isActiveXYChart()) {
minFieldsRequired = chartType === "bubble" ? 3 : 2;
} else if (isHierarchical(getSeriesType(chartType))) {
minFieldsRequired = 0;
}
const isEmptyChart = numFields < minFieldsRequired || data.length === 0;
if (this.eChart) {
const isEmpty = pivotModeDisabled || isEmptyChart;
(0, import_ag_grid_community288._setDisplayed)(this.eChart, !isEmpty);
(0, import_ag_grid_community288._setDisplayed)(this.eEmpty, isEmpty);
}
if (pivotModeDisabled) {
this.eEmpty.textContent = this.chartTranslation.translate("pivotChartRequiresPivotMode");
return true;
}
if (isEmptyChart) {
this.eEmpty.textContent = this.chartTranslation.translate("noDataToChart");
return true;
}
return false;
}
downloadChart(dimensions, fileName, fileFormat) {
this.chartProxy.downloadChart(dimensions, fileName, fileFormat);
}
openChartToolPanel(panel) {
const menuPanel = panel ? CHART_TOOL_PANEL_MENU_OPTIONS[panel] : panel;
this.chartMenu.showMenu({ panel: menuPanel });
}
closeChartToolPanel() {
this.chartMenu.hideMenu();
}
getChartId() {
return this.chartController.getChartId();
}
getUnderlyingChart() {
return this.chartProxy.getChartRef();
}
crossFilteringReset() {
this.chartProxy.crossFilteringReset();
}
setMaximized(maximized) {
this.chartDialog?.setMaximized(maximized);
}
setActiveChartCellRange(focusEvent) {
if (this.getGui().contains(focusEvent.relatedTarget)) {
return;
}
this.chartController.setChartRange(true);
}
getThemeName() {
const availableChartThemes = this.gos.get("chartThemes") || DEFAULT_THEMES;
if (availableChartThemes.length === 0) {
throw new Error((0, import_ag_grid_community288._errMsg)(254));
}
const { chartThemeName } = this.params;
return availableChartThemes.includes(chartThemeName) ? chartThemeName : availableChartThemes[0];
}
getAllKeysInObjects(objects) {
const allValues = {};
objects.filter((obj) => obj != null).forEach((obj) => {
Object.keys(obj).forEach((key) => allValues[key] = null);
});
return Object.keys(allValues);
}
validateCustomThemes() {
const suppliedThemes = this.getChartThemes();
const customChartThemes = this.gos.get("customChartThemes");
if (customChartThemes) {
this.getAllKeysInObjects([customChartThemes]).forEach((customThemeName) => {
if (!suppliedThemes.includes(customThemeName)) {
(0, import_ag_grid_community288._warn)(139, { customThemeName });
}
});
}
}
reactivePropertyUpdate() {
this.chartController.setChartThemeName(this.getThemeName(), true);
const chartId = this.getChartId();
const modelType = this.chartController.isCrossFilterChart() ? "crossFilter" : this.getChartModel().modelType;
const chartThemeOverrides = this.gos.get("chartThemeOverrides") || {};
this.update({
type: `${modelType}ChartUpdate`,
chartId,
chartThemeOverrides
});
}
raiseChartCreatedEvent() {
this.chartProxy.getChart().waitForUpdate().then(() => {
this.eventSvc.dispatchEvent({
type: "chartCreated",
chartId: this.chartController.getChartId()
});
});
}
raiseChartDestroyedEvent() {
this.eventSvc.dispatchEvent({
type: "chartDestroyed",
chartId: this.chartController.getChartId()
});
}
destroy() {
super.destroy();
if (this.chartProxy) {
this.chartProxy.destroy();
}
this.destroyBean(this.chartMenu);
if (this.chartDialog && this.chartDialog.isAlive()) {
this.destroyBean(this.chartDialog);
}
this.onDestroyColorSchemeChangeListener?.();
const eGui = this.getGui();
(0, import_ag_grid_community288._clearElement)(eGui);
(0, import_ag_grid_community288._removeFromParent)(eGui);
this.raiseChartDestroyedEvent();
}
};
// packages/ag-grid-enterprise/src/charts/chartModelMigration.ts
var import_ag_grid_community289 = require("ag-grid-community");
var DEBUG = false;
function upgradeChartModel(model) {
const originalVersion = model.version;
if (model.version == null) {
model.version = heuristicVersionDetection(model);
}
model = migrateIfBefore("23.0.0", model, migrateV23);
model = migrateIfBefore("24.0.0", model, migrateV24);
model = migrateIfBefore("25.1.0", model, migrateV25_1);
model = migrateIfBefore("26.0.0", model, migrateV26);
model = migrateIfBefore("26.1.0", model, migrateV26_1);
model = migrateIfBefore("26.2.0", model, migrateV26_2);
model = migrateIfBefore("28.0.0", model, migrateV28);
model = migrateIfBefore("28.2.0", model, migrateV28_2);
model = migrateIfBefore("29.0.0", model, migrateV29);
model = migrateIfBefore("29.1.0", model, migrateV29_1);
model = migrateIfBefore("29.2.0", model, migrateV29_2);
model = migrateIfBefore("30.0.0", model, migrateV30);
model = migrateIfBefore("31.0.0", model, migrateV31);
model = migrateIfBefore("32.0.0", model, migrateV32);
model = migrateIfBefore("33.0.0", model, migrateV33);
model = migrateIfBefore("34.0.0", model, migrateV34);
model = cleanup(model);
model = migrateIfBefore(VERSION, model, (m) => m);
if (DEBUG && originalVersion !== model.version) {
console.log("AG Grid: ChartModel migration complete", { model });
}
return model;
}
function migrateV23(model) {
model = jsonRename("chartOptions.legend.item.marker.type", "shape", model);
model = jsonRename("chartOptions.seriesDefaults.marker.type", "shape", model);
model = jsonRename("chartOptions.legend.padding", "spacing", model);
return model;
}
function migrateV24(model) {
model = jsonDelete("chartOptions.seriesDefaults.marker.minSize", model);
const {
chartType,
chartPalette,
// Migrate.
chartOptions: { xAxis, yAxis, ...chartOptions },
...chartModel
} = model;
const axesTypes = getLegacyAxisType(chartType);
const axes = axesTypes?.map((type, i) => ({
type,
...i === 0 ? xAxis : yAxis
}));
const LEGACY_PALETTES = {
borneo: "ag-default",
material: "ag-material",
bright: "ag-vivid"
};
return {
chartType,
chartThemeName: LEGACY_PALETTES[chartPalette] ?? "ag-default",
chartOptions: {
...chartOptions,
axes,
xAxis,
yAxis
},
...chartModel
};
}
function migrateV25_1(model) {
model = jsonRename("chartOptions.seriesDefaults.label.minRequiredAngle", "minAngle", model);
return model;
}
function migrateV26(model) {
const highlightOptUpdate = ({ dimOpacity, ...opts }) => ({
...opts,
...dimOpacity != null ? { series: { dimOpacity } } : {}
});
model = jsonMutate("chartOptions.seriesDefaults.highlightStyle", model, highlightOptUpdate);
model = jsonDelete("chart", model);
model = jsonDelete("chartOptions.seriesDefaults.tooltipClass", model);
model = jsonDelete("chartOptions.seriesDefaults.tooltipTracking", model);
model = jsonDeleteDefault("chartOptions.axes[].label.rotation", 0, model);
model = jsonDeleteDefault("chartOptions.axes[].label.rotation", 335, model);
return model;
}
function migrateV26_1(model) {
const highlightOptUpdate = ({ item, series, ...opts }) => ({
item: { ...opts, ...item },
...series ? { series } : {}
});
model = jsonMutate("chartOptions.seriesDefaults.highlightStyle", model, highlightOptUpdate);
model = jsonMutate("chartOptions.series[].highlightStyle", model, highlightOptUpdate);
return model;
}
function migrateV26_2(model) {
model = jsonMove("chartOptions.seriesDefaults.fill.opacity", "chartOptions.seriesDefaults.fillOpacity", model);
model = jsonMove("chartOptions.seriesDefaults.stroke.opacity", "chartOptions.seriesDefaults.strokeOpacity", model);
model = jsonMove("chartOptions.seriesDefaults.stroke.width", "chartOptions.seriesDefaults.strokeWidth", model);
model = jsonDelete("chartOptions.seriesDefaults.fill", model);
model = jsonDelete("chartOptions.seriesDefaults.stroke", model);
model = jsonDelete("chartOptions.seriesDefaults.callout.colors", model);
model = jsonDelete("chartOptions.xAxis", model);
model = jsonDelete("chartOptions.yAxis", model);
const {
chartType: providedChartType,
// disable no-unused-vars because `series` is required here, even though
// unused, because it serves to take the `series` key out of otherChartOptions
// eslint-disable-next-line @typescript-eslint/no-unused-vars
chartOptions: { axes, series, seriesDefaults, ...otherChartOptions },
...otherModelProps
} = model;
const chartType = getCanonicalChartType(providedChartType);
const seriesType = getSeriesType(chartType);
const seriesTypes = [seriesType];
const chartTypeMixin = {};
if (!isPieChartSeries(seriesType)) {
const minimalAxis = { top: {}, bottom: {}, left: {}, right: {} };
const updatedAxes = axes.map(({ type, ...axisProps }) => ({
[type]: { ...minimalAxis, ...axisProps }
})).reduce(merge, {});
ALL_AXIS_TYPES.filter((v) => updatedAxes[v] == null).forEach((v) => {
updatedAxes[v] = { ...minimalAxis };
});
chartTypeMixin.axes = updatedAxes;
}
const updatedChartOptions = seriesTypes.map((t) => ({
[t]: {
...chartTypeMixin,
series: seriesDefaults,
...otherChartOptions
}
})).reduce(merge, {});
model = {
...otherModelProps,
chartType,
chartOptions: updatedChartOptions
};
return model;
}
function migrateV28(model) {
model = jsonDelete("chartOptions.*.title.padding", model);
model = jsonDelete("chartOptions.*.subtitle.padding", model);
model = jsonDelete("chartOptions.*.axes.*.title.padding", model);
model = jsonBackfill("chartOptions.*.axes.*.title.enabled", false, model);
return model;
}
function migrateV28_2(model) {
model = jsonRename("chartOptions.pie.series.callout", "calloutLine", model);
model = jsonRename("chartOptions.pie.series.label", "calloutLabel", model);
model = jsonRename("chartOptions.pie.series.labelKey", "sectorLabelKey", model);
model = jsonRename("chartOptions.pie.series.labelName", "sectorLabelName", model);
model = jsonRename("chartOptions.donut.series.callout", "calloutLine", model);
model = jsonRename("chartOptions.donut.series.label", "calloutLabel", model);
model = jsonRename("chartOptions.donut.series.labelKey", "sectorLabelKey", model);
model = jsonRename("chartOptions.donut.series.labelName", "sectorLabelName", model);
return model;
}
function migrateV29(model) {
model = jsonMoveIfMissing("chartOptions.scatter.series.fill", "chartOptions.scatter.series.marker.fill", model);
model = jsonMoveIfMissing(
"chartOptions.scatter.series.fillOpacity",
"chartOptions.scatter.series.marker.fillOpacity",
model
);
model = jsonMoveIfMissing("chartOptions.scatter.series.stroke", "chartOptions.scatter.series.marker.stroke", model);
model = jsonMoveIfMissing(
"chartOptions.scatter.series.strokeOpacity",
"chartOptions.scatter.series.marker.strokeOpacity",
model
);
model = jsonMoveIfMissing(
"chartOptions.scatter.series.strokeWidth",
"chartOptions.scatter.series.marker.strokeWidth",
model
);
model = jsonMove("chartOptions.scatter.series.paired", "chartOptions.scatter.paired", model);
return model;
}
function migrateV29_1(model) {
model = jsonDelete("chartOptions.axes[].tick.count", model);
return model;
}
function migrateV29_2(model) {
const tooltipOptUpdate = ({ tracking, ...opts }) => {
const output = { ...opts };
if (tracking === false) {
output.position ?? (output.position = { type: "pointer" });
output.range ?? (output.range = "nearest");
} else if (tracking === true) {
output.position ?? (output.position = { type: "node" });
output.range ?? (output.range = "nearest");
}
return output;
};
model = jsonMutate("chartOptions.*.tooltip", model, tooltipOptUpdate);
return model;
}
function migrateV30(model) {
model = jsonRename("chartOptions.pie.series.labelKey", "sectorLabelKey", model);
model = jsonRename("chartOptions.pie.series.labelName", "sectorLabelName", model);
model = migrateV29_1(model);
model = migrateV29_2(model);
model = jsonDelete("chartOptions.*.series.flipXY", model);
model = jsonAdd("chartOptions.common.legend.enabled", true, model);
model = jsonBackfill("chartOptions.common.legend.position", "right", model);
return model;
}
function migrateV31(model) {
const V30_LEGACY_PALETTES = {
"ag-pastel": "ag-sheets",
"ag-solar": "ag-polychroma"
};
const updatedModel = jsonRename("chartOptions.column", "bar", model);
const chartThemeName = V30_LEGACY_PALETTES[updatedModel.chartThemeName] || updatedModel.chartThemeName;
return {
...updatedModel,
chartThemeName
};
}
function migrateV32(model) {
model = jsonMutateProperty("chartOptions.*.autoSize", true, model, (parent, targetProp) => {
if (parent[targetProp] === true) {
} else if (parent[targetProp] === false) {
parent["minHeight"] = 600;
parent["minWidth"] = 300;
}
delete parent[targetProp];
});
return model;
}
function migrateV33(model) {
model = jsonDelete("chartOptions.*.axes.category.label.format", model);
model = jsonDelete("chartOptions.*.axes.category.crosshair.label.format", model);
model = jsonDelete("chartOptions.*.axes.angle-category.label.format", model);
model = jsonDelete("chartOptions.*.axes.radius-category.label.format", model);
model = jsonRename("chartOptions.*.axes.*.label.padding", "spacing", model);
model = jsonRename("chartOptions.*.navigator.miniChart.label.padding", "spacing", model);
model = jsonDelete("chartOptions.*.axes.*.crossLines.label.className", model);
model = jsonMutateProperty("chartOptions.*.axes.*.crossLines.label.position", true, model, (parent, targetProp) => {
if (typeof parent[targetProp] === "string") {
parent[targetProp] = parent[targetProp].replace(/([A-Z])/, "-$1").toLowerCase();
}
});
model = jsonDelete("chartOptions.bullet", model);
model = jsonRenameEnumValues("chartOptions.bar.series.label.placement", model, {
inside: "inside-center",
outside: "inside-end"
});
model = jsonRenameEnumValues("chartOptions.waterfall.series.item.*.label.placement", model, {
inside: "inside-center",
start: "outside-start",
end: "outside-end"
});
model = jsonDelete("chartOptions.*.navigator.min", model);
model = jsonDelete("chartOptions.*.navigator.max", model);
model = jsonDelete("chartOptions.*.zoom.ratioX", model);
model = jsonDelete("chartOptions.*.zoom.ratioY", model);
model = jsonDelete("chartOptions.*.zoom.rangeX", model);
model = jsonDelete("chartOptions.*.zoom.rangeY", model);
return model;
}
function migrateV34(model) {
const highlightUpdate = (parent, targetProp) => {
const highlightStyle = parent[targetProp];
if (highlightStyle == null)
return;
const highlight = {};
if (highlightStyle.item) {
highlight.highlightedItem = highlightStyle.item;
}
if (highlightStyle.series) {
const { dimOpacity, ...seriesOpts } = highlightStyle.series;
if (dimOpacity != null) {
highlight.unhighlightedSeries = { opacity: dimOpacity };
}
if (Object.keys(seriesOpts).length > 0) {
highlight.highlightedSeries = seriesOpts;
}
}
delete parent[targetProp];
parent.highlight = highlight;
};
jsonMutateProperty("chartOptions.series[].highlightStyle", true, model, highlightUpdate);
return model;
}
function cleanup(model) {
model = jsonDelete("chartOptions.*.width", model);
model = jsonDelete("chartOptions.*.height", model);
model = jsonBackfill("chartOptions.*.axes.category.label.autoRotate", true, model);
return model;
}
function heuristicVersionDetection(model) {
const modelAny = model;
if (model.version != null) {
return model.version;
}
const hasKey = (obj, ...keys) => {
return Object.keys(obj || {}).some((k) => keys.includes(k));
};
const chartOptions = modelAny.chartOptions;
const seriesOptions = hasKey(chartOptions, "seriesDefaults") ? chartOptions?.seriesDefaults : chartOptions?.[Object.keys(chartOptions)[0]];
const hints = {
"27.0.0": hasKey(modelAny, "seriesChartTypes"),
"26.2.0": !hasKey(chartOptions, "seriesDefaults"),
"26.1.0": hasKey(seriesOptions?.highlightStyle, "item"),
"26.0.0": hasKey(seriesOptions?.highlightStyle, "series"),
// '26.0.0': modelAny.chart === undefined,
"25.1.0": hasKey(seriesOptions?.label, "minAngle"),
"25.0.0": hasKey(modelAny, "modelType", "aggFunc", "unlinkChart", "suppressChartRanges") || hasKey(seriesOptions, "lineDash", "lineDashOffset"),
"24.0.0": hasKey(modelAny, "chartThemeName", "chart") || hasKey(chartOptions, "series"),
"23.2.0": hasKey(chartOptions, "navigator"),
"23.0.0": hasKey(chartOptions?.legend?.item?.marker, "shape"),
"22.1.0": hasKey(modelAny, "chartPalette", "chartType")
};
const defaultVersion = "27.1.0";
const matchingHints = Object.entries(hints).filter(([_, match]) => match);
if (DEBUG)
console.log("AG Grid: ChartModel migration", { heuristicVersionCandidates: matchingHints });
const [heuristicVersion = defaultVersion] = matchingHints[0];
if (DEBUG)
console.log("AG Grid: ChartModel migration", { heuristicVersion });
return heuristicVersion;
}
function migrateIfBefore(maxVersion, model, migration) {
if (versionNumber(maxVersion) > versionNumber(model.version)) {
if (DEBUG)
console.log("AG Grid: ChartModel migration", { migratingTo: maxVersion });
const result = migration(model);
result.version = maxVersion;
if (DEBUG)
console.log("AG Grid: ChartModel migration", { migratedTo: maxVersion, result });
return result;
}
return model;
}
function versionParts(versionRaw) {
const version = versionRaw.includes("-beta") ? versionRaw.replace(/-beta.*/, "") : versionRaw;
const split = typeof version === "string" ? version.split(".").map((v) => Number(v)) : [];
if (split.length !== 3 || split.some((v) => isNaN(v))) {
throw new Error((0, import_ag_grid_community289._errMsg)(253, { version }));
}
return {
major: split[0],
minor: split[1],
patch: split[2]
};
}
function versionNumber(version) {
const { major, minor, patch } = versionParts(version);
return major * 1e4 + minor * 100 + patch;
}
function jsonDeleteDefault(path, defaultValue, json) {
return jsonMutateProperty(path, true, json, (parent, prop) => {
if (parent[prop] === defaultValue) {
delete parent[prop];
}
});
}
function jsonBackfill(path, defaultValue, json) {
return jsonMutateProperty(path, false, json, (parent, prop) => {
if (parent[prop] == null) {
parent[prop] = defaultValue;
}
});
}
function jsonAdd(path, value, json) {
if (typeof path === "string") {
path = path.split(".");
}
const nextPath = path[0];
if (path.length > 1) {
json[nextPath] = jsonAdd(path.slice(1), value, json[nextPath] ?? {});
}
const hasProperty = Object.keys(json).includes(nextPath);
if (!hasProperty) {
json[nextPath] = value;
}
return json;
}
function jsonMove(from, to, json) {
let valueToMove = void 0;
let valueFound = false;
json = jsonMutateProperty(from, true, json, (parent, prop) => {
valueFound = true;
valueToMove = parent[prop];
delete parent[prop];
});
if (!valueFound) {
return json;
}
return jsonMutateProperty(to, false, json, (parent, prop) => {
parent[prop] = valueToMove;
});
}
function jsonMoveIfMissing(from, to, json) {
let valueToMove = void 0;
let valueFound = false;
json = jsonMutateProperty(from, true, json, (parent, prop) => {
valueFound = true;
valueToMove = parent[prop];
delete parent[prop];
});
if (!valueFound) {
return json;
}
return jsonMutateProperty(to, false, json, (parent, prop) => {
if (parent[prop] === void 0) {
parent[prop] = valueToMove;
}
});
}
function jsonRename(path, renameTo, json) {
return jsonMutateProperty(path, true, json, (parent, prop) => {
parent[renameTo] = parent[prop];
delete parent[prop];
});
}
function jsonDelete(path, json) {
return jsonMutateProperty(path, true, json, (parent, prop) => delete parent[prop]);
}
function jsonMutateProperty(path, skipMissing, json, mutator) {
const pathElements = path instanceof Array ? path : path.split(".");
const parentPathElements = pathElements.slice(0, pathElements.length - 1);
const targetName = pathElements[pathElements.length - 1];
return jsonMutate(parentPathElements, json, (parent) => {
const hasProperty = Object.keys(parent).includes(targetName);
if (skipMissing && !hasProperty) {
return parent;
}
const result = { ...parent };
mutator(result, targetName);
return result;
});
}
function jsonMutate(path, json, mutator) {
const pathElements = path instanceof Array ? path : path.split(".");
json = { ...json };
if (pathElements.length === 0) {
return mutator(json);
} else if (pathElements[0].startsWith("{")) {
const pathOptions = pathElements[0].substring(1, pathElements[0].lastIndexOf("}")).split(",");
for (const pathOption of pathOptions) {
if (json[pathOption] != null) {
json[pathOption] = jsonMutate(pathElements.slice(1), json[pathOption], mutator);
}
}
} else if (pathElements[0].endsWith("[]")) {
const arrayName = pathElements[0].substring(0, path[0].indexOf("["));
if (json[arrayName] instanceof Array) {
json[arrayName] = json[arrayName].map((v) => jsonMutate(pathElements.slice(1), v, mutator));
}
} else if (pathElements[0] === "*") {
for (const jsonProp of Object.keys(json)) {
json[jsonProp] = jsonMutate(pathElements.slice(1), json[jsonProp], mutator);
}
} else if (json[pathElements[0]] != null) {
json[pathElements[0]] = jsonMutate(pathElements.slice(1), json[pathElements[0]], mutator);
}
return json;
}
function jsonRenameEnumValues(path, json, values) {
return jsonMutateProperty(path, true, json, (parent, targetProp) => {
if (typeof parent[targetProp] === "string") {
parent[targetProp] = values[targetProp] ?? targetProp;
}
});
}
var merge = (r, n) => ({ ...r, ...n });
// packages/ag-grid-enterprise/src/charts/chartService.ts
var ChartService = class extends import_ag_grid_community290.BeanStub {
constructor() {
super(...arguments);
this.beanName = "chartSvc";
// we destroy all charts bound to this grid when grid is destroyed. activeCharts contains all charts, including
// those in developer provided containers.
this.activeCharts = /* @__PURE__ */ new Set();
this.activeChartComps = /* @__PURE__ */ new Set();
// this shared (singleton) context is used by cross filtering in line and area charts
this.crossFilteringContext = {
lastSelectedChartId: ""
};
this.isEnterprise = () => this.agChartsExports.isEnterprise;
}
wireBeans(beans) {
this.visibleCols = beans.visibleCols;
this.rangeSvc = beans.rangeSvc;
this.agChartsExports = beans.agChartsExports;
}
updateChart(params) {
if (this.activeChartComps.size === 0) {
(0, import_ag_grid_community290._warn)(124);
return;
}
const chartComp = [...this.activeChartComps].find((chartComp2) => chartComp2.getChartId() === params.chartId);
if (!chartComp) {
(0, import_ag_grid_community290._warn)(125, { chartId: params.chartId });
return;
}
chartComp.update(params);
}
getChartModels() {
const models = [];
const versionedModel = (c) => {
return { ...c, version: VERSION };
};
this.activeChartComps.forEach((c) => models.push(versionedModel(c.getChartModel())));
return models;
}
getChartRef(chartId) {
let chartRef;
this.activeCharts.forEach((cr) => {
if (cr.chartId === chartId) {
chartRef = cr;
}
});
return chartRef;
}
getChartComp(chartId) {
let chartComp;
this.activeChartComps.forEach((comp) => {
if (comp.getChartId() === chartId) {
chartComp = comp;
}
});
return chartComp;
}
getChartImageDataURL(params) {
let url;
this.activeChartComps.forEach((c) => {
if (c.getChartId() === params.chartId) {
url = c.getChartImageDataURL(params.fileFormat);
}
});
return url;
}
downloadChart(params) {
const chartComp = Array.from(this.activeChartComps).find((c) => c.getChartId() === params.chartId);
chartComp?.downloadChart(params.dimensions, params.fileName, params.fileFormat);
}
openChartToolPanel(params) {
const chartComp = Array.from(this.activeChartComps).find((c) => c.getChartId() === params.chartId);
chartComp?.openChartToolPanel(params.panel);
}
closeChartToolPanel(chartId) {
const chartComp = Array.from(this.activeChartComps).find((c) => c.getChartId() === chartId);
chartComp?.closeChartToolPanel();
}
createChartFromCurrentRange(chartType = "groupedColumn", fromApi) {
const cellRange = this.getSelectedRange();
return this.createChart({ cellRange, chartType, focusDialogOnOpen: !fromApi });
}
restoreChart(model, chartContainer) {
if (!model) {
(0, import_ag_grid_community290._warn)(126);
return;
}
if (model.version !== VERSION) {
model = upgradeChartModel(model);
}
let cellRange;
let pivotChart;
let suppressChartRanges;
let chartPaletteToRestore;
if (model.modelType === "pivot") {
this.gos.updateGridOptions({ options: { pivotMode: true }, source: "pivotChart" });
cellRange = this.createCellRange(void 0, true);
pivotChart = true;
suppressChartRanges = true;
} else {
cellRange = this.createCellRange(model.cellRange);
chartPaletteToRestore = model.chartPalette;
suppressChartRanges = model.suppressChartRanges;
}
if (!cellRange) {
return;
}
return this.createChart({
...model,
cellRange,
pivotChart,
suppressChartRanges,
chartContainer,
chartOptionsToRestore: model.chartOptions,
chartPaletteToRestore
});
}
createRangeChart(params, fromApi) {
const cellRange = this.createCellRange(params.cellRange);
if (!cellRange) {
return;
}
return this.createChart({
...params,
cellRange,
focusDialogOnOpen: !fromApi
});
}
createPivotChart(params, fromApi) {
this.gos.updateGridOptions({ options: { pivotMode: true }, source: "pivotChart" });
const cellRange = this.createCellRange(void 0, true);
if (!cellRange) {
return;
}
return this.createChart({
...params,
cellRange,
pivotChart: true,
suppressChartRanges: true,
focusDialogOnOpen: !fromApi
});
}
createCrossFilterChart(params, fromApi) {
const cellRange = this.createCellRange(params.cellRange);
if (!cellRange) {
return;
}
const suppressChartRangesSupplied = typeof params.suppressChartRanges !== "undefined" && params.suppressChartRanges !== null;
const suppressChartRanges = suppressChartRangesSupplied ? params.suppressChartRanges : true;
return this.createChart({
...params,
cellRange,
suppressChartRanges,
crossFiltering: true,
focusDialogOnOpen: !fromApi
});
}
createChart(params) {
const validationResult = validateCreateParams(params, this.agChartsExports.isEnterprise);
if (!validationResult) {
return void 0;
}
params = validationResult === true ? params : validationResult;
const { chartType, chartContainer } = params;
const createChartContainerFunc = this.gos.getCallback("createChartContainer");
const gridChartParams = {
...params,
chartId: this.generateId(),
chartType: getCanonicalChartType(chartType),
insideDialog: !(chartContainer || createChartContainerFunc),
crossFilteringContext: this.crossFilteringContext,
crossFilteringResetCallback: () => this.activeChartComps.forEach((c) => c.crossFilteringReset())
};
const chartComp = new GridChartComp(gridChartParams);
this.createBean(chartComp);
const chartRef = this.createChartRef(chartComp);
if (chartContainer) {
chartContainer.appendChild(chartRef.chartElement);
} else if (createChartContainerFunc) {
createChartContainerFunc(chartRef);
} else {
chartComp.addEventListener("destroyed", () => {
this.activeChartComps.delete(chartComp);
this.activeCharts.delete(chartRef);
});
}
return chartRef;
}
createChartRef(chartComp) {
const chartRef = {
destroyChart: () => {
if (this.activeCharts.has(chartRef)) {
this.destroyBean(chartComp);
this.activeChartComps.delete(chartComp);
this.activeCharts.delete(chartRef);
}
},
focusChart: () => {
(0, import_ag_grid_community290._focusInto)(chartComp.getGui());
},
chartElement: chartComp.getGui(),
chart: chartComp.getUnderlyingChart(),
chartId: chartComp.getChartModel().chartId,
setMaximized: chartComp.setMaximized.bind(chartComp)
};
this.activeCharts.add(chartRef);
this.activeChartComps.add(chartComp);
return chartRef;
}
getSelectedRange() {
const ranges = this.rangeSvc?.getCellRanges();
if (!ranges || ranges.length === 0) {
return { columns: [] };
}
const uCols = /* @__PURE__ */ new Set();
let startRowIndex = Number.MAX_VALUE;
let endRowIndex = -Number.MAX_VALUE;
ranges.forEach(({ startRow: sr, endRow: er, columns: cols }) => {
if (!(sr && er)) {
return;
}
cols.forEach((col) => uCols.add(col));
let { rowIndex: sRowIndex, rowPinned: startRowPinned } = sr;
let { rowIndex: eRowIndex, rowPinned: endRowPinned } = er;
if (startRowPinned === "top") {
if (endRowPinned === "top") {
return;
}
sRowIndex = 0;
}
if (endRowPinned === "bottom") {
if (startRowPinned === "bottom") {
return;
}
eRowIndex = this.beans.pageBounds.getLastRow();
}
if (sRowIndex !== void 0) {
startRowIndex = Math.min(startRowIndex, sRowIndex);
}
if (eRowIndex !== void 0) {
endRowIndex = Math.max(endRowIndex, eRowIndex);
}
});
if (startRowIndex === Number.MAX_VALUE || endRowIndex === -Number.MAX_VALUE) {
return { columns: [] };
}
const columns = Array.from(uCols);
return {
// Don't specify id here, as it should be chart-specific
// but we don't have that context yet
columns,
startColumn: columns[0],
startRow: {
rowIndex: startRowIndex,
rowPinned: void 0
},
endRow: {
rowIndex: endRowIndex,
rowPinned: void 0
}
};
}
generateId() {
return `id-${Math.random().toString(36).substring(2, 18)}`;
}
createCellRange(cellRangeParams, allRange) {
const rangeParams = allRange ? {
rowStartIndex: null,
rowStartPinned: void 0,
rowEndIndex: null,
rowEndPinned: void 0,
columns: this.visibleCols.allCols.map((col) => col.getColId())
} : cellRangeParams;
const cellRange = rangeParams && this.rangeSvc?.createPartialCellRangeFromRangeParams(rangeParams, true);
if (!cellRange) {
(0, import_ag_grid_community290._warn)(127, { allRange });
}
return cellRange;
}
destroy() {
this.activeCharts.forEach((chart) => chart.destroyChart());
super.destroy();
}
};
// packages/ag-grid-enterprise/src/charts/chartsApi.ts
function getChartModels(beans) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.getChartModels());
}
function getChartRef(beans, chartId) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.getChartRef(chartId));
}
function getChartImageDataURL(beans, params) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.getChartImageDataURL(params));
}
function downloadChart(beans, params) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.downloadChart(params));
}
function openChartToolPanel(beans, params) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.openChartToolPanel(params));
}
function closeChartToolPanel(beans, params) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.closeChartToolPanel(params.chartId));
}
function createRangeChart(beans, params) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.createRangeChart(params, true));
}
function createPivotChart(beans, params) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.createPivotChart(params, true));
}
function createCrossFilterChart(beans, params) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.createCrossFilterChart(params, true));
}
function updateChart(beans, params) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.updateChart(params));
}
function restoreChart(beans, chartModel, chartContainer) {
return beans.frameworkOverrides.wrapIncoming(() => beans.chartSvc?.restoreChart(chartModel, chartContainer));
}
// packages/ag-grid-enterprise/src/charts/integratedChartsModule.css-GENERATED.ts
var integratedChartsModuleCSS = (
/*css*/
`.ag-chart{display:flex;height:100%;position:relative;width:100%}.ag-chart-components-wrapper{display:flex}.ag-chart-canvas-wrapper,.ag-chart-components-wrapper{flex:1 1 auto;position:relative}.ag-chart-menu{background:var(--ag-background-color);background-color:color-mix(in srgb,transparent,var(--ag-background-color) 30%);border-radius:var(--ag-border-radius);display:flex;flex-direction:row;gap:20px;padding:4px 2px;position:absolute;top:8px;width:auto;--ag-icon-size:20px}:where(.ag-ltr) .ag-chart-menu{justify-content:right;right:calc(var(--ag-cell-horizontal-padding) + var(--ag-spacing) - 4px)}:where(.ag-rtl) .ag-chart-menu{justify-content:left;left:calc(var(--ag-cell-horizontal-padding) + var(--ag-spacing) - 4px)}.ag-chart-docked-container{min-width:var(--ag-chart-menu-panel-width);position:relative}:where(.ag-chart-menu-hidden)~.ag-chart-docked-container{display:none}.ag-chart-tabbed-menu{display:flex;flex-direction:column;height:100%;overflow:hidden;width:100%}.ag-chart-tabbed-menu-header{cursor:default;flex:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.ag-chart-tabbed-menu-body{align-items:stretch;display:flex;flex:1 1 auto;overflow:hidden;position:relative;&:after{background:linear-gradient(var(--ag-background-color),transparent);content:"";display:block;height:16px;left:0;position:absolute;right:0;top:0}}.ag-chart-tab{overflow:hidden;overflow-y:auto;width:100%}.ag-chart-settings{overflow-x:hidden}.ag-chart-settings-wrapper{display:flex;flex-direction:column;height:100%;overflow:hidden;position:relative;width:100%}.ag-chart-settings-nav-bar{align-items:center;border-top:solid var(--ag-border-width) var(--ag-border-color);display:flex;height:30px;padding:0 10px;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:100%}.ag-chart-settings-card-selector{align-items:center;display:flex;flex:1 1 auto;height:100%;justify-content:space-around;padding:0 10px}.ag-chart-settings-card-item{background-color:var(--ag-foreground-color);border-radius:4px;cursor:pointer;height:8px;position:relative;width:8px;&.ag-not-selected{opacity:.2}&:before{background-color:transparent;content:" ";display:block;height:20px;left:50%;margin-left:-10px;margin-top:-10px;position:absolute;top:50%;width:20px}&.ag-selected{background-color:var(--ag-accent-color)}}.ag-chart-settings-next,.ag-chart-settings-prev{flex:none;position:relative;&:focus-within{border-radius:1px;box-shadow:var(--ag-focus-shadow)}}.ag-chart-settings-next-button,.ag-chart-settings-prev-button{cursor:pointer;height:100%;left:0;opacity:0;position:absolute;top:0;width:100%}.ag-chart-settings-mini-charts-container{flex:1 1 auto;overflow:hidden auto;position:relative}.ag-chart-settings-mini-wrapper{display:flex;flex-direction:column;left:0;min-height:100%;overflow:hidden;padding-bottom:var(--ag-widget-container-vertical-padding);position:absolute;top:0;width:100%;&.ag-animating{transition:left .3s;transition-timing-function:ease-in-out}}.ag-chart-mini-thumbnail{border:solid var(--ag-border-width) var(--ag-border-color);border-radius:5px;cursor:pointer;padding:1px;&.ag-selected{border-color:var(--ag-accent-color);border-width:calc(var(--ag-border-width) + 1px);padding:unset}&:focus-visible{border-color:var(--ag-accent-color);box-shadow:var(--ag-focus-shadow)}}.ag-chart-mini-thumbnail-canvas{display:block}.ag-chart-advanced-settings-wrapper,.ag-chart-data-wrapper,.ag-chart-format-wrapper{display:flex;flex-direction:column;padding-bottom:16px;position:relative;-webkit-user-select:none;-moz-user-select:none;user-select:none}.ag-chart-advanced-settings-wrapper,.ag-chart-data-wrapper{height:100%;overflow-y:auto}.ag-chart-advanced-settings{background-color:var(--ag-chrome-background-color)}.ag-chart-advanced-settings,.ag-chart-advanced-settings-wrapper{width:100%}.ag-chart-advanced-settings-wrapper{padding-bottom:0}.ag-chart-advanced-settings-section{border-bottom:solid var(--ag-border-width) var(--ag-border-color);display:flex;margin:0;padding-bottom:var(--ag-widget-container-vertical-padding);padding-top:var(--ag-widget-container-vertical-padding)}.ag-chart-empty-text{align-items:center;background-color:var(--ag-background-color);display:flex;height:100%;justify-content:center;top:0;width:100%}.ag-charts-font-size-color{align-self:stretch;display:flex;justify-content:space-between}.ag-charts-data-group-item{padding-bottom:var(--ag-widget-container-vertical-padding);position:relative}.ag-charts-data-group-item:where(:not(:last-child)){margin-bottom:var(--ag-spacing)}.ag-chart-menu-icon{border-radius:var(--ag-border-radius);cursor:pointer;margin:2px 0;opacity:.8;&:hover{opacity:1}}.ag-chart-menu-toolbar-button{background-color:unset;border:0;border-radius:1px;padding:0 2px}.ag-chart-data-column-drag-handle{margin-left:var(--ag-spacing)}.ag-charts-advanced-settings-top-level-group-title-bar{background-color:unset;position:relative}.ag-charts-data-group-container{padding:calc(var(--ag-widget-container-vertical-padding)*.5) var(--ag-widget-container-horizontal-padding)}.ag-charts-data-group-item:where(:not(.ag-charts-format-sub-level-group,.ag-pill-select,.ag-select)){height:var(--ag-list-item-height)}.ag-charts-data-group-item:where(.ag-picker-field){margin-top:var(--ag-spacing)}.ag-charts-advanced-settings-top-level-group-container,.ag-charts-format-top-level-group-container{margin-left:calc(var(--ag-spacing)*2);padding:var(--ag-spacing)}.ag-charts-advanced-settings-top-level-group-item,.ag-charts-format-top-level-group-item{margin:var(--ag-spacing) 0}.ag-charts-format-sub-level-group-container{display:flex;flex-direction:column;padding:var(--ag-widget-vertical-spacing) 0}.ag-charts-settings-group-container{display:grid;grid-template-columns:60px 1fr 60px 1fr 60px;padding:var(--ag-spacing);row-gap:8px;:where(.ag-chart-mini-thumbnail:nth-child(3n+1)){grid-column:1}:where(.ag-chart-mini-thumbnail:nth-child(3n+2)){grid-column:3}:where(.ag-chart-mini-thumbnail:nth-child(3n+3)){grid-column:5}}.ag-chart-data-section,.ag-chart-format-section{display:flex;margin:0;:where(.ag-label:not(.ag-group-title-bar)){color:var(--ag-chart-menu-label-color)}:where(.ag-label-align-top .ag-label){margin-bottom:var(--ag-widget-vertical-spacing);margin-top:calc(var(--ag-widget-vertical-spacing)*.5)}:where(.ag-slider.ag-label-align-top .ag-label){margin-bottom:0}:where(label){display:inline-block}}.ag-chart-menu-panel{--ag-panel-background-color:var(--ag-chrome-background-color)}:where(.ag-ltr) .ag-chart-menu-panel{border-left:solid var(--ag-border-width) var(--ag-border-color)}:where(.ag-rtl) .ag-chart-menu-panel{border-right:solid var(--ag-border-width) var(--ag-border-color)}.ag-charts-data-group-title-bar,.ag-charts-format-top-level-group-title-bar,.ag-charts-settings-group-container,.ag-charts-settings-group-title-bar{border-top:none;font-weight:500;padding:0 calc(var(--ag-spacing)*1.5)}.ag-charts-format-sub-level-group-title-bar{background:none;font-weight:500;padding:var(--ag-widget-vertical-spacing) 0}.ag-chart-data-wrapper,.ag-chart-format-wrapper,.ag-charts-data-group-container,.ag-charts-data-group-title-bar,.ag-charts-format-sub-level-group,.ag-charts-format-sub-level-group-container>*,.ag-charts-format-sub-level-group-item:last-child,.ag-charts-format-top-level-group,.ag-charts-format-top-level-group-item,.ag-charts-format-top-level-group-title-bar,.ag-charts-settings-group-container,.ag-charts-settings-group-title-bar,:where(.ag-charts-format-top-level-group) .ag-charts-format-top-level-group-container{margin:0;padding:0}.ag-charts-data-group-title-bar,.ag-charts-format-top-level-group-title-bar,.ag-charts-settings-group-title-bar{padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding);position:relative}.ag-charts-data-group,.ag-charts-format-top-level-group{border-top:solid var(--ag-border-width) var(--ag-border-color)}:where(.ag-charts-data-group) .ag-charts-data-group-container,:where(.ag-charts-format-top-level-group) .ag-charts-format-top-level-group-container,:where(.ag-charts-settings-group) .ag-charts-settings-group-container{padding:0 var(--ag-widget-container-horizontal-padding)}.ag-charts-format-sub-level-group-container>*,.ag-charts-format-sub-level-no-header-group-container>*,.ag-charts-format-top-level-group-container>*{margin-bottom:var(--ag-widget-vertical-spacing)}.ag-charts-advanced-settings-top-level-group-container{margin:0}:where(.ag-charts-advanced-settings-top-level-group){.ag-charts-advanced-settings-top-level-group-container,.ag-charts-advanced-settings-top-level-group-title-bar{padding:0 var(--ag-widget-container-horizontal-padding)}}.ag-charts-advanced-settings-top-level-group-item{margin-bottom:0;margin-top:calc(var(--ag-widget-vertical-spacing)*2)}.ag-chart-settings-card-item.ag-not-selected:hover{opacity:.35}.ag-angle-select{align-items:center;display:flex}.ag-angle-select-wrapper{display:flex}.ag-angle-select-parent-circle{background-color:var(--ag-background-color);border:solid var(--ag-border-width) var(--ag-border-color);border-radius:12px;display:block;height:24px;position:relative;width:24px}.ag-angle-select-child-circle{background-color:var(--ag-foreground-color);border-radius:3px;height:6px;left:12px;margin-left:-3px;margin-top:-4px;position:absolute;top:4px;width:6px}.ag-slider-wrapper{display:flex;:where(.ag-input-field){flex:1 1 auto}}.ag-color-panel{display:flex;flex-direction:column;padding:var(--ag-spacing);text-align:center;width:100%}.ag-spectrum-color{cursor:default;flex:1 1 auto;overflow:visible;position:relative}.ag-spectrum-color,.ag-spectrum-fill{border-radius:var(--ag-border-radius)}.ag-spectrum-fill{inset:0;position:absolute}.ag-spectrum-val{background-image:linear-gradient(0deg,#000,hsla(20,42%,65%,0));cursor:pointer}.ag-spectrum-dragger{background:#000;border:var(--ag-color-picker-thumb-border-width) solid #fff;border-radius:var(--ag-color-picker-thumb-size);box-shadow:0 0 2px 0 rgba(0,0,0,.24);cursor:pointer;height:var(--ag-color-picker-thumb-size);pointer-events:none;position:absolute;width:var(--ag-color-picker-thumb-size)}.ag-spectrum-alpha,.ag-spectrum-hue{cursor:default}.ag-spectrum-hue-background{background:linear-gradient(270deg,red 3%,#ff0 17%,#0f0 33%,#0ff 50%,#00f 67%,#f0f 83%,red);height:100%;width:100%}.ag-spectrum-alpha-background{background:linear-gradient(to right,var(--ag-internal-spectrum-alpha-color-from),var(--ag-internal-spectrum-alpha-color-to)),url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="4" height="4"><rect x="0" y="0" width="4" height="4" fill="%23fff"/><path d="M0 0H2V4H4V2H0Z" fill="%23b2b2b2"/></svg>') 0 0 /4px 4px;height:100%;width:100%}.ag-spectrum-tool{cursor:pointer;height:var(--ag-color-picker-track-size);margin-bottom:10px;position:relative}.ag-spectrum-slider,.ag-spectrum-tool{border-radius:var(--ag-color-picker-thumb-size)}.ag-spectrum-slider{border:var(--ag-color-picker-thumb-border-width) solid #fff;box-shadow:0 1px 4px 0 rgba(0,0,0,.37);height:var(--ag-color-picker-thumb-size);margin-top:calc(var(--ag-color-picker-track-size)/2*-1 + var(--ag-color-picker-thumb-size)/2*-1);pointer-events:none;position:absolute;width:var(--ag-color-picker-thumb-size)}:where(.ag-spectrum-alpha) .ag-spectrum-slider{background:linear-gradient(to bottom,var(--ag-internal-spectrum-alpha-color),var(--ag-internal-spectrum-alpha-color)) var(--ag-background-color)}.ag-recent-colors{display:flex;gap:6px;margin:10px var(--ag-spacing) 2px}.ag-recent-color{border:solid var(--ag-border-width) var(--ag-border-color);cursor:pointer}.ag-angle-select[disabled]{opacity:.5;pointer-events:none}:where(.ag-ltr) .ag-angle-select-field,:where(.ag-ltr) .ag-slider-field{margin-right:calc(var(--ag-spacing)*2)}:where(.ag-rtl) .ag-angle-select-field,:where(.ag-rtl) .ag-slider-field{margin-left:calc(var(--ag-spacing)*2)}.ag-color-dialog{border-radius:5px}:where(.ag-color-picker){.ag-picker-field-wrapper{padding-left:var(--ag-spacing);padding-right:var(--ag-spacing)}.ag-picker-field-display{align-items:center;display:flex;flex-direction:row;min-height:var(--ag-list-item-height)}}:where(.ag-ltr) .ag-color-picker-color,:where(.ag-ltr) .ag-color-picker-value{margin-right:var(--ag-spacing)}:where(.ag-rtl) .ag-color-picker-color,:where(.ag-rtl) .ag-color-picker-value{margin-left:var(--ag-spacing)}.ag-spectrum-tools{padding:10px 0 0}.ag-spectrum-alpha-background,.ag-spectrum-hue-background{border-radius:var(--ag-color-picker-track-border-radius)}.ag-color-input-color,.ag-color-picker-color,.ag-recent-color{border-radius:var(--ag-color-picker-color-border-radius)}.ag-spectrum-sat{background-image:linear-gradient(90deg,#fff,hsla(20,42%,65%,0))}.ag-recent-color,.ag-spectrum-color,.ag-spectrum-slider{&:where(:not(:disabled,[readonly])):focus-visible{box-shadow:var(--ag-focus-shadow)}}.ag-color-input-color,.ag-color-picker-color{border:solid var(--ag-border-width) var(--ag-border-color);height:var(--ag-icon-size);width:var(--ag-icon-size)}:where(.ag-ltr) .ag-color-input .ag-input-field-input{padding-left:calc(var(--ag-icon-size) + var(--ag-spacing)*2)}:where(.ag-rtl) .ag-color-input .ag-input-field-input{padding-right:calc(var(--ag-icon-size) + var(--ag-spacing)*2)}:where(.ag-color-input) .ag-color-input-color{position:absolute}:where(.ag-ltr) :where(.ag-color-input) .ag-color-input-color{margin-left:var(--ag-spacing)}:where(.ag-rtl) :where(.ag-color-input) .ag-color-input-color{margin-right:var(--ag-spacing)}.ag-range-field{align-items:center;display:flex;:where(.ag-input-wrapper){height:100%}}.ag-range-field-input{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:none;height:100%;overflow:visible;padding:0;width:100%;&:disabled{opacity:.5}}.ag-range-field-input{&::-webkit-slider-runnable-track{background-color:var(--ag-border-color);border-radius:1.5px;height:3px;margin:0;padding:0;width:100%}&::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;background-color:var(--ag-background-color);border:solid var(--ag-border-width) var(--ag-border-color);border-radius:100%;height:var(--ag-icon-size);margin:0;padding:0;transform:translateY(calc(var(--ag-icon-size)*-.5 + 1.5px));width:var(--ag-icon-size)}&:focus::-webkit-slider-thumb{border-color:var(--ag-accent-color);box-shadow:var(--ag-focus-shadow)}&:active::-webkit-slider-runnable-track{background-color:var(--ag-accent-color)}}.ag-range-field-input{&::-moz-range-track{background-color:var(--ag-border-color);border-radius:1.5px;height:3px;margin:0;padding:0;width:100%}&::-moz-ag-range-thumb{-moz-appearance:none;appearance:none;background-color:var(--ag-background-color);border:solid var(--ag-border-width) var(--ag-border-color);border-radius:100%;height:var(--ag-icon-size);margin:0;padding:0;transform:translateY(calc(var(--ag-icon-size)*-.5 + 1.5px));width:var(--ag-icon-size)}&:focus::-moz-ag-range-thumb{border-color:var(--ag-accent-color);box-shadow:var(--ag-focus-shadow)}&:active::-moz-ag-range-track{background-color:var(--ag-accent-color)}}`
);
// packages/ag-grid-enterprise/src/charts/utils/validGridChartsVersion.ts
var VERSION_CHECKING_FIRST_GRID_MAJOR_VERSION = 28;
var VERSION_CHECKING_FIRST_CHARTS_MAJOR_VERSION = 6;
function isValidVersion(version) {
return version && version.match(/\d+\.\d+\.\d+/);
}
function isValidMajorVersion({
gridMajorVersion,
chartsMajorVersion
}) {
const gridMajor = parseInt(gridMajorVersion, 10);
const chartsMajor = parseInt(chartsMajorVersion, 10);
const gridMajorDifference = gridMajor - VERSION_CHECKING_FIRST_GRID_MAJOR_VERSION;
const chartsMajorDifference = chartsMajor - VERSION_CHECKING_FIRST_CHARTS_MAJOR_VERSION;
const isFirstOrAfterVersion = gridMajorDifference >= 0;
return gridMajorDifference === chartsMajorDifference && isFirstOrAfterVersion;
}
function gridChartVersion(gridVersion) {
if (!gridVersion || !isValidVersion(gridVersion)) {
return void 0;
}
const [gridMajor, gridMinor] = gridVersion.split(".") || [];
const gridMajorMinor = `${gridMajor}.${gridMinor}.x`;
const gridMajorNumber = parseInt(gridMajor, 10);
const chartsMajor = gridMajorNumber - VERSION_CHECKING_FIRST_GRID_MAJOR_VERSION + VERSION_CHECKING_FIRST_CHARTS_MAJOR_VERSION;
if (chartsMajor < 0) {
return void 0;
}
const chartsMinor = gridMinor;
const chartsMajorMinor = `${chartsMajor}.${chartsMinor}.x`;
return {
gridMajorMinor,
chartsMajorMinor
};
}
function validGridChartsVersionErrorMessage({
type,
gridVersion,
chartsVersion
}) {
const invalidMessage = "AG Grid: AG Grid version is incompatible. Please see https://www.ag-grid.com/javascript-data-grid/modules/ for more information.";
if (!gridVersion) {
return invalidMessage;
}
const version = gridChartVersion(gridVersion);
if (!version) {
return invalidMessage;
}
const { gridMajorMinor, chartsMajorMinor } = version;
if (type === "incompatible") {
return `AG Grid version ${gridVersion} and AG Charts version ${chartsVersion} is not supported. AG Grid version ${gridMajorMinor} should be used with AG Chart ${chartsMajorMinor}. Please see https://www.ag-grid.com/javascript-data-grid/modules/ for more information.`;
} else if (type === "invalidCharts") {
return `AG Grid version ${gridMajorMinor} should be used with AG Chart ${chartsMajorMinor} not ${chartsVersion}. Please see https://www.ag-grid.com/javascript-data-grid/modules/ for more information.`;
}
return invalidMessage;
}
function validGridChartsVersion({
gridVersion,
chartsVersion
}) {
if (!isValidVersion(chartsVersion)) {
return {
isValid: false,
message: validGridChartsVersionErrorMessage({ type: "invalidCharts", gridVersion, chartsVersion })
};
}
if (!isValidVersion(gridVersion)) {
return {
isValid: false,
message: validGridChartsVersionErrorMessage({ type: "invalidGrid", gridVersion, chartsVersion })
};
}
const [gridMajor, gridMinor] = gridVersion.split(".") || [];
const [chartsMajor, chartsMinor, chartsPatch] = chartsVersion.split(".") || [];
const isValidMajor = isValidMajorVersion({
gridMajorVersion: gridMajor,
chartsMajorVersion: chartsMajor
});
if (isValidMajor && gridMinor === chartsMinor || chartsPatch.includes("beta")) {
return {
isValid: true
};
} else if (!isValidMajor || gridMinor !== chartsMinor) {
return {
isValid: false,
message: validGridChartsVersionErrorMessage({ type: "incompatible", gridVersion, chartsVersion })
};
}
return {
isValid: false,
message: validGridChartsVersionErrorMessage({ type: "invalid", gridVersion, chartsVersion })
};
}
// packages/ag-grid-enterprise/src/charts/integratedChartsModule.ts
var icons = {
// 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",
// icon to open charts menu
chartsMenu: "menu-alt",
// download chart
chartsDownload: "save",
// Edit Chart menu item shown in Integrated Charts menu
chartsMenuEdit: "chart",
// Advanced Settings menu item shown in Integrated Charts menu
chartsMenuAdvancedSettings: "settings",
// shown in Integrated Charts menu add fields
chartsMenuAdd: "plus",
// shown in Integrated Charts tool panel color picker
chartsColorPicker: "small-down",
// previous in Integrated Charts settings tool panel theme switcher
chartsThemePrevious: "previous",
// next in Integrated Charts settings tool panel theme switcher
chartsThemeNext: "next"
};
var apiFunctions = {
getChartModels,
getChartRef,
getChartImageDataURL,
downloadChart,
openChartToolPanel,
closeChartToolPanel,
createRangeChart,
createPivotChart,
createCrossFilterChart,
updateChart,
restoreChart
};
var dependsOn = [
CellSelectionModule,
EnterpriseCoreModule,
import_ag_grid_community291._SharedDragAndDropModule,
import_ag_grid_community291._PopupModule,
MenuItemModule
];
var moduleName2 = "IntegratedCharts";
var GridChartsModule = {
moduleName: "GridCharts",
version: VERSION,
dependsOn,
// included to avoid other false positive warnings about missing modules
validate: () => {
return {
isValid: false,
message: `AG Grid: As of v33, the "GridChartsModule" has been deprecated. Please use "IntegratedChartsModule.with(...)" instead.
${(0, import_ag_grid_community291._preInitErrMsg)(257)}`
};
}
};
var IntegratedChartsModule = {
moduleName: moduleName2,
version: VERSION,
dependsOn,
// included to avoid other false positive warnings about missing modules
validate: () => {
return {
isValid: false,
message: (0, import_ag_grid_community291._preInitErrMsg)(257)
};
},
with: (params) => {
params.setup();
params.setGridContext?.(true);
if (params.isEnterprise && params.setLicenseKey) {
const chartsManager = {
setLicenseKey: params.setLicenseKey
};
LicenseManager.setChartsLicenseManager(chartsManager);
}
return {
moduleName: moduleName2,
version: VERSION,
icons,
apiFunctions,
dependsOn,
css: [integratedChartsModuleCSS],
validate: () => {
return validGridChartsVersion({
gridVersion: VERSION,
chartsVersion: params.VERSION
});
},
beans: [
// bind the params to the constructor to avoid the need for static properties
AgChartsExports.bind(null, params),
ChartService,
ChartTranslationService,
ChartCrossFilterService,
ChartMenuListFactory,
ChartMenuService,
// Include enterprise beans for now for all users as tiny compared to charts bundle size
EnterpriseChartProxyFactory,
AdvancedSettingsMenuFactory
]
};
}
};
// packages/ag-grid-enterprise/src/allEnterpriseModule.ts
var import_ag_grid_community292 = require("ag-grid-community");
var dependsOn2 = [
import_ag_grid_community292.AllCommunityModule,
ClipboardModule,
ColumnsToolPanelModule,
ExcelExportModule,
FiltersToolPanelModule,
NewFiltersToolPanelModule,
MasterDetailModule,
ColumnMenuModule,
ContextMenuModule,
CellSelectionModule,
RichSelectModule,
RowNumbersModule,
RowGroupingModule,
RowGroupingPanelModule,
GroupFilterModule,
ServerSideRowModelModule,
ServerSideRowModelApiModule,
SetFilterModule,
MultiFilterModule,
AdvancedFilterModule,
SideBarModule,
StatusBarModule,
ViewportRowModelModule,
PivotModule,
TreeDataModule,
FindModule,
BatchEditModule
];
var moduleName3 = "AllEnterprise";
var AllEnterpriseModule = {
with: (params) => ({
moduleName: moduleName3,
version: VERSION,
dependsOn: [...dependsOn2, IntegratedChartsModule.with(params), SparklinesModule.with(params)]
}),
moduleName: moduleName3,
version: VERSION,
dependsOn: dependsOn2
};
// packages/ag-grid-enterprise/src/main.ts
__reExport(main_exports, require("ag-grid-community"), module.exports);