// packages/ag-grid-enterprise/src/license/gridLicenseManager.ts import { BeanStub, _getDocument } from "ag-grid-community"; // packages/ag-grid-enterprise/src/license/shared/licenseManager.ts import { _exists, _logPreInitWarn } from "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, s2, t) { a = this.add32(this.add32(a, q), this.add32(x, t)); return this.add32(a << s2 | a >>> 32 - s2, b); } ff(a, b, c, d, x, s2, t) { return this.cmn(b & c | ~b & d, a, b, x, s2, t); } gg(a, b, c, d, x, s2, t) { return this.cmn(b & d | c & ~d, a, b, x, s2, t); } hh(a, b, c, d, x, s2, t) { return this.cmn(b ^ c ^ d, a, b, x, s2, t); } ii(a, b, c, d, x, s2, t) { return this.cmn(c ^ (b | ~d), a, b, x, s2, t); } md51(s2) { const n = s2.length; const state = [1732584193, -271733879, -1732584194, 271733878]; let i; for (i = 64; i <= s2.length; i += 64) { this.md5cycle(state, this.md5blk(s2.substring(i - 64, i))); } s2 = s2.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 < s2.length; i++) { tail[i >> 2] |= s2.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(s2) { const md5blks = []; for (let i = 0; i < 64; i += 4) { md5blks[i >> 2] = s2.charCodeAt(i) + (s2.charCodeAt(i + 1) << 8) + (s2.charCodeAt(i + 2) << 16) + (s2.charCodeAt(i + 3) << 24); } return md5blks; } rhex(n) { const hex_chr = "0123456789abcdef".split(""); let s2 = "", j = 0; for (; j < 4; j++) { s2 += hex_chr[n >> j * 8 + 4 & 15] + hex_chr[n >> j * 8 & 15]; } return s2; } hex(x) { for (let i = 0; i < x.length; i++) { x[i] = this.rhex(x[i]); } return x.join(""); } md5(s2) { return this.hex(this.md51(s2)); } 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.includes("For_Trialing_ag-Grid_Only"); 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.includes("forceWatermark") : 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 s2, o, u, a; let f = 0; const e = input.replace(/[^A-Za-z0-9+/=]/g, ""); while (f < e.length) { s2 = keystr.indexOf(e.charAt(f++)); o = keystr.indexOf(e.charAt(f++)); u = keystr.indexOf(e.charAt(f++)); a = keystr.indexOf(e.charAt(f++)); n = s2 << 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) { if (_exists(this.licenseKey) && this.licenseKey !== licenseKey) { _logPreInitWarn( 291, void 0, "AG Grid: License Key being set multiple times with different values. This can result in an incorrect license key being used." ); } 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"; } }; // eslint-disable-next-line no-restricted-syntax _LicenseManager.RELEASE_INFORMATION = "MTc3MDgwOTgzNDk5MQ=="; var LicenseManager = _LicenseManager; // packages/ag-grid-enterprise/src/license/watermark.ts import { Component, RefPlaceholder } from "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}:where(.ag-ltr) .ag-watermark{right:25px}:where(.ag-rtl) .ag-watermark{left:25px}.ag-watermark:before{background-image:url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMDkiIGhlaWdodD0iMzYiIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCAyMDkgMzYiPjxwYXRoIGZpbGw9IiM5YjliOWIiIGQ9Ik0xOTIuOTkzIDIzLjY1OHYtNy45NDZoLTEzLjU0MWwtNy45NDcgNy45NDZ6TTIwOC4yNSAzLjk1aC0xNi45NzRsLTguMDEgNy45NDdoMjQuOTg0ek0xNjMuNjIyIDMxLjYwNWw0LjA2OS00LjA2OWgxMy43MzJ2Ny45NDdoLTE3LjgwMXoiLz48cGF0aCBmaWxsPSIjOWI5YjliIiBkPSJNMTY2LjYxIDE5Ljc4aDguNzczbDguMDEtNy45NDZIMTY2LjYxek0xNTcuMDExIDMxLjYwNWg2LjYxMWw3Ljg4My03Ljk0N2gtMTQuNDk0ek0xOTEuMjc2IDMuOTVsLTQuMDY4IDQuMDdIMTYxLjI3Vi4wNzJoMzAuMDA2ek0yMC44NCAzMC4yMDZIOC4zNzhsLTIuMTYyIDUuMzRILjc1TDEyLjI1NyA4LjU5Mmg0Ljc2OEwyOC41MyAzNS41NDZoLTUuNTN6bS0xLjcxNy00LjI2TDE0LjYwOSAxNC45NWwtNC41MTQgMTAuOTk4ek0xMDQuNDM3IDE4LjUwOWMxLjU4OS0yLjM1MiA1LjU5NC0yLjYwNyA3LjI0Ny0yLjYwN3Y0LjU3OGMtMi4wMzQgMC00LjA2OS4wNjMtNS4yNzcuOTUzLTEuMjA3Ljg5LTEuODQzIDIuMDk4LTEuODQzIDMuNTZ2MTAuNTUzaC00Ljk1OVYxNS45MDJoNC43Njh6TTExOS4zNzYgMTUuOTAyaC00Ljk1OHYxOS42NDRoNC45NTh6TTExOS4zNzYgNy4xM2gtNC45NTh2NS44NDhoNC45NTh6TTE0My45NzkgNy4xM3YyOC40MTZoLTQuNzY4bC0uMTI3LTIuOTg4YTguMyA4LjMgMCAwIDEtMi42NyAyLjQ4Yy0xLjA4MS41NzItMi40MTYuODktMy45NDIuODktMS4zMzUgMC0yLjYwNi0uMjU1LTMuNjg3LS43LTEuMTQ0LS41MDgtMi4xNjItMS4xNDQtMi45ODgtMi4wMzRhOS42IDkuNiAwIDAgMS0xLjk3MS0zLjE3OWMtLjUwOC0xLjIwNy0uNjk5LTIuNjA2LS42OTktNC4xMzJzLjI1NC0yLjkyNC42OTktNC4xOTZjLjUwOS0xLjI3MSAxLjE0NS0yLjM1MiAxLjk3MS0zLjI0MnMxLjg0NC0xLjU4OSAyLjk4OC0yLjA5OCAyLjM1Mi0uNzYzIDMuNjg3LS43NjNjMS41MjYgMCAyLjc5Ny4yNTUgMy44NzguODI3czEuOTcxIDEuMzM1IDIuNjcgMi40MTZWNy4xOTNoNC45NTl6bS0xMC40MjYgMjQuNTM4YzEuNjUzIDAgMi45MjQtLjU3MiAzLjk0MS0xLjY1M3MxLjUyNi0yLjU0MyAxLjUyNi00LjMyMy0uNTA5LTMuMTc4LTEuNTI2LTQuMzIyYy0xLjAxNy0xLjA4MS0yLjI4OC0xLjY1My0zLjk0MS0xLjY1My0xLjU5IDAtMi45MjUuNTcyLTMuODc4IDEuNjUzLTEuMDE3IDEuMDgtMS41MjYgMi41NDMtMS41MjYgNC4zMjIgMCAxLjc4LjUwOSAzLjE4IDEuNTI2IDQuMjYgMS4wMTcgMS4xNDQgMi4yODggMS43MTYgMy44NzggMS43MTZNNTcuMjAyIDIwLjM1M0g0NC45MzN2NC4yNTloNi45OTNjLS4xOSAyLjE2MS0xLjAxNyAzLjgxNC0yLjQxNiA1LjE1LTEuMzk4IDEuMjctMy4xNzggMS45MDYtNS40NjcgMS45MDYtMS4yNzEgMC0yLjQ4LS4yNTQtMy40OTYtLjY5OWE3IDcgMCAwIDEtMi43MzQtMS45N2MtLjc2My0uODI3LTEuMzM1LTEuODQ0LTEuNzgtMy4wNTJzLS42MzYtMi40OC0uNjM2LTMuOTQyLjE5LTIuNzMzLjYzNi0zLjk0MWMuMzgxLTEuMjA4IDEuMDE3LTIuMTYyIDEuNzgtMy4wNTIuNzYzLS44MjYgMS42NTMtMS40NjIgMi43MzMtMS45N2E5LjEgOS4xIDAgMCAxIDMuNTYtLjdxNC4wMDUgMCA2LjEwMyAxLjkwN2wzLjMwNi0zLjMwNWMtMi40OC0xLjkwNy01LjY1OC0yLjkyNS05LjQwOS0yLjkyNS0yLjA5NyAwLTQuMDA0LjMxOC01LjcyMSAxLjAxOC0xLjcxNi42OTktMy4xNzkgMS41ODktNC4zODYgMi43OTdBMTIuMSAxMi4xIDAgMCAwIDMxLjIgMTYuMjJjLS42MzUgMS43MTctLjk1MyAzLjYyNC0uOTUzIDUuNjU4cy4zMTggMy45NDIgMS4wMTcgNS42NThjLjcgMS43MTcgMS41OSAzLjE3OSAyLjc5NyA0LjM4N2ExMi4xIDEyLjEgMCAwIDAgNC4zODcgMi43OTdjMS43MTYuNyAzLjYyMyAxLjAxNyA1LjY1NyAxLjAxNyAyLjAzNSAwIDMuODc4LS4zMTggNS41MzEtMS4wMTcgMS42NTMtLjcgMy4wNTItMS41OSA0LjE5Ni0yLjc5N3ExLjcxNi0xLjgxMiAyLjY3LTQuMzg3Yy42MzYtMS43MTYuOTU0LTMuNjIzLjk1NC01LjY1OHYtLjgyNmMtLjE5MS0uMTI3LS4yNTUtLjQ0NS0uMjU1LS43TTk1Ljk4MiAyMC4zNTNoLTEyLjI3djQuMjU5aDYuOTkzYy0uMTkgMi4xNjEtMS4wMTcgMy44MTQtMi40MTYgNS4xNS0xLjM5OCAxLjI3LTMuMTc4IDEuOTA2LTUuNDY3IDEuOTA2LTEuMjcxIDAtMi40OC0uMjU0LTMuNDk2LS42OTlhNyA3IDAgMCAxLTIuNzM0LTEuOTdjLS43NjMtLjgyNy0xLjMzNS0xLjg0NC0xLjc4LTMuMDUycy0uNjM2LTIuNDgtLjYzNi0zLjk0Mi4xOS0yLjczMy42MzYtMy45NDFjLjM4MS0xLjIwOCAxLjAxNy0yLjE2MiAxLjc4LTMuMDUyLjc2My0uODI2IDEuNjUzLTEuNDYyIDIuNzM0LTEuOTdhOS4xIDkuMSAwIDAgMSAzLjU2LS43cTQuMDA1IDAgNi4xMDMgMS45MDdsMy4zMDUtMy4zMDVjLTIuNDc5LTEuOTA3LTUuNjU4LTIuOTI1LTkuNDA4LTIuOTI1LTIuMDk4IDAtNC4wMDUuMzE4LTUuNzIyIDEuMDE4LTEuNzE2LjY5OS0zLjE3OCAxLjU4OS00LjM4NiAyLjc5N2ExMi4xIDEyLjEgMCAwIDAtMi43OTcgNC4zODZjLS42MzYgMS43MTctLjk1NCAzLjYyNC0uOTU0IDUuNjU4cy4zMTggMy45NDIgMS4wMTcgNS42NThjLjcgMS43MTcgMS41OSAzLjE3OSAyLjc5NyA0LjM4N2ExMi4xIDEyLjEgMCAwIDAgNC4zODcgMi43OTdjMS43MTYuNyAzLjYyMyAxLjAxNyA1LjY1OCAxLjAxNyAyLjAzNCAwIDMuODc4LS4zMTggNS41My0xLjAxNyAxLjY1My0uNyAzLjA1Mi0xLjU5IDQuMTk2LTIuNzk3cTEuNzE4LTEuODEyIDIuNjctNC4zODdjLjYzNi0xLjcxNi45NTQtMy42MjMuOTU0LTUuNjU4di0uODI2Yy0uMTktLjEyNy0uMjU1LS40NDUtLjI1NS0uNyIvPjwvc3ZnPg==");background-repeat:no-repeat;background-size:170px 40px;content:"";display:block;height:40px;width:170px}.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 Component { constructor() { super(WatermarkElement); this.eLicenseTextRef = 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 BeanStub { constructor() { super(...arguments); this.beanName = "licenseManager"; } postConstruct() { this.validateLicense(); } validateLicense() { this.licenseManager = new LicenseManager(_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 import { BaseCreator, _addGridCommonParams as _addGridCommonParams2, _downloadFile, _getHeaderClassesFromColDef, _getHeaderRowCount, _warn as _warn3 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/excelExport/excelSerializingSession.ts import { BaseGridSerializingSession, _addGridCommonParams, _isExpressionString, _last, _mergeDeep, _warn } from "ag-grid-community"; // packages/ag-grid-enterprise/src/excelExport/assets/excelUtils.ts import { _escapeString } from "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 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) => { for (const key of Object.keys(prefixedSet.map)) { props += returnAttributeIfPopulated( prefixedSet.prefix + key, prefixedSet.map[key], booleanTransformer ); } }); } if (xmlElement.properties.rawMap) { for (const key of Object.keys(xmlElement.properties.rawMap)) { 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 + "" + LINE_SEPARATOR; } result += ">" + LINE_SEPARATOR; if (xmlElement.children) { for (const it of xmlElement.children) { result += createXml(it, booleanTransformer); } } return result + "" + 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: _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/excelSerializingSession.ts var ExcelSerializingSession = class extends 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.formulaSvc = config.formulaSvc; this.config = Object.assign({}, config); this.workbook = config.workbook; this.stylesByIds = {}; for (const style of this.config.baseExcelStyles) { this.stylesByIds[style.id] = style; } const quotePrefixStyle = { id: "_quotePrefix", quotePrefix: 1 }; this.stylesByIds[quotePrefixStyle.id] = quotePrefixStyle; this.excelStyles = [...this.config.baseExcelStyles, quotePrefixStyle]; } addCustomContent(customContent) { for (const row of customContent) { 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, collapsibleGroupRanges) => { 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: collapsibleGroupRanges }); } }; } 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(_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 worksheet = this.createWorksheet(); return this.addWorksheetToWorkbook(worksheet); } createWorksheet() { const { sheetName } = this.config; let name; if (sheetName != null) { const sheetNameValue = typeof sheetName === "function" ? sheetName(_addGridCommonParams(this.gos, {})) : sheetName; name = String(sheetNameValue).substring(0, 31); } else { name = "ag-grid"; } return { name, table: { columns: this.cols, rows: this.rows } }; } 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 = _last(this.rows); if (node.uiLevel == null || node.level === node.uiLevel) { 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(_addGridCommonParams(this.gos, { column }))) { this.frozenColumnCount++; } else { this.skipFrozenColumns = true; } } const { value: valueForCell, valueFormatted } = this.extractRowCellValue({ column, node, currentColumnIndex: index, accumulatedRowIndex: rowIndex, type: "excel", useRawFormula: true }); const rawValueForCell = valueForCell; const valueForCellString = typeof rawValueForCell === "bigint" ? rawValueForCell.toString() : rawValueForCell; const styleIds = this.config.styleLinker({ rowType: "BODY", rowIndex, value: rawValueForCell, column, node }); const excelStyleId = this.getStyleId(styleIds); const colSpan = column.getColSpan(node); const addedImage = this.addImage(rowIndex, column, valueForCellString); 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(rawValueForCell), valueForCellString, colSpan - 1 ) ); } else { const isFormula = column.isAllowFormula() && this.formulaSvc?.isFormula(valueForCellString); const cell = this.createCell( excelStyleId, isFormula ? "f" : this.getDataTypeForValue(rawValueForCell), isFormula ? this.formulaSvc?.updateFormulaByOffset({ value: valueForCellString, rowDelta: rowIndex - (node.formulaRowIndex + 1), useRefFormat: false }) : valueForCellString, valueFormatted ); currentCells.push(cell); } }; } 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)() }; } addWorksheetToWorkbook(worksheet) { const { excelStyles, config } = this; this.mapSharedStrings(worksheet); if (this.frozenColumnCount) { config.frozenColumnCount = this.frozenColumnCount; } if (this.frozenRowCount) { config.frozenRowCount = this.frozenRowCount; } return this.workbook.addWorksheet(excelStyles, worksheet, config); } mapSharedStrings(worksheet) { let emptyStringPosition; for (const row of worksheet.table.rows) { for (const cell of row.cells) { const data = cell.data; if (!data || data.type !== "s") { continue; } const value = data.value; if (value == null) { continue; } if (value === "") { emptyStringPosition ?? (emptyStringPosition = this.workbook.getStringPosition("").toString()); data.value = emptyStringPosition; continue; } data.value = this.workbook.getStringPosition(String(value)).toString(); } } } 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?.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: _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; } this.workbook.addBodyImageToMap( 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" ? String(valueToUse) : value }, mergeAcross: numOfCells }; } getCellValue(type, value) { let escaped = false; if (value == null || type === "s" && value === "") { return { value: "", escaped: false }; } if (type === "s") { value = String(value); if (value[0] === "'") { escaped = true; value = value.slice(1); } } else if (type === "f") { value = this.addXlfnPrefix(value).slice(1); } else if (type === "n") { const numberValue = Number(value); if (isNaN(numberValue)) { value = ""; } else if (value !== "") { value = numberValue.toString(); } } return { value, escaped }; } addXlfnPrefix(value) { if (!value) { return value; } const concatRegex = /(^|[^A-Z0-9._])(CONCAT)(\s*\()/gi; return value.replace(concatRegex, (_match, prefix, fn, openParen) => `${prefix}_xlfn.${fn}${openParen}`); } getStyleId(styleIds) { if (!styleIds?.length) { return null; } const filteredStyleIds = styleIds.filter((styleId) => this.stylesByIds[styleId] != null); if (!filteredStyleIds.length) { return null; } if (filteredStyleIds.length === 1) { return filteredStyleIds[0]; } const key = filteredStyleIds.join("-"); if (!this.mixedStyles[key]) { this.addNewMixedStyle(filteredStyleIds); } return this.mixedStyles[key].excelID; } addNewMixedStyle(styleIds) { this.mixedStyleCounter += 1; const excelId = `mixedStyle${this.mixedStyleCounter}`; const resultantStyle = {}; for (const styleId of styleIds) { const excelStyle = this.stylesByIds[styleId]; if (excelStyle) { _mergeDeep(resultantStyle, excelStyle, true, true); } } 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; } const strValue = String(value); return this.config.autoConvertFormulas && _isExpressionString(strValue); } isNumerical(value) { if (typeof value === "bigint") { return false; } 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/excelXlsxFactory.ts import { _escapeString as _escapeString7, _warn as _warn2 } from "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, hasCustomProperties }) { 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 customPropertiesDocs = hasCustomProperties ? [ { name: "Override", ContentType: "application/vnd.openxmlformats-officedocument.custom-properties+xml", PartName: "/docProps/custom.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" }, ...customPropertiesDocs ].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/customProperties.ts import { _escapeString as _escapeString2 } from "ag-grid-community"; var DEFAULT_FMTID = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"; var buildPropertyElements = (metadata) => { const keys = Object.keys(metadata).filter((name) => name && metadata[name] != null); return keys.map((name, index) => ({ name: "property", properties: { rawMap: { fmtid: DEFAULT_FMTID, pid: (index + 2).toString(), name: _escapeString2(name) ?? "" } }, children: [ { name: "vt:lpwstr", textNode: _escapeString2(replaceInvisibleCharacters(String(metadata[name]))) ?? "" } ] })); }; var customPropertiesFactory = { getTemplate(metadata) { return { name: "Properties", properties: { rawMap: { xmlns: "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties", "xmlns:vt": "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes" } }, children: buildPropertyElements(metadata) }; } }; var customProperties_default = customPropertiesFactory; // 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?.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?.style } }, children: leftChildren }, { name: "right", properties: { rawMap: { style: right?.style } }, children: rightChildren }, { name: "top", properties: { rawMap: { style: top?.style } }, children: topChildren }, { name: "bottom", properties: { rawMap: { style: bottom?.style } }, children: bottomChildren }, { name: "diagonal", properties: { rawMap: { style: 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 import { _escapeString as _escapeString3 } from "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] = _escapeString3(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.includes("mixedStyle") && 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; return !(patternType != convertedPattern || fgRgb != convertedFillColor || bgRgb != convertedPatternColor); }); 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) => { return !(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); }); 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 import { _escapeString as _escapeString4 } from "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: displayNameToUse, 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: _escapeString4(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 import { _escapeString as _escapeString6 } from "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: s2, 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: s2, 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 import { _escapeString as _escapeString5 } from "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: _escapeString5(replaceInvisibleCharacters(value)) } ]; } else if (convertedType === "inlineStr") { children = [ { name: "is", children: [ { name: "t", textNode: _escapeString5(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}${_escapeString6(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 getPasswordHash = (password) => { const passwordLength = password.length; if (!passwordLength) { return ""; } const passwordArray = new Array(passwordLength + 1); passwordArray[0] = passwordLength; for (let i = 1; i <= passwordLength; i++) { passwordArray[i] = password.charCodeAt(i - 1) & 255; } let verifier = 0; for (let i = passwordArray.length - 1; i >= 0; i--) { const passwordByte = passwordArray[i]; const intermediate1 = (verifier & 16384) === 0 ? 0 : 1; const intermediate2 = verifier << 1 & 32767; verifier = (intermediate1 | intermediate2) ^ passwordByte; } return (verifier ^ 52811).toString(16).toUpperCase().padStart(4, "0"); }; var addSheetProtection = (protectSheet) => { return (params) => { if (!protectSheet) { return params; } const sheetProtection = typeof protectSheet === "boolean" ? {} : protectSheet; const rawMap = { sheet: 1 }; const passwordHash = sheetProtection.password ? getPasswordHash(sheetProtection.password) : ""; if (passwordHash) { rawMap.password = passwordHash; } const defaults = { autoFilter: false, deleteColumns: false, deleteRows: false, formatCells: false, formatColumns: false, formatRows: false, insertColumns: false, insertHyperlinks: false, insertRows: false, pivotTables: false, selectLockedCells: true, selectUnlockedCells: true }; Object.keys(defaults).forEach( (key) => { const allow = sheetProtection[key]; if (allow == null || allow === defaults[key]) { return; } rawMap[key] = allow ? 0 : 1; } ); params.children.push({ name: "sheetProtection", properties: { rawMap } }); 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, protectSheet } = config; const { table } = worksheet; const { rows, columns } = table; const mergedCells = 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), addSheetProtection(protectSheet), 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_SHEET_DATA = []; var XLSX_SHEET_CONTENT_INDICES = /* @__PURE__ */ new Map(); 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 && config.pivotModeActive) { _warn2(163, { featureName: "pivot mode" }); newConfig.exportAsExcelTable = false; } processTableConfig(worksheet, newConfig); const worksheetXml = createWorksheet(worksheet, newConfig); registerSheetXml(worksheetXml); return worksheetXml; } 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)) { _warn2(164); return; } XLSX_WORKSHEET_DATA_TABLES.set(sheetIndex, table); } function processTableConfig(worksheet, config) { const { exportAsExcelTable, prependContent, appendContent, headerRowCount = 0 } = config; if (!exportAsExcelTable) { return; } const tableConfig = typeof exportAsExcelTable === "boolean" ? {} : exportAsExcelTable; const { name, showColumnStripes, showRowStripes, showFilterButton, highlightFirstColumn, highlightLastColumn } = tableConfig; const tableName = getXlsxSanitizedTableName(name || DEFAULT_TABLE_DISPLAY_NAME); const sheetIndex = XLSX_SHEET_NAMES.length - 1; const { table } = worksheet; const { rows, columns } = table; 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?.length || !tableRowCount || !tableName) { _warn2(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 = _escapeString7(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_SHEET_DATA = []; XLSX_SHEET_CONTENT_INDICES = /* @__PURE__ */ new Map(); 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 createXlsxCustomProperties(metadata) { return createXmlPart(customProperties_default.getTemplate(metadata)); } function createXlsxContentTypes(sheetLen, hasCustomProperties) { return createXmlPart(contentTypes_default.getTemplate({ sheetLen, hasCustomProperties })); } function createXlsxRels(hasCustomProperties) { const relationships = [ { 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" } ]; if (hasCustomProperties) { relationships.push({ Id: "rId3", Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties", Target: "docProps/custom.xml" }); } const rs = relationships_default.getTemplate(relationships); 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 }) ); } var reorderSheetSpecificMap = (map, order) => { if (!map.size) { return; } const remapped = /* @__PURE__ */ new Map(); order.forEach((originalIdx, newIdx) => { if (map.has(originalIdx)) { remapped.set(newIdx, map.get(originalIdx)); } }); map.clear(); remapped.forEach((value, key) => map.set(key, value)); }; var registerSheetXml = (worksheetXml) => { const indices = XLSX_SHEET_CONTENT_INDICES.get(worksheetXml) ?? []; indices.push(XLSX_SHEET_NAMES.length - 1); XLSX_SHEET_CONTENT_INDICES.set(worksheetXml, indices); XLSX_SHEET_DATA.push(worksheetXml); }; var getSheetOrderFromRefs = (data) => { const refMap = new Map(XLSX_SHEET_CONTENT_INDICES); const order = []; for (const sheetData of data) { const indices = refMap.get(sheetData); if (!indices?.length) { return null; } const idx = indices.shift(); order.push(idx); refMap.set(sheetData, indices); } return order; }; var getSheetOrderFromData = (data) => { if (!data.length || XLSX_SHEET_DATA.length === 0) { return null; } const consumed = /* @__PURE__ */ new Set(); const order = []; for (const sheetData of data) { const matchIndex = XLSX_SHEET_DATA.findIndex((value, idx) => !consumed.has(idx) && value === sheetData); if (matchIndex === -1) { return null; } consumed.add(matchIndex); order.push(matchIndex); } return order; }; var reorderSheetState = (order) => { const indexRemap = /* @__PURE__ */ new Map(); order.forEach((originalIdx, newIdx) => indexRemap.set(originalIdx, newIdx)); XLSX_SHEET_NAMES = order.map((idx) => XLSX_SHEET_NAMES[idx]); XLSX_SHEET_DATA = order.map((idx) => XLSX_SHEET_DATA[idx]); reorderSheetSpecificMap(XLSX_WORKSHEET_IMAGES, order); reorderSheetSpecificMap(XLSX_WORKSHEET_HEADER_FOOTER_IMAGES, order); reorderSheetSpecificMap(XLSX_WORKSHEET_DATA_TABLES, order); reorderSheetSpecificMap(XLSX_WORKSHEET_IMAGE_IDS, order); XLSX_IMAGES.forEach((sheetImages) => { sheetImages.forEach((entry) => { const remappedId = indexRemap.get(entry.sheetId); if (remappedId != null) { entry.sheetId = remappedId; } }); }); XLSX_SHEET_CONTENT_INDICES = /* @__PURE__ */ new Map(); XLSX_SHEET_DATA.forEach((xml, idx) => { const indices = XLSX_SHEET_CONTENT_INDICES.get(xml) ?? []; indices.push(idx); XLSX_SHEET_CONTENT_INDICES.set(xml, indices); }); }; var syncXlsxOrderWithSheetData = (data) => { if (data.length <= 1) { return; } const order = getSheetOrderFromRefs(data) ?? getSheetOrderFromData(data); if (!order) { return; } reorderSheetState(order); }; var Workbook = class { getStringPosition(str) { return getXlsxStringPosition(str); } addBodyImageToMap(image, rowIndex, col, columnsToExport, rowHeight) { addXlsxBodyImageToMap(image, rowIndex, col, columnsToExport, rowHeight); } addHeaderFooterImageToMap(image, position) { addXlsxHeaderFooterImageToMap(image, position); } addWorksheet(styles, worksheet, config) { return createXlsxExcel(styles, worksheet, config); } syncOrderWithSheetData(data) { syncXlsxOrderWithSheetData(data); } reset() { resetXlsxFactory(); } setFactoryMode(factoryMode) { setXlsxFactoryMode(factoryMode); } getFactoryMode() { return getXlsxFactoryMode(); } getSheetNames() { return [...XLSX_SHEET_NAMES]; } }; // packages/ag-grid-enterprise/src/excelExport/zipContainer/zipContainerHelper.ts import { _errMsg } from "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(s2) { 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 new Error(_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(s2); 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 preprocessFileForZip = async (currentFile) => { const { content } = currentFile; const { size: rawSize, content: rawContent } = !content ? { size: 0, content: Uint8Array.from([]) } : getDecodedContent(content); let deflatedContent; let deflatedSize; let deflationPerformed = false; const shouldDeflate = currentFile.type === "file" && rawContent && rawSize > 0; if (shouldDeflate) { const result = await deflateLocalFile(rawContent); deflatedContent = result.content; deflatedSize = result.size; deflationPerformed = true; } return { rawContent, rawSize, deflatedContent, deflatedSize, 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 preprocessed = await Promise.all(totalFiles.map(preprocessFileForZip)); const processed = []; let offset = 0; for (let i = 0; i < totalFiles.length; i++) { const currentFile = totalFiles[i]; const { rawContent, rawSize, deflatedContent, deflatedSize, isCompressed } = preprocessed[i]; const headers = getHeaders(currentFile, isCompressed, offset, rawSize, rawContent, deflatedSize); const contentToUse = deflatedContent ?? rawContent; processed.push({ ...headers, content: contentToUse, isCompressed }); offset += headers.localFileHeader.length + contentToUse.length; } return this.packageFiles(processed); } 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, customMetadata) => { const hasCustomMetadata = !!customMetadata && Object.keys(customMetadata).some((key) => customMetadata[key] != null); 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)); if (hasCustomMetadata) { zipContainer.addFile("docProps/custom.xml", createXlsxCustomProperties(customMetadata)); } zipContainer.addFile("[Content_Types].xml", createXlsxContentTypes(sheetLen, hasCustomMetadata)); zipContainer.addFile("_rels/.rels", createXlsxRels(hasCustomMetadata)); }; var createExcelFileForExcel = (zipContainer, data, options = {}, workbook) => { if (!data || data.length === 0) { _warn3(159); workbook.reset(); return false; } workbook.syncOrderWithSheetData(data); const { fontSize = 11, author = "AG Grid", activeTab = 0, customMetadata } = 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, customMetadata); workbook.reset(); return true; }; var getMultipleSheetsAsExcelCompressed = (params, workbook = new Workbook()) => { const { data, fontSize, author, activeSheetIndex, customMetadata } = params; const mimeType = params.mimeType || "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; const zipContainer = new ZipContainer(); if (!createExcelFileForExcel( zipContainer, data, { author, fontSize, activeTab: activeSheetIndex, customMetadata }, workbook )) { return Promise.resolve(void 0); } return zipContainer.getZipFile(mimeType); }; var getMultipleSheetsAsExcel = (params, workbook = new Workbook()) => { const { data, fontSize, author, activeSheetIndex: activeTab, customMetadata } = params; const mimeType = params.mimeType || "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; const zipContainer = new ZipContainer(); if (!createExcelFileForExcel( zipContainer, data, { author, fontSize, activeTab, customMetadata }, workbook )) { return; } return zipContainer.getUncompressedZipFile(mimeType); }; var exportMultipleSheetsAsExcel = (params) => { const { fileName = "export.xlsx" } = params; const workbook = new Workbook(); getMultipleSheetsAsExcelCompressed(params, workbook).then((contents) => { if (contents) { const downloadFileName = typeof fileName === "function" ? fileName() : fileName; _downloadFile(downloadFileName, contents); } }); }; var ExcelCreator = class extends BaseCreator { constructor() { super(...arguments); this.beanName = "excelCreator"; this.workbook = new Workbook(); } getMergedParams(params) { const baseParams = this.gos.get("defaultExcelExportParams"); return Object.assign({}, baseParams, params); } export(userParams) { if (this.isExportSuppressed()) { _warn3(160); return; } const exportFunc = () => { const mergedParams = this.getMergedParams(userParams); const data = this.getData(mergedParams); const { fontSize, author, mimeType, customMetadata } = mergedParams; const exportParams = { data: [data], fontSize, author, mimeType, customMetadata }; this.packageCompressedFile(exportParams).then((packageFile) => { if (packageFile) { const { fileName } = mergedParams; const providedFileName = typeof fileName === "function" ? fileName(_addGridCommonParams2(this.gos, {})) : fileName; _downloadFile(this.getFileName(providedFileName), packageFile); } }); }; const { overlays } = this.beans; if (overlays) { overlays.showExportOverlay(exportFunc); } else { exportFunc(); } } exportDataAsExcel(params) { this.export(params); } getDataAsExcel(params) { const mergedParams = this.getMergedParams(params); const data = this.getData(mergedParams); const { fontSize, author, mimeType, customMetadata } = mergedParams; const exportParams = { data: [data], fontSize, author, mimeType, customMetadata }; return this.packageFile(exportParams); } setFactoryMode(factoryMode) { this.workbook.setFactoryMode(factoryMode); } getFactoryMode() { return this.workbook.getFactoryMode(); } getSheetDataForExcel(params) { const mergedParams = this.getMergedParams(params); return this.getData(mergedParams); } getMultipleSheetsAsExcel(params) { return getMultipleSheetsAsExcel(params, this.workbook); } exportMultipleSheetsAsExcel(params) { getMultipleSheetsAsExcelCompressed(params, this.workbook).then((contents) => { const { fileName = "export.xlsx" } = params; if (contents) { const downloadFileName = typeof fileName === "function" ? fileName() : fileName; _downloadFile(downloadFileName, contents); } }); } getDefaultFileExtension() { return "xlsx"; } createSerializingSession(params) { const { colModel, colNames, rowGroupColsSvc, valueSvc, formula, gos } = this.beans; const baseExcelStyles = gos.get("excelStyles") || []; const styleLinker = this.createStyleLinker(baseExcelStyles); const config = { ...params, colModel, colNames, rowGroupColsSvc, valueSvc, formulaSvc: formula, gos, suppressRowOutline: params.suppressRowOutline || params.skipRowGroups, headerRowHeight: params.headerRowHeight || params.rowHeight, baseExcelStyles, rightToLeft: params.rightToLeft ?? gos.get("enableRtl"), styleLinker, headerRowCount: _getHeaderRowCount(colModel), pivotModeActive: colModel.isPivotActive(), workbook: this.workbook }; return new ExcelSerializingSession(config); } createStyleLinker(baseExcelStyles) { const styleIds = []; const styleIdsSet = /* @__PURE__ */ new Set(); const styleIdOrder = /* @__PURE__ */ new Map(); baseExcelStyles.forEach((it, idx) => { styleIds.push(it.id); styleIdsSet.add(it.id); styleIdOrder.set(it.id, idx); }); const { gos, cellStyles } = this.beans; return (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 = []; if (isHeader || isGroupHeader) { headerClasses.push("header"); if (isGroupHeader) { headerClasses.push("headerGroup"); } if (col) { headerClasses = headerClasses.concat( _getHeaderClassesFromColDef( col.getDefinition(), gos, column || null, columnGroup || null ) ); } return headerClasses; } const applicableStyles = ["cell"]; if (!styleIds.length) { return applicableStyles; } const colDef = column.getDefinition(); cellStyles?.processAllCellClasses( colDef, _addGridCommonParams2(gos, { value, data: node.data, node, colDef, column, rowIndex }), (className) => { if (styleIdsSet.has(className)) { applicableStyles.push(className); } } ); return applicableStyles.sort((left, right) => { const leftIdx = styleIdOrder.get(left) ?? -1; const rightIdx = styleIdOrder.get(right) ?? -1; return leftIdx === rightIdx ? 0 : leftIdx < rightIdx ? -1 : 1; }); }; } isExportSuppressed() { return this.gos.get("suppressExcelExport"); } packageCompressedFile(params) { return getMultipleSheetsAsExcelCompressed(params, this.workbook); } packageFile(params) { return getMultipleSheetsAsExcel(params, this.workbook); } }; // packages/ag-grid-enterprise/src/agStack/agVirtualList.ts import { KeyCode, RefPlaceholder as RefPlaceholder2, _AgTabGuardComp, _createAgElement, _getAriaPosInSet, _observeResize, _requestAnimationFrame, _setAriaLabel, _setAriaPosInSet, _setAriaRole, _setAriaSetSize, _waitUntil } from "ag-grid-community"; // packages/ag-grid-enterprise/src/agStack/agVirtualList.css-GENERATED.ts var agVirtualListCSS = ( /*css*/ `:where(.ag-virtual-list-viewport) .ag-tab-guard{position:sticky}.ag-virtual-list-viewport{flex:1 1 auto;height:100%;min-width:0;overflow:auto;position:relative;width:100%}.ag-virtual-list-container{overflow:hidden;position:relative}.ag-virtual-list-item{height:var(--ag-list-item-height);position:absolute;width:100%}` ); // packages/ag-grid-enterprise/src/agStack/agVirtualList.ts 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 AgVirtualList = class extends _AgTabGuardComp { constructor(stopPropagationCallbacks, params) { super(getVirtualListTemplate(params?.cssIdentifier || "default")); this.stopPropagationCallbacks = stopPropagationCallbacks; this.renderedRows = /* @__PURE__ */ new Map(); this.rowHeight = 20; this.pageSize = -1; this.isScrolling = false; this.isHeightFromTheme = true; this.eContainer = RefPlaceholder2; this.awaitStableCallbacks = []; this.registerCSS(agVirtualListCSS); const { cssIdentifier = "default", ariaRole = "listbox", listName, moveItemCallback } = params || {}; this.cssIdentifier = cssIdentifier; this.ariaRole = ariaRole; this.listName = listName; this.moveItemCallback = moveItemCallback; } 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.stopPropagationCallbacks ); this.refreshAriaProperties(); this.addManagedEventListeners({ stylesChanged: this.onStylesChanged.bind(this) }); } onStylesChanged(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; _setAriaRole(ariaEl, this.model?.getRowCount() > 0 ? this.ariaRole : "presentation"); _setAriaLabel(ariaEl, listName); } addResizeObserver() { const listener = () => _requestAnimationFrame(this.beans, () => this.drawVirtualRows()); const destroyObserver = _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 = _getAriaPosInSet(target) - 1; } } onFocusOut(e) { if (!this.getFocusableElement().contains(e.relatedTarget)) { this.lastFocusedRowIndex = null; } } handleKeyDown(e) { const { key, shiftKey } = e; switch (key) { case KeyCode.UP: case KeyCode.DOWN: { const isUp = key === KeyCode.UP; e.preventDefault(); if (shiftKey) { this.moveItem(isUp); } else { this.navigate(isUp); } } break; case KeyCode.PAGE_HOME: case KeyCode.PAGE_END: case KeyCode.PAGE_UP: case KeyCode.PAGE_DOWN: if (this.navigateToPage(key) !== null) { e.preventDefault(); } break; } } onTabKeyDown(e) { this.stopPropagationCallbacks?.stopPropagation(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 === KeyCode.PAGE_HOME) { newIndex = 0; } else if (key === KeyCode.PAGE_END) { newIndex = rowCount; } else if (key === KeyCode.PAGE_DOWN) { newIndex = Math.min(fromItem + this.pageSize, rowCount); } else if (key === 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); _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.beans.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) { 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(); _waitUntil( this, () => this.eContainer.clientHeight >= rowCount * this.rowHeight, () => { if (!this.isAlive()) { return; } const callbacks = this.awaitStableCallbacks; this.awaitStableCallbacks = []; for (const c of callbacks) { 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 = _createAgElement({ tag: "div", cls: `ag-virtual-list-item ag-${this.cssIdentifier}-virtual-list-item`, role, attrs: { tabindex: "-1" } }); _setAriaSetSize(eDiv, this.model.getRowCount()); _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); component.eDiv.remove(); 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/agStack/agVirtualListDragFeature.ts import { AutoScrollService, _AgBeanStub, _radioCssClass } from "ag-grid-community"; // packages/ag-grid-enterprise/src/agStack/agVirtualListDragFeature.css-GENERATED.ts var agVirtualListDragFeatureCSS = ( /*css*/ `.ag-list-item-hovered:after{background-color:var(--ag-accent-color);content:"";height:1px;left:0;position:absolute;right:0}.ag-item-highlight-top:after{top:0}.ag-item-highlight-bottom:after{bottom:0}` ); // packages/ag-grid-enterprise/src/agStack/agVirtualListDragFeature.ts var LIST_ITEM_HOVERED = "ag-list-item-hovered"; var AgVirtualListDragFeature = class extends _AgBeanStub { constructor(comp, virtualList, params) { super(); this.comp = comp; this.virtualList = virtualList; this.params = params; this.currentDragValue = null; this.lastHoveredListItem = null; } postConstruct() { this.beans.environment.addGlobalCSS(agVirtualListDragFeatureCSS, "component-AgVirtualListDragFeature"); this.params.addListeners(this, this.listItemDragStart.bind(this), 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.beans.dragAndDrop?.addDropTarget(dropTarget); } createAutoScrollService() { const virtualListGui = this.virtualList.getGui(); this.autoScrollService = new 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; _radioCssClass(el, LIST_ITEM_HOVERED); _radioCssClass(el, `ag-item-highlight-${hoveredListItem.position}`); } getListDragItem(e) { const virtualListGui = this.virtualList.getGui(); const paddingTop = Number.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(); for (const el of virtualListGui.querySelectorAll(`.${LIST_ITEM_HOVERED}`)) { for (const cls of [LIST_ITEM_HOVERED, "ag-item-highlight-top", "ag-item-highlight-bottom"]) { el.classList.remove(cls); } } this.lastHoveredListItem = null; } }; // packages/ag-grid-enterprise/src/agStack/agSlider.ts import { AgAbstractLabel, AgInputNumberFieldSelector, RefPlaceholder as RefPlaceholder3 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/agStack/agInputRange.ts import { AgAbstractInputField } from "ag-grid-community"; var AgInputRange = class extends 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/agStack/agSlider.ts var AgSlider = class extends AgAbstractLabel { constructor(config) { super( config, /* html */ `
`, [AgInputRangeSelector, AgInputNumberFieldSelector] ); this.eLabel = RefPlaceholder3; this.eSlider = RefPlaceholder3; this.eText = RefPlaceholder3; 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/agStack/agColorPicker.ts import { AgPickerField, _createElement } from "ag-grid-community"; // packages/ag-grid-enterprise/src/agStack/agColorPanel.ts import { KeyCode as KeyCode2, RefPlaceholder as RefPlaceholder5, _AgComponentStub, _exists as _exists2, _setDisplayed } from "ag-grid-community"; // packages/ag-grid-enterprise/src/agStack/agColorInput.ts import { AgInputTextField, RefPlaceholder as RefPlaceholder4 } from "ag-grid-community"; var AgColorInput = class extends AgInputTextField { constructor() { super({ template: { 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" } ] } ] } }); this.eColor = RefPlaceholder4; } wireBeans(beans) { 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.getLocaleTextFunc()("invalidColor", "Color value is invalid") ); 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/agStack/agColorPanel.ts var maxRecentColors = 8; var sharedRecentColors = []; var AgColorPanel = class extends _AgComponentStub { constructor(config) { super( /* html */ `
`, [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 = RefPlaceholder5; this.spectrumVal = RefPlaceholder5; this.spectrumDragger = RefPlaceholder5; this.spectrumHue = RefPlaceholder5; this.spectrumHueSlider = RefPlaceholder5; this.spectrumAlpha = RefPlaceholder5; this.spectrumAlphaSlider = RefPlaceholder5; this.colorInput = RefPlaceholder5; this.recentColors = RefPlaceholder5; 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 === KeyCode2.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 === KeyCode2.ENTER || e.key === KeyCode2.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 === KeyCode2.LEFT; const isRight = e.key === KeyCode2.RIGHT; const isUp = e.key === KeyCode2.UP; const isDown = e.key === KeyCode2.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 === KeyCode2.LEFT; const isRight = e.key === KeyCode2.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 */ `
` ); }); this.recentColors.innerHTML = colorsHtmlStr.join(""); _setDisplayed(this.recentColors, !!recentColors.length); } setValue(val) { const color = this._Color.fromString(val); this.setColor(color, true); } setColor(color, updateColorInput) { const [h, s2, 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(s2, b, !updateColorInput); } onRecentColorClick(e) { const target = e.target; if (!_exists2(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/agStack/agDialog.ts import { _AgComponentStub as _AgComponentStub3, _AgTabGuardFeature, _findNextFocusableElement, _setDisplayed as _setDisplayed3 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/agStack/agPanel.ts import { RefPlaceholder as RefPlaceholder6, _AgComponentStub as _AgComponentStub2, _AgPositionableFeature, _getActiveDomElement, _getInnerHeight, _getInnerWidth, _isVisible, _setDisplayed as _setDisplayed2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/agStack/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-family:var(--ag-panel-title-bar-font-family);font-size:var(--ag-panel-title-bar-font-size);font-weight:var(--ag-panel-title-bar-font-weight);height:var(--ag-panel-title-bar-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/agStack/agPanel.ts function getTemplate(cssIdentifier) { cssIdentifier ?? (cssIdentifier = 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 _AgComponentStub2 { constructor(config) { super(getTemplate(config.cssIdentifier)); this.config = config; this.closable = true; this.eContentWrapper = RefPlaceholder6; this.eTitleBar = RefPlaceholder6; this.eTitleBarButtons = RefPlaceholder6; this.eTitle = RefPlaceholder6; 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 _AgPositionableFeature( 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 { _setDisplayed2(this.eTitleBar, false); } this.addManagedElementListeners(this.eTitleBar, { mousedown: (e) => { if (eGui.contains(e.relatedTarget) || eGui.contains(_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, mouseEvent } = postProcessPopupParams; postProcessCallback = () => beans.popupSvc?.callPostProcessPopup(postProcessPopupParams, type, eGui, eventSource, mouseEvent); } positionableFeature.initialisePosition(postProcessCallback); this.eContentWrapper.style.height = "0"; } renderComponent() { const eGui = this.getGui(); eGui.focus(); this.close = () => { eGui.remove(); 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 _AgComponentStub2({ tag: "div", cls: "ag-button" }); this.createBean(closeButtonComp); const eGui = closeButtonComp.getGui(); const child = this.beans.iconSvc.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.remove(); 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.prepend(eGui); } else if (position === len) { eTitleBarButtons.append(eGui); } else { buttons[position - 1].after(eGui); } button.setParentComponent(this); } getBodyHeight() { return _getInnerHeight(this.eContentWrapper); } getBodyWidth() { return _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 && _isVisible(eGui)) { this.close(); } super.destroy(); } }; // packages/ag-grid-enterprise/src/agStack/agDialog.ts var AgDialog = class extends AgPanel { constructor(config, callbacks) { super({ ...config, popup: true }); this.callbacks = callbacks; 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 _AgTabGuardFeature(this, this.callbacks?.stopPropagationCallbacks) ); this.tabGuardFeature.initialiseTabGuard({ isFocusableContainer: true, onFocusIn: () => { this.popupSvc?.bringPopupToFront(eGui); }, onTabKeyDown: (e) => { if (modal) { return; } const backwards = e.shiftKey; const nextFocusableElement = _findNextFocusableElement(this.beans, eGui, false, backwards); if (!nextFocusableElement || this.tabGuardFeature.getTabGuardCtrl().isTabGuard(nextFocusableElement)) { if (this.callbacks?.focusNextContainer(this.beans, backwards)) { e.preventDefault(); } } } }); if (movable) { this.setMovable(movable); } if (maximizable) { this.setMaximizable(maximizable); } if (resizable) { this.setResizable(resizable); } if (!this.config.modal) { this.callbacks?.configureFocusableContainer(this.beans, 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() { _setDisplayed3(this.maximizeIcon, !this.isMaximized); _setDisplayed3(this.minimizeIcon, this.isMaximized); } clearMaximizebleListeners() { if (this.maximizeListeners.length) { for (const destroyListener of this.maximizeListeners) { 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 _AgComponentStub3({ tag: "div", cls: "ag-dialog-button" })); const eGui = maximizeButtonComp.getGui(); const iconSvc = this.beans.iconSvc; this.maximizeIcon = iconSvc.createIconNoSpan("maximize"); eGui.appendChild(this.maximizeIcon); this.maximizeIcon.classList.add("ag-panel-title-bar-button-icon"); this.minimizeIcon = iconSvc.createIconNoSpan("minimize"); eGui.appendChild(this.minimizeIcon); this.minimizeIcon.classList.add("ag-panel-title-bar-button-icon"); return maximizeButtonComp; } }; // packages/ag-grid-enterprise/src/agStack/agColorPicker.ts var AgColorPicker = class extends AgPickerField { constructor(config) { super({ pickerAriaLabelKey: "ariaLabelColorPicker", pickerAriaLabelValue: "Color Picker", pickerType: "ag-list", className: "ag-color-picker", pickerIcon: "chartsColorPicker", ...config }); } postConstruct() { this.eDisplayFieldColor = _createElement({ tag: "span", cls: "ag-color-picker-color" }); this.eDisplayFieldText = _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 } }, this.config.dialogCallbacks ) ); 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/agStack/agMenuList.ts import { AgPromise, KeyCode as KeyCode5, _AgTabGuardComp as _AgTabGuardComp3, _createAgElement as _createAgElement2, _last as _last2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/agStack/agMenuItemComponent.ts import { KeyCode as KeyCode4, _AgBeanStub as _AgBeanStub2, _createElement as _createElement2, _setAriaDisabled, _setAriaExpanded, _setAriaHasPopup, _setAriaRole as _setAriaRole2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/agStack/agMenuPanel.ts import { KeyCode as KeyCode3, _AgTabGuardComp as _AgTabGuardComp2 } from "ag-grid-community"; var AgMenuPanel = class extends _AgTabGuardComp2 { 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 === KeyCode3.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/agStack/agMenuItemComponent.ts var AgMenuItemComponent = class extends _AgBeanStub2 { constructor(callbacks) { super(); this.callbacks = callbacks; this.ACTIVATION_DELAY = 80; this.isActive = false; this.subMenuIsOpen = false; this.subMenuIsOpening = false; this.suppressRootStyles = true; this.suppressAria = true; this.suppressFocus = true; } 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"; return this.callbacks.getMenuItemComp(this.beans, this.params, { ...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() }).then((comp) => { if (!comp) { return; } this.menuItemComp = comp; const configureDefaults = comp.configureDefaults?.(); if (configureDefaults) { this.configureDefaults(configureDefaults === true ? void 0 : configureDefaults); } }); } 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 === KeyCode4.ENTER || e.key === KeyCode4.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 = _createElement2({ tag: "div", cls: "ag-menu", role: "presentation" }); 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, this.callbacks) ); 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.beans.popupSvc; const positionCallback = () => { const eventSource = this.eGui; popupSvc?.positionPopupForMenu({ eventSource, ePopup, event: event instanceof MouseEvent ? event : void 0, additionalParams: this.callbacks.getPostProcessPopupParams(this.contextParams) }); }; 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) { _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) { this.callbacks.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( this.gos.addCommon({ ...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); for (const it of cssClasses ?? []) { 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; _setAriaRole2(eGui, hasCheck ? "menuitemcheckbox" : "menuitem"); if (subMenu) { _setAriaHasPopup(eGui, subMenuRole ?? "menu"); } if (disabled) { _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.beans.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/agStack/agMenuList.ts var AgMenuList = class extends _AgTabGuardComp3 { constructor(level = 0, menuActionParams, callbacks) { super({ tag: "div", cls: "ag-menu-list", role: "menu" }); this.level = level; this.menuActionParams = menuActionParams; this.callbacks = callbacks; this.menuItems = []; } postConstruct() { this.initialiseTabGuard({ onTabKeyDown: (e) => this.onTabKeyDown(e), handleKeyDown: (e) => this.callbacks.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 KeyCode5.UP: case KeyCode5.RIGHT: case KeyCode5.DOWN: case KeyCode5.LEFT: e.preventDefault(); this.handleNavKey(e.key); break; case KeyCode5.ESCAPE: if (this.closeIfIsChild()) { this.callbacks.stopPropagationCallbacks.stopPropagation(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; } AgPromise.all( menuItems.map((menuItemOrString) => { if (menuItemOrString === "separator") { return AgPromise.resolve({ eGui: this.createSeparator() }); } else if (typeof menuItemOrString === "string") { this.callbacks.warnNoItem?.(menuItemOrString); return AgPromise.resolve({ eGui: null }); } else { return this.addItem(menuItemOrString); } }) ).then((elements) => { for (const element of elements ?? []) { if (element?.eGui) { this.appendChild(element.eGui); if (element.comp) { this.menuItems.push(element.comp); } } } }); } addItem(menuItemDef) { const menuItem = this.createManagedBean( new AgMenuItemComponent(this.callbacks) ); return menuItem.init({ menuItemDef, isAnotherSubMenuOpen: () => this.menuItems.some((m) => m.isSubMenuOpen()), level: this.level, contextParams: this.menuActionParams }).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 _createAgElement2({ tag: "div", cls: "ag-menu-separator", attrs: { "aria-hidden": "true" }, children: [part, part, part, part] }); } handleNavKey(key) { switch (key) { case KeyCode5.UP: case KeyCode5.DOWN: { const nextItem = this.findNextItem(key === KeyCode5.UP); if (nextItem && nextItem !== this.activeMenuItem) { nextItem.activate(false, true); } return; } } const left = this.gos.get("enableRtl") ? KeyCode5.RIGHT : KeyCode5.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 ? _last2(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/agStack/agContextMenuService.ts import { _AgBeanStub as _AgBeanStub3, _AgComponentStub as _AgComponentStub4, _anchorElementToMouseMoveEvent, _createAgElement as _createAgElement3, _focusInto, _getPageBody, _getRootNode, _isPromise, _isVisible as _isVisible2 } from "ag-grid-community"; var CSS_MENU = "ag-menu"; var CSS_CONTEXT_MENU_LOADING_ICON = "ag-context-menu-loading-icon"; var AgContextMenuService = class extends _AgBeanStub3 { constructor(params) { super(); this.params = params; this.destroyLoadingSpinner = null; this.lastPromise = 0; } hideActiveMenu() { this.destroyBean(this.activeMenu); } showMenu(menuActionParams, mouseEvent, anchorToElement) { const { getMenuItems, shouldBlockMenuOpen: shouldBlockMenu } = this.params; const menuItems = getMenuItems(menuActionParams, mouseEvent); if (_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?.length && // check if the element that triggered the context menu was removed from the DOM (isFromFakeEvent || _isVisible2(target)) && !shouldBlockMenu?.() ); if (shouldShowMenu) { this.createContextMenu({ menuItems: menuItems2, menuActionParams, mouseEvent, anchorToElement }); } this.destroyLoadingSpinner?.(); }); return true; } if (!menuItems?.length) { return false; } this.createContextMenu({ menuItems, menuActionParams, mouseEvent, anchorToElement }); return true; } createLoadingIcon(mouseEvent) { const { beans } = this; const translate = this.getLocaleTextFunc(); const loadingIcon = beans.iconSvc.createIconNoSpan("loadingMenuItems"); const wrapperEl = _createAgElement3({ tag: "div", cls: CSS_CONTEXT_MENU_LOADING_ICON }); wrapperEl.appendChild(loadingIcon); const rootNode = _getRootNode(beans); const targetEl = _getPageBody(beans); if (!targetEl) { return; } targetEl.appendChild(wrapperEl); beans.ariaAnnounce?.announceValue( translate("ariaLabelLoadingContextMenu", "Loading Context Menu"), "contextmenu" ); beans.environment.applyThemeClasses(wrapperEl); _anchorElementToMouseMoveEvent(wrapperEl, mouseEvent, beans); const mouseMoveCallback = (e) => { _anchorElementToMouseMoveEvent(wrapperEl, e, beans); }; rootNode.addEventListener("mousemove", mouseMoveCallback); this.destroyLoadingSpinner = () => { rootNode.removeEventListener("mousemove", mouseMoveCallback); wrapperEl.remove(); this.destroyLoadingSpinner = null; }; } createContextMenu(params) { const { mapMenuItems, menuItemCallbacks, beforeMenuOpen, onMenuClose, afterMenuDestroyed, onVisibleChanged, onMenuOpen } = this.params; const { menuItems, menuActionParams, mouseEvent, anchorToElement } = params; const popupSvc = this.beans.popupSvc; const getMenuItems = mapMenuItems ? (getGui) => mapMenuItems(menuItems, menuActionParams, getGui) : () => menuItems; const menu = new ContextMenu(getMenuItems, menuActionParams, menuItemCallbacks); this.createBean(menu); const eMenuGui = menu.getGui(); beforeMenuOpen?.(menuActionParams); const positionParams = { additionalParams: menuItemCallbacks.getPostProcessPopupParams(menuActionParams), 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) => { menuItemCallbacks.preserveRangesWhile(this.beans, () => { onMenuClose?.(); this.destroyBean(menu); afterMenuDestroyed?.(); onVisibleChanged?.(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) { onMenuOpen?.(); 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"; onVisibleChanged?.(true, isApi ? "api" : "ui"); } destroy() { this.destroyLoadingSpinner?.(); super.destroy(); } }; var ContextMenu = class extends _AgComponentStub4 { constructor(getMenuItems, menuActionParams, callbacks) { super({ tag: "div", cls: CSS_MENU, role: "presentation" }); this.getMenuItems = getMenuItems; this.menuActionParams = menuActionParams; this.callbacks = callbacks; this.menuList = null; } postConstruct() { const menuList = this.createManagedBean( new AgMenuList(0, this.menuActionParams, this.callbacks) ); const menuItemsMapped = this.getMenuItems(() => this.getGui()); menuList.addMenuItems(menuItemsMapped); this.appendChild(menuList); this.menuList = menuList; menuList.addEventListener("closeMenu", (e) => this.dispatchLocalEvent(e)); } afterGuiAttached({ hidePopup }) { if (hidePopup) { this.addDestroyFunc(hidePopup); } const menuList = this.menuList; if (menuList) { this.callbacks.preserveRangesWhile(this.beans, () => _focusInto(menuList.getGui())); } } }; // packages/ag-grid-enterprise/src/agStack/agMenuItemRenderer.ts import { _AgComponentStub as _AgComponentStub5, _createAgElement as _createAgElement4, _isNodeOrElement, _setAriaChecked, _setAriaExpanded as _setAriaExpanded2 } from "ag-grid-community"; var AgMenuItemRenderer = class extends _AgComponentStub5 { constructor(callbacks) { super({ tag: "div" }); this.callbacks = callbacks; } 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) { _setAriaChecked(eGui, checked); } if (subMenu) { _setAriaExpanded2(eGui, false); } } addIcon() { if (this.params.isCompact) { return; } const iconWrapper = _createAgElement4({ tag: "span", ref: "eIcon", cls: `${this.getClassName("part")} ${this.getClassName("icon")}`, role: "presentation" }); const { checked, icon } = this.params; if (checked) { iconWrapper.appendChild(this.beans.iconSvc.createIconNoSpan("check")); } else if (icon) { if (_isNodeOrElement(icon)) { iconWrapper.appendChild(icon); } else if (typeof icon === "string") { iconWrapper.innerHTML = icon; } else { this.callbacks?.warnNoIcon?.(); } } this.getGui().appendChild(iconWrapper); } addName() { const name = _createAgElement4({ 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 = _createAgElement4({ tag: "span", ref: "eShortcut", cls: `${this.getClassName("part")} ${this.getClassName("shortcut")}`, children: this.params.shortcut || "" }); this.getGui().appendChild(shortcut); } addSubMenu() { const pointer = _createAgElement4({ 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(this.beans.iconSvc.createIconNoSpan(iconName)); } eGui.appendChild(pointer); } getClassName(suffix) { return `${this.cssClassPrefix}-${suffix}`; } }; // packages/ag-grid-enterprise/src/agStack/agTabbedLayout.ts import { KeyCode as KeyCode6, RefPlaceholder as RefPlaceholder7, _AgTabGuardComp as _AgTabGuardComp4, _clearElement, _createAgElement as _createAgElement5, _findNextFocusableElement as _findNextFocusableElement2, _focusInto as _focusInto2, _getActiveDomElement as _getActiveDomElement2, _getDocument as _getDocument2, _isKeyboardMode, _setAriaLabel as _setAriaLabel2, _setAriaRole as _setAriaRole3 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/misc/enterpriseFocusUtils.ts import { TabGuardClassNames, _FOCUS_MANAGED_CLASS, _findFocusableElements } from "ag-grid-community"; function findFocusableElementBeforeTabGuard(rootNode, referenceElement) { if (!referenceElement) { return null; } const focusableElements = _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(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(`.${_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/agStack/agTabbedLayout.ts 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 AgTabbedLayout = class extends _AgTabGuardComp4 { constructor(params) { super(getTabbedLayoutTemplate(params.cssClass)); this.eHeader = RefPlaceholder7; this.eBody = RefPlaceholder7; this.items = []; this.tabbedItemScrollMap = /* @__PURE__ */ new Map(); this.params = params; } postConstruct() { this.setupHeader(); if (this.params.items) { for (const item of this.params.items) { 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 = _createAgElement5({ tag: "div", role: "presentation" }); addCssClasses(this.eHeader, "header-wrapper"); this.eHeader.appendChild(this.eTabHeader); } else { this.eTabHeader = this.eHeader; } _setAriaRole3(this.eTabHeader, "tablist"); addCssClasses(this.eTabHeader, "header"); } setupCloseButton(addCssClasses) { const eCloseButton = _createAgElement5({ tag: "button" }); addCssClasses(eCloseButton, "close-button"); const eIcon = this.beans.iconSvc.createIconNoSpan("close"); _setAriaLabel2(eCloseButton, this.params.closeButtonAriaLabel); eCloseButton.appendChild(eIcon); this.addManagedElementListeners(eCloseButton, { click: () => this.params.onCloseClicked?.() }); const eCloseButtonWrapper = _createAgElement5({ 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 KeyCode6.RIGHT: case KeyCode6.LEFT: { if (!this.eTabHeader.contains(_getActiveDomElement2(this.beans))) { return; } const isRightKey = e.key === KeyCode6.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 KeyCode6.UP: case KeyCode6.DOWN: e.stopPropagation(); break; } } onTabKeyDown(e) { if (e.defaultPrevented) { return; } const { beans, eHeader, eBody, activeItem, params } = this; const { suppressTrapFocus, enableCloseButton } = params; const activeElement = _getActiveDomElement2(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(_getDocument2(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 = _findNextFocusableElement2(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 _focusInto2(this.eBody, fromBottom); } setAfterAttachedParams(params) { this.afterAttachedParams = params; } showFirstItem() { if (this.items.length > 0) { this.showItemWrapper(this.items[0]); } } addItem(item) { const eHeaderButton = _createAgElement5({ tag: "span", cls: "ag-tab", role: "tab", attrs: { tabindex: "-1" } }); eHeaderButton.appendChild(item.title); this.eTabHeader.appendChild(eHeaderButton); _setAriaLabel2(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(); } _clearElement(this.eBody); tabbedItem.bodyPromise.then((body) => { this.eBody.appendChild(body); const onlyUnmanaged = !_isKeyboardMode(); if (!this.params.suppressFocusBodyOnOpen) { _focusInto2(this.eBody, false, onlyUnmanaged); } if (tabbedItem.afterAttachedCallback) { tabbedItem.afterAttachedCallback(this.afterAttachedParams); } if (this.params.keepScrollPosition) { const scrollableContainer = 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/agStack/agGroupComponent.ts import { AgCheckboxSelector, AgToggleButton, KeyCode as KeyCode7, RefPlaceholder as RefPlaceholder8, _AgComponentStub as _AgComponentStub6, _isComponent, _removeFromParent, _setAriaExpanded as _setAriaExpanded3, _setAriaRole as _setAriaRole4, _setDisplayed as _setDisplayed4 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/agStack/agGroupComponent.css-GENERATED.ts var agGroupComponentCSS = ( /*css*/ `.ag-group{position:relative;width:100%}.ag-group-title-bar{align-items:center;display:flex;padding:var(--ag-spacing)}.ag-group-title{display:inline;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:where(.ag-group-title-bar) .ag-group-title{cursor:default}.ag-group-toolbar{align-items:center;display:flex;padding:var(--ag-spacing)}.ag-group-container{display:flex}.ag-disabled .ag-group-container{pointer-events:none}.ag-disabled-group-container,.ag-disabled-group-title-bar{opacity:.5}.ag-group-container-horizontal{flex-flow:row wrap}.ag-group-container-vertical{flex-direction:column}.ag-group-title-bar-icon{cursor:pointer;flex:none}:where(.ag-ltr) .ag-group-title-bar-icon{margin-right:var(--ag-spacing)}:where(.ag-rtl) .ag-group-title-bar-icon{margin-left:var(--ag-spacing)}:where(.ag-group-item-alignment-stretch) .ag-group-item{align-items:stretch}:where(.ag-group-item-alignment-start) .ag-group-item{align-items:flex-start}:where(.ag-group-item-alignment-end) .ag-group-item{align-items:flex-end}` ); // packages/ag-grid-enterprise/src/agStack/agGroupComponent.ts 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 _AgComponentStub6 { constructor(params = {}) { super( getAgGroupComponentTemplate(params), [AgCheckboxSelector] ); this.params = params; this.suppressEnabledCheckbox = true; this.suppressToggleExpandOnEnableChange = false; this.eToolbar = RefPlaceholder8; this.cbGroupEnabled = RefPlaceholder8; this.eContainer = RefPlaceholder8; this.registerCSS(agGroupComponentCSS); 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(); _setDisplayed4(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() { _setDisplayed4(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(); _setDisplayed4(this.eContainer, expanded); if (!silent) { this.dispatchLocalEvent({ type: expanded ? "expanded" : "collapsed" }); } return this; } addItems(items) { for (const item of items) { this.addItem(item); } } prependItem(item) { this.insertItem(item, true); } addItem(item) { this.insertItem(item, false); } updateItems(newItems) { const oldItems = this.items; let newIndex = 0; for (let prevIndex = 0; prevIndex < oldItems.length; ++prevIndex) { const ePrevItem = oldItems[prevIndex]; if (ePrevItem === newItems[newIndex]) { newIndex++; } else { const el = _isComponent(ePrevItem) ? ePrevItem.getGui() : ePrevItem; _removeFromParent(el); } } while (newIndex < newItems.length) { this.insertItem(newItems[newIndex++]); } this.items = newItems; } insertItem(item, prepend) { const container = this.eContainer; const el = _isComponent(item) ? item.getGui() : item; el.classList.add("ag-group-item", `ag-${this.cssIdentifier}-group-item`); if (prepend) { container.prepend(el); this.items.unshift(el); } else { container.appendChild(el); this.items.push(el); } } hideItem(hide, index) { const itemToHide = this.items[index]; _setDisplayed4(itemToHide, !hide); } getItemIndex(item) { const el = _isComponent(item) ? 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 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" : "group", 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 _AgComponentStub6 { constructor(params = {}) { super(getDefaultTitleBarTemplate(params)); this.suppressOpenCloseIcons = false; this.suppressKeyboardNavigation = false; this.eGroupOpenedIcon = RefPlaceholder8; this.eGroupClosedIcon = RefPlaceholder8; this.eTitle = RefPlaceholder8; 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() { const iconSvc = this.beans.iconSvc; this.eGroupClosedIcon.appendChild(iconSvc.createIconNoSpan("accordionClosed")); this.eGroupOpenedIcon.appendChild(iconSvc.createIconNoSpan("accordionOpen")); this.addManagedElementListeners(this.getGui(), { click: () => this.dispatchExpandChanged(), keydown: (e) => { switch (e.key) { case KeyCode7.ENTER: case KeyCode7.SPACE: e.preventDefault(); this.dispatchExpandChanged(); break; case KeyCode7.RIGHT: case KeyCode7.LEFT: e.preventDefault(); this.dispatchExpandChanged(e.key === KeyCode7.RIGHT); break; } } }); } refreshOnExpand(expanded) { this.refreshAriaStatus(expanded); this.refreshOpenCloseIcons(expanded); } refreshAriaStatus(expanded) { if (!this.suppressOpenCloseIcons) { _setAriaExpanded3(this.getGui(), expanded); } } refreshOpenCloseIcons(expanded) { const showIcon = !this.suppressOpenCloseIcons; _setDisplayed4(this.eGroupOpenedIcon, showIcon && expanded); _setDisplayed4(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 ?? ""; _setDisplayed4(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"); _setAriaRole4(eGui, "presentation"); } else { eGui.classList.remove(TITLE_BAR_DISABLED_CLASS); if (typeof this.title === "string" && !this.suppressKeyboardNavigation) { this.activateTabIndex([eGui]); _setAriaRole4(eGui, "group"); } else { eGui.removeAttribute("tabindex"); _setAriaRole4(eGui, "presentation"); } } } }; var AgGroupComponentSelector = { selector: "AG-GROUP-COMPONENT", component: AgGroupComponent }; // packages/ag-grid-enterprise/src/advancedFilter/advancedFilterModule.ts import { TooltipModule, _FilterCoreModule, _FilterValueModule, _PopupModule, _SharedDragAndDropModule } from "ag-grid-community"; // packages/ag-grid-enterprise/src/version.ts var VERSION = "35.1.0"; // 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: [], setLicenseKey: GridLicenseManager.setLicenseKey }; // 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(.ag-standard-button):where(:not(:disabled)){cursor:pointer;&:where(.ag-standard-button):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-line{width:var(--ag-advanced-filter-builder-indent-size)}.ag-advanced-filter-builder-item-tree-line-root{width:var(--ag-icon-size)}.ag-advanced-filter-builder-item-tree-line-root: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}.ag-advanced-filter-builder-item-tree-line-horizontal:after,.ag-advanced-filter-builder-item-tree-line-horizontal:before,.ag-advanced-filter-builder-item-tree-line-vertical-bottom:after,.ag-advanced-filter-builder-item-tree-line-vertical-bottom:before,.ag-advanced-filter-builder-item-tree-line-vertical-top:after,.ag-advanced-filter-builder-item-tree-line-vertical-top:before,.ag-advanced-filter-builder-item-tree-line-vertical:after,.ag-advanced-filter-builder-item-tree-line-vertical: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{display:flex;gap:var(--ag-spacing);padding: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)}.ag-advanced-filter-builder-virtual-list-item: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 import { BeanStub as BeanStub2, _exists as _exists3, _parseDateTimeFromString, _serialiseDate, _toStringOrNull } from "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", advancedFilterValidationNotABigInt: "Value is not a big integer", 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/colFilterExpressionParser.ts import { _parseBigIntOrNull } from "ag-grid-community"; // 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"); } }, bigint: () => { if (this.quotes || _parseBigIntOrNull(this.modelValue) === null) { this.valid = false; this.validationMessage = this.params.advFilterExpSvc.translate("advancedFilterValidationNotABigInt"); } }, 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, bigint: (operand) => _parseBigIntOrNull(operand), date: (operand) => this.params.valueSvc.parseValue(this.columnParser.column, null, operand, void 0), dateString: (operand) => this.operandValueGetters.date(operand), dateTime: (operand) => this.operandValueGetters.date(operand), dateTimeString: (operand) => this.operandValueGetters.date(operand), 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?.endPosition == null || position <= this.columnParser.endPosition + 1; } isOperatorPosition(position) { return 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" && baseCellDataType !== "bigint"; } 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 BeanStub2 { constructor() { super(...arguments); this.beanName = "advFilterExpSvc"; this.filterOperandGetters = { number: (model) => _toStringOrNull(model.filter) ?? "", bigint: (model) => _toStringOrNull(model.filter) ?? "", date: (model) => { const column = this.colModel.getColDefCol(model.colId); if (!column) { return null; } return this.valueSvc.formatValue( column, null, _parseDateTimeFromString(_toStringOrNull(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?.(_parseDateTimeFromString(_toStringOrNull(model.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) => _exists3(operand) ? Number(operand) : null, bigint: (operand) => operand, date: (operand, column, baseCellDataType) => _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 _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, filterType } = model; if (filter == null) { return ""; } let operand1 = this.filterOperandGetters[filterType]( model ); if (filterType !== "number" && filterType !== "bigint") { operand1 ?? (operand1 = _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"); for (const column of columns) { 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) => _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 }), bigint: 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 import { BeanStub as BeanStub6, _exists as _exists11, _isClientSideRowModel, _isServerSideRowModel, _warn as _warn4 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/advancedFilter/advancedFilterCtrl.ts import { BeanStub as BeanStub5, _getAbsoluteHeight, _getAbsoluteWidth, _removeFromParent as _removeFromParent4 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/widgets/dialog.ts import { _STOP_PROPAGATION_CALLBACKS, _focusNextGridCoreContainer } from "ag-grid-community"; var DIALOG_CALLBACKS = { stopPropagationCallbacks: _STOP_PROPAGATION_CALLBACKS, focusNextContainer: (beans, backwards) => { return _focusNextGridCoreContainer(beans, backwards); }, configureFocusableContainer: (beans, dialog) => { const gridCtrl = beans.ctrlsSvc.get("gridCtrl"); gridCtrl.addFocusableContainer(dialog); dialog.addDestroyFunc(() => gridCtrl.removeFocusableContainer(dialog)); } }; var Dialog = class extends AgDialog { constructor(config) { super(config, DIALOG_CALLBACKS); } }; // packages/ag-grid-enterprise/src/advancedFilter/advancedFilterComp.ts import { AgFilterButtonSelector, Component as Component4, RefPlaceholder as RefPlaceholder11, _createIconNoSpan, _makeNull as _makeNull2, _setDisabled, _setDisplayed as _setDisplayed5 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/advancedFilter/autocomplete/agAutocomplete.ts import { AgInputTextFieldSelector, Component as Component3, KeyCode as KeyCode9, RefPlaceholder as RefPlaceholder10, _isNothingFocused, _makeNull } from "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%;>:where(.ag-text-field){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}}.ag-autocomplete-virtual-list-item: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 import { AgPopupComponent, KeyCode as KeyCode8, RefPlaceholder as RefPlaceholder9, _exists as _exists5, _fuzzySuggestions, _isVisible as _isVisible3 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/widgets/virtualList.ts import { _STOP_PROPAGATION_CALLBACKS as _STOP_PROPAGATION_CALLBACKS2 } from "ag-grid-community"; var VirtualList = class extends AgVirtualList { constructor(params) { super(_STOP_PROPAGATION_CALLBACKS2, params); } }; // packages/ag-grid-enterprise/src/advancedFilter/autocomplete/agAutocompleteRow.ts import { Component as Component2, _clearElement as _clearElement2, _createElement as _createElement3, _exists as _exists4 } from "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 Component2 { 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 && _exists4(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; _clearElement2(child); child.append( // Start part value.slice(0, index), // Highlighted part wrapped in bold tag _createElement3({ 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 AgPopupComponent { constructor(params) { super(AgAutocompleteListElement); this.params = params; this.eList = RefPlaceholder9; this.searchString = ""; this.lastAutoListHeight = null; } 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); this.updateListHeight(); } onNavigationKeyDown(event, key) { event.preventDefault(); const oldIndex = this.autocompleteEntries.indexOf(this.selectedValue); const newIndex = key === KeyCode8.UP ? oldIndex - 1 : oldIndex + 1; this.checkSetSelectedValue(newIndex); } setSearch(searchString) { this.searchString = searchString; if (_exists5(searchString)) { this.runSearch(); } else { this.autocompleteEntries = this.params.autocompleteEntries; this.virtualList.refresh(); this.checkSetSelectedValue(0); this.updateListHeight(); } 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 }; } runStartsWithSearch(searchString, searchStrings) { const lowerCaseSearchString = searchString.toLocaleLowerCase(); const allMatches = searchStrings.filter( (string) => string.toLocaleLowerCase().startsWith(lowerCaseSearchString) ); const topMatch = allMatches[0]; return { topMatch, allMatches }; } runSearch() { const { autocompleteEntries, useFuzzySearch, useStartsWithSearch, forceLastSelection } = this.params; const searchStrings = autocompleteEntries.map((v) => v.displayValue ?? v.key); let matchingStrings; let topSuggestion; if (useFuzzySearch) { matchingStrings = _fuzzySuggestions({ inputValue: this.searchString, allSuggestions: searchStrings, hideIrrelevant: true }).values; topSuggestion = matchingStrings.length ? matchingStrings[0] : void 0; } else { const matches = useStartsWithSearch ? this.runStartsWithSearch(this.searchString, searchStrings) : this.runContainsSearch(this.searchString, searchStrings); matchingStrings = matches.allMatches; topSuggestion = matches.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(); this.updateListHeight(); if (!topSuggestion) { return; } const topSuggestionIndex = matchingStrings.indexOf(topSuggestion); this.checkSetSelectedValue(topSuggestionIndex); } updateSearchInList() { this.virtualList.forEachRenderedRow((row) => row.setSearchString(this.searchString)); } updateListHeight() { if (!this.params.autoSizeList) { return; } const rowCount = this.autocompleteEntries.length; const rowHeight = this.virtualList.getRowHeight(); const maxItems = this.params.maxVisibleItems ?? rowCount; const visibleCount = Math.min(rowCount, maxItems); let height = visibleCount * rowHeight; if (rowCount === 0) { height = rowHeight; } if (this.lastAutoListHeight === height) { return; } this.lastAutoListHeight = height; this.eList.style.height = `${height}px`; if (_isVisible3(this.eList)) { this.params.onListHeightChanged?.(); } } 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(); this.updateListHeight(); } 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 Component3 { constructor() { super(AgAutocompleteElement, [AgInputTextFieldSelector]); this.eAutocompleteInput = RefPlaceholder10; 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 = _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 KeyCode9.ENTER: this.onEnterKeyDown(event); break; case KeyCode9.TAB: this.onTabKeyDown(event); break; case KeyCode9.DOWN: case KeyCode9.UP: this.onUpDownKeyDown(event, key); break; case KeyCode9.LEFT: case KeyCode9.RIGHT: case KeyCode9.PAGE_HOME: case KeyCode9.PAGE_END: setTimeout(() => { this.updatePositionAndList(); }); break; case KeyCode9.ESCAPE: this.onEscapeKeyDown(event); break; case KeyCode9.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 || _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 _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 Component4 { constructor() { super(AdvancedFilterElement, [AgAutocompleteSelector, AgFilterButtonSelector]); this.eAutocomplete = RefPlaceholder11; this.eButtons = RefPlaceholder11; this.eBuilderFilterButton = RefPlaceholder11; this.eBuilderFilterButtonIcon = RefPlaceholder11; this.eBuilderFilterButtonLabel = RefPlaceholder11; 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) { _setDisplayed5(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(_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() }); _setDisplayed5(this.eBuilderFilterButton, !suppressed); } onValueChanged(value) { value = _makeNull2(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; _setDisabled(this.eBuilderFilterButton, true); this.advancedFilter.getCtrl().toggleFilterBuilder({ source: "ui", eventSource: this.eBuilderFilterButton }); } closeBuilder() { if (!this.builderOpen) { return; } this.builderOpen = false; _setDisabled(this.eBuilderFilterButton, false); this.eBuilderFilterButton.focus(); } }; // packages/ag-grid-enterprise/src/advancedFilter/advancedFilterHeaderComp.ts import { Component as Component5, KeyCode as KeyCode10, _clearElement as _clearElement3, _findNextFocusableElement as _findNextFocusableElement3, _focusInto as _focusInto3, _getActiveDomElement as _getActiveDomElement3, _getFloatingFiltersHeight, _setAriaColIndex, _setAriaColSpan, _setAriaRole as _setAriaRole5, _setAriaRowIndex, _setDisplayed as _setDisplayed6 } from "ag-grid-community"; var AdvancedFilterHeaderElement = { tag: "div", cls: "ag-advanced-filter-header", role: "row" }; var AdvancedFilterHeaderComp = class extends Component5 { 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, stylesChanged: 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(); _setAriaRole5(eAdvancedFilterGui, "gridcell"); _setAriaColIndex(eAdvancedFilterGui, 1); this.setAriaColumnCount(eAdvancedFilterGui); eGui.appendChild(eAdvancedFilterGui); } else { _clearElement3(eGui); this.destroyBean(this.eAdvancedFilter); this.height = 0; } _setDisplayed6(eGui, enabled); this.enabled = enabled; } setEnabledHeight() { const eGui = this.getGui(); this.height = _getFloatingFiltersHeight(this.beans); const height = `${this.height}px`; eGui.style.height = height; eGui.style.minHeight = height; } setAriaColumnCount(eAdvancedFilterGui) { _setAriaColSpan(eAdvancedFilterGui, this.colModel.getCols().length); } setAriaRowIndex() { _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 KeyCode10.ENTER: { if (this.hasFocus()) { if (_focusInto3(this.getFocusableElement())) { event.preventDefault(); } } break; } case KeyCode10.ESCAPE: if (!this.hasFocus()) { this.getFocusableElement().focus(); } break; case KeyCode10.UP: this.navigateUpDown(true, event); break; case KeyCode10.DOWN: this.navigateUpDown(false, event); break; case KeyCode10.TAB: if (this.hasFocus()) { this.navigateLeftRight(event); } else { const nextFocusableEl = _findNextFocusableElement3( 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 _getActiveDomElement3(this.beans) === this.getFocusableElement(); } }; // packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderComp.ts import { Component as Component13, FilterButtonComp, RefPlaceholder as RefPlaceholder17, _exists as _exists10, _removeFromParent as _removeFromParent3 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderDragFeature.ts import { BeanStub as BeanStub3, DragSourceType } from "ag-grid-community"; // packages/ag-grid-enterprise/src/features/virtualListDragFeature.ts var VirtualListDragFeature = class extends AgVirtualListDragFeature { }; // packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderDragFeature.ts var AdvancedFilterBuilderDragFeature = class extends BeanStub3 { constructor(comp, virtualList) { super(); this.comp = comp; this.virtualList = virtualList; } postConstruct() { this.createManagedBean( new VirtualListDragFeature(this.comp, this.virtualList, { dragSourceType: DragSourceType.AdvancedFilterBuilder, addListeners: (parent, listItemDragStart, listItemDragEnd) => { parent.addManagedListeners(this, { advancedFilterBuilderDragStarted: listItemDragStart, advancedFilterBuilderDragEnded: listItemDragEnd }); }, 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 import { Component as Component9, RefPlaceholder as RefPlaceholder14, _setAriaLabel as _setAriaLabel5, _setAriaLevel } from "ag-grid-community"; // packages/ag-grid-enterprise/src/advancedFilter/builder/addDropdownComp.ts import { AgInputTextFieldSelector as AgInputTextFieldSelector3, _setAriaLabel as _setAriaLabel4, _setAriaLabelledBy, _setDisplayed as _setDisplayed8, _stopPropagationForAgGrid as _stopPropagationForAgGrid2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/widgets/agRichSelect.ts import { AgInputTextFieldSelector as AgInputTextFieldSelector2, AgPickerField as AgPickerField2, KeyCode as KeyCode13, RefPlaceholder as RefPlaceholder13, _addGridCommonParams as _addGridCommonParams4, _clearElement as _clearElement6, _createIconNoSpan as _createIconNoSpan3, _debounce, _exists as _exists7, _fuzzySuggestions as _fuzzySuggestions2, _getActiveDomElement as _getActiveDomElement5, _getEditorRendererDetails as _getEditorRendererDetails2, _isElementOverflowingCallback as _isElementOverflowingCallback2, _isEventFromPrintableCharacter, _isVisible as _isVisible4, _setAriaActiveDescendant as _setAriaActiveDescendant2, _stopPropagationForAgGrid } from "ag-grid-community"; // packages/ag-grid-enterprise/src/widgets/AgPillContainer.ts import { Component as Component7, KeyCode as KeyCode11, _clearElement as _clearElement4, _findFocusableElements as _findFocusableElements2, _findNextFocusableElement as _findNextFocusableElement4, _getActiveDomElement as _getActiveDomElement4, _getDocument as _getDocument3, _setAriaPosInSet as _setAriaPosInSet2, _setAriaRole as _setAriaRole6, _setAriaSetSize as _setAriaSetSize2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/widgets/agPill.ts import { Component as Component6, RefPlaceholder as RefPlaceholder12 } from "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 Component6 { constructor(config) { super(AgPillElement); this.config = config; this.eText = RefPlaceholder12; this.eButton = RefPlaceholder12; } 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 Component7 { constructor() { super(AgPillContainerElement); this.pills = []; } init(params) { this.params = params; this.getKey = params.valueFormatter ?? ((v) => String(v)); this.refresh(); } refresh() { this.clearPills(); const { params, onPillKeyDown, getKey } = 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; _setAriaRole6(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(); _setAriaPosInSet2(pillGui, i + 1); _setAriaSetSize2(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({ key: getKey(value) ?? i.toString(), pill }); } } onNavigationKeyDown(e) { const { key } = e; if (!this.pills.length || key !== KeyCode11.LEFT && key !== KeyCode11.RIGHT) { return; } e.preventDefault(); const { params, beans } = this; const activeEl = _getActiveDomElement4(beans); const eGui = this.getGui(); if (eGui.contains(activeEl)) { const nextFocusableEl = _findNextFocusableElement4(beans, eGui, false, key === KeyCode11.LEFT); if (nextFocusableEl) { nextFocusableEl.focus(); } else if (params.eWrapper) { params.eWrapper.focus(); } } else { const focusableElements = _findFocusableElements2(eGui); if (focusableElements.length > 0) { focusableElements[key === KeyCode11.RIGHT ? 0 : focusableElements.length - 1].focus(); } } } clearPills() { const eGui = this.getGui(); if (eGui.contains(_getActiveDomElement4(this.beans)) && this.params.eWrapper) { this.params.eWrapper.focus(); } _clearElement4(eGui); this.destroyBeans(this.pills.map(({ pill }) => pill)); this.pills = []; } onPillButtonClick(pill) { this.deletePill(pill); } onPillKeyDown(e) { const key = e.key; if (key !== KeyCode11.DELETE && key !== KeyCode11.BACKSPACE) { return; } e.preventDefault(); const eDoc = _getDocument3(this.beans); const pillIndex = this.pills.findIndex(({ pill }) => pill.getGui().contains(eDoc.activeElement)); if (pillIndex === -1) { return; } const pillObj = this.pills[pillIndex]; if (pillObj?.pill) { this.deletePill(pillObj.pill, pillIndex); } } deletePill(p, restoreFocusToIndex) { const { getKey, pills, params } = this; const pillKey = (pills[restoreFocusToIndex ?? -1] ?? pills.find(({ pill }) => pill === p))?.key; const values = (params.getValue() || []).filter((val) => getKey(val) !== pillKey); params.setValue(values); if (!values.length && params.eWrapper) { params.eWrapper.focus(); } else if (restoreFocusToIndex != null) { const { pill } = pills[Math.min(restoreFocusToIndex, pills.length - 1)]; if (pill) { pill.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-virtual-list-viewport.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-rich-select-loading){display:flex;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}:where(.ag-ltr) .ag-pill-button{margin-left:var(--ag-spacing)}:where(.ag-rtl) .ag-pill-button{margin-right:var(--ag-spacing)}.ag-pill-button:hover{color:var(--ag-accent-color);cursor:pointer}` ); // packages/ag-grid-enterprise/src/widgets/agRichSelectList.ts import { KeyCode as KeyCode12, _createElement as _createElement5, _createIconNoSpan as _createIconNoSpan2, _requestAnimationFrame as _requestAnimationFrame2, _setAriaActiveDescendant, _setAriaControlsAndLabel, _setAriaLabel as _setAriaLabel3, _setDisplayed as _setDisplayed7 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/widgets/agRichSelectRow.ts import { Component as Component8, _addGridCommonParams as _addGridCommonParams3, _clearElement as _clearElement5, _createElement as _createElement4, _exists as _exists6, _getEditorRendererDetails, _isElementOverflowingCallback, _setAriaSelected, _toString } from "ag-grid-community"; var RichSelectRowElement = { tag: "div", cls: "ag-rich-select-row", role: "presentation" }; var RichSelectRow = class extends Component8 { 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( "highlightTooltipFeature", false, { getGui: () => this.getGui(), shouldDisplayTooltip: () => this.shouldDisplayTooltip?.() ?? true }, this ) ); } 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 || !_exists6(parsedValue)) { return; } let hasMatch = _exists6(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) { _clearElement5(child); child.append( // Start part parsedValue.slice(0, index), // Highlighted part wrapped in bold tag _createElement4({ 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(); _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); this.dispatchLocalEvent({ type: "itemHighlighted", highlighted }); } populateWithoutRenderer(value, valueFormatted) { const eGui = this.getGui(); const span = _createElement4({ tag: "span" }); span.style.overflow = "hidden"; span.style.textOverflow = "ellipsis"; const parsedValue = _toString(_exists6(valueFormatted) ? valueFormatted : value); this.parsedValue = _exists6(parsedValue) ? parsedValue : null; eGui.appendChild(span); this.renderValueWithoutRenderer(parsedValue); this.shouldDisplayTooltip = _isElementOverflowingCallback(() => span); this.tooltipFeature?.setTooltipAndRefresh(this.parsedValue); } renderValueWithoutRenderer(value) { const span = this.getGui().querySelector("span"); if (!span) { return; } span.textContent = _exists6(value) ? value : "\xA0"; } populateWithRenderer(value, valueFormatted) { let cellRendererPromise; let userCompDetails; const { cellRenderer, cellRendererParams } = this.params; if (cellRenderer) { const richSelect = this.getParentComponent()?.getParentComponent(); userCompDetails = _getEditorRendererDetails( this.userCompFactory, this.params, _addGridCommonParams3(this.gos, { value, valueFormatted, cellRendererParams, 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 STATE_LOADING = 0; var STATE_READY_WITH_RESULTS = 1; var STATE_NO_RESULTS = 2; var STATE_READY_FOR_INPUT = 3; 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.loadingState = STATE_READY_FOR_INPUT; this.params = params; this.setComponentCreator(this.createRowComponent.bind(this)); this.setComponentUpdater(() => { }); } postConstruct() { super.postConstruct(); const i18n = this.getLocaleTextFunc(); this.loadingLabel = i18n("loadingOoo", "Loading..."); this.noMatchesLabel = i18n("noMatches", "No matches to show"); this.eLoadingIcon = _createIconNoSpan2("richSelectLoading", this.beans, null); this.eStateCompLabel = _createElement5({ tag: "span", cls: "ag-loading-text", children: this.loadingLabel }); this.eStateComp = _createElement5({ tag: "div", cls: "ag-rich-select-loading", children: [ { tag: "span", cls: "ag-loading-icon", children: [this.eLoadingIcon ? () => this.eLoadingIcon : void 0] }, { tag: "span", cls: "ag-loading-text", children: [() => this.eStateCompLabel] } ] }); this.appendChild(this.eStateComp); 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); _setAriaLabel3(eListAriaEl, ariaLabel); _setAriaControlsAndLabel(this.richSelectWrapper, eListAriaEl); } setIsLoading() { this.setLoadingState(STATE_LOADING); } setLoadingState(state) { this.loadingState = state; this.toggleStateComp(); this.toggleVisibility(); } toggleStateComp() { const { eStateComp, eStateCompLabel, eLoadingIcon, loadingState, loadingLabel, noMatchesLabel, params } = this; if (!eStateComp) { return; } if (loadingState === STATE_LOADING) { eStateCompLabel.textContent = loadingLabel; if (eLoadingIcon) { _setDisplayed7(eLoadingIcon, true); } _setDisplayed7(eStateComp, true); return; } if (loadingState === STATE_NO_RESULTS && params.allowNoResultsCopy) { eStateCompLabel.textContent = noMatchesLabel; if (eLoadingIcon) { _setDisplayed7(eLoadingIcon, false); } _setDisplayed7(eStateComp, true); return; } _setDisplayed7(eStateComp, false); } shouldBeVisible() { if (this.loadingState === STATE_NO_RESULTS) { return !!this.params.allowNoResultsCopy; } return this.loadingState !== STATE_READY_FOR_INPUT; } toggleVisibility(forceVisible) { const eListGui = this.getGui(); if (forceVisible === void 0) { _setDisplayed7(eListGui, this.shouldBeVisible()); } else { _setDisplayed7(eListGui, forceVisible); } } navigateToPage(key) { const newIndex = super.navigateToPage(key, this.lastRowHovered); if (newIndex != null) { _requestAnimationFrame2(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) { _requestAnimationFrame2(this.beans, () => { if (!this.currentList || !this.isAlive()) { return; } const len = this.currentList.length; const oldIndex = this.lastRowHovered; const diff = key === KeyCode12.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 || 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) { const newState = getListStateBasedOnResults(list); this.setLoadingState(newState); list || (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()}`; _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?.length) { 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.eStateComp = void 0; } }; function getListStateBasedOnResults(valueList) { if (!valueList) { return STATE_READY_FOR_INPUT; } if (valueList.length) { return STATE_READY_WITH_RESULTS; } return STATE_NO_RESULTS; } // packages/ag-grid-enterprise/src/widgets/agRichSelect.ts var ON_SEARCH_CALLBACK_DEBOUNCE_DELAY = 300; 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 AgPickerField2 { 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: [AgInputTextFieldSelector2], 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 = RefPlaceholder13; this.eDeselect = RefPlaceholder13; this.skipWrapperAnnouncement = false; const { value, valueList, searchStringCreator, onSearch } = config || {}; if (value !== void 0) { this.value = value; } if (searchStringCreator) { this.searchStringCreator = searchStringCreator; } if (valueList != null) { this.setValueList({ valueList, isInitial: true }); } const { searchDebounceDelay = ON_SEARCH_CALLBACK_DEBOUNCE_DELAY } = this.config; if (onSearch) { this.onSearchCallbackDebounced = _debounce(this, onSearch, searchDebounceDelay); } 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(_createIconNoSpan3("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 = _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(fromPicker) { const { value, eDisplayField, config, gos } = this; const { allowTyping, cellRenderer, cellRendererParams, initialInputValue, multiSelect, suppressDeselectAll, suppressMultiSelectPillRenderer, valueFormatter, onSearch } = config; const valueFormatted = formatValueFn(value, valueFormatter); if (allowTyping) { this.eInput.setValue(initialInputValue ?? valueFormatted, !!fromPicker && !!onSearch); 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 = _getEditorRendererDetails2( this.userCompFactory, config, _addGridCommonParams4(this.gos, { value, valueFormatted, cellRendererParams, 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) { _clearElement6(eDisplayField); _bindCellRendererToHtmlElement(userCompDetailsPromise, eDisplayField); userCompDetailsPromise.then((renderer) => { this.addDestroyFunc(() => this.destroyBean(renderer)); }); } else { if (_exists7(this.value)) { eDisplayField.innerText = valueFormatted; eDisplayField.classList.remove("ag-display-as-placeholder"); } else { const { placeholder } = config; if (_exists7(placeholder)) { eDisplayField.textContent = placeholder; eDisplayField.classList.add("ag-display-as-placeholder"); } else { _clearElement6(eDisplayField); } } this.shouldDisplayTooltip = _isElementOverflowingCallback2(() => 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; } setValueListInternal(params) { const { listComponent, isPickerDisplayed, value } = this; const { valueList, refresh, isInitial } = params; if (isInitial) { this.setValues(valueList); } if (!listComponent) { return; } this.listComponent?.setCurrentList(valueList); if (!refresh) { return; } if (this.values) { listComponent.refresh(true); } else if (isPickerDisplayed) { const hasRefreshed = listComponent.selectValue(value); if (!hasRefreshed) { listComponent.refresh(); } } this.alignPickerToComponent(); } setValueList(params) { const { valueList } = params; if (!valueList || Array.isArray(valueList)) { this.setValueListInternal(params); return; } this.listComponent?.setIsLoading(); valueList.then((values) => { if (values) { this.setValueListInternal({ ...params, valueList: values }); } }); } /** * This method updates the list of select options */ setValues(values) { this.values = values; this.searchStrings = this.getSearchStringsFromValues(values || []); } showPicker() { const { listComponent, value } = this; if (!listComponent) { return; } super.showPicker(); let valueToUse = value; if (value === void 0) { valueToUse = null; } listComponent.selectValue(valueToUse); const idx = listComponent.getIndicesForValues(Array.isArray(valueToUse) ? valueToUse : [valueToUse])[0]; if (idx != null) { this.tooltipFeature?.attemptToHideTooltip(); listComponent.highlightIndex(idx); } else { listComponent.refresh(); } } createOrUpdatePillContainer(container) { if (!this.pillContainer) { const pillContainer = this.pillContainer = this.createBean(new AgPillContainer()); this.addDestroyFunc(() => { this.destroyBean(this.pillContainer); this.pillContainer = null; }); _clearElement6(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 === KeyCode13.BACKSPACE) { this.searchString = this.searchString.slice(0, -1); key = ""; } else if (!_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; } if (this.onSearchCallbackDebounced) { this.onSearchCallbackDebounced(this.searchString); return; } 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 : this.values || []); if (!this.highlightEmptyValue()) { this.highlightListValue(suggestions, filteredValues, shouldFilter); } if (highlightMatch && searchType !== "fuzzy") { this.listComponent?.highlightFilterMatch(this.searchString); } this.listComponent?.toggleVisibility(); } 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) { _setAriaActiveDescendant2(eListAriaEl, null); } } } } getSuggestionsAndFilteredValues(searchValue, valueList) { let suggestions = []; const filteredValues = []; if (!searchValue.length) { return { suggestions, filteredValues }; } const { searchType = "fuzzy", filterList } = this.config; const values = this.values || []; if (searchType === "fuzzy") { const fuzzySearchResult = _fuzzySuggestions2({ 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(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.includes(valueToMatch); if (filterList && isMatch) { filteredValues.push(values[idx]); } return isMatch; }); } return { suggestions, filteredValues }; } 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(fromPicker); } return this; } onNavigationKeyDown(event, key, announceItem) { event.preventDefault(); const isDown = key === KeyCode13.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 === void 0) { this.dispatchPickerEventAndHidePicker(this.value, true); } else { this.onListValueSelected(/* @__PURE__ */ new Set([lastRowHovered]), true); } } } onDeleteKeyDown(e) { const { eWrapper, beans } = this; const activeEl = _getActiveDomElement5(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 !== void 0) { 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 KeyCode13.LEFT: case KeyCode13.RIGHT: if (!allowTyping || this.pillContainer) { e.preventDefault(); if (this.pillContainer) { this.listComponent?.highlightIndex(-1); this.pillContainer.onNavigationKeyDown(e); } } break; case KeyCode13.PAGE_HOME: case KeyCode13.PAGE_END: if (allowTyping) { e.preventDefault(); const inputEl = this.eInput.getInputElement(); const target = key === KeyCode13.PAGE_HOME ? 0 : inputEl.value.length; inputEl.setSelectionRange(target, target); break; } case KeyCode13.PAGE_UP: case KeyCode13.PAGE_DOWN: e.preventDefault(); if (pickerComponent) { listComponent?.navigateToPage(key); } break; case KeyCode13.DOWN: case KeyCode13.UP: if (!isComposing) { this.onNavigationKeyDown(e, key, () => { if (multiSelect) { this.doWhileBlockingAnnouncement(() => this.eWrapper.focus()); this.announceAriaValue(this.ariaToggleSelection); } }); } break; case KeyCode13.ESCAPE: if (isPickerDisplayed) { if (_isVisible4(this.listComponent.getGui())) { e.preventDefault(); _stopPropagationForAgGrid(e); } this.hidePicker(); } break; case KeyCode13.ENTER: if (isComposing) { e.preventDefault(); } else { this.onEnterKeyDown(e); } break; case KeyCode13.SPACE: if (!allowTyping || isComposing) { e.preventDefault(); } if (!isComposing && isPickerDisplayed && multiSelect && listComponent) { const lastItemHovered = listComponent.getLastItemHovered(); if (lastItemHovered !== void 0) { listComponent.toggleListItemSelection(lastItemHovered); } } break; case KeyCode13.TAB: this.onTabKeyDown(); break; case KeyCode13.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: [AgInputTextFieldSelector3] }); this.params = params; } showPicker() { setTimeout(() => super.showPicker()); } hidePicker() { setTimeout(() => super.hidePicker()); } postConstruct() { super.postConstruct(); const { wrapperClassName, ariaLabel } = this.params; _setDisplayed8(this.eDisplayField, false); if (wrapperClassName) { this.eWrapper.classList.add(wrapperClassName); } _setAriaLabelledBy(this.eWrapper, ""); _setAriaLabel4(this.eWrapper, ariaLabel); } onEnterKeyDown(event) { _stopPropagationForAgGrid2(event); if (this.isPickerDisplayed) { super.onEnterKeyDown(event); } else { event.preventDefault(); this.showPicker(); } } }; // packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderItemNavigationFeature.ts import { BeanStub as BeanStub4, KeyCode as KeyCode14, _getActiveDomElement as _getActiveDomElement6, _isStopPropagationForAgGrid, _stopPropagationForAgGrid as _stopPropagationForAgGrid3 } from "ag-grid-community"; var AdvancedFilterBuilderItemNavigationFeature = class extends BeanStub4 { 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 KeyCode14.TAB: if (!event.defaultPrevented) { _stopPropagationForAgGrid3(event); } break; case KeyCode14.UP: case KeyCode14.DOWN: _stopPropagationForAgGrid3(event); break; case KeyCode14.ESCAPE: if (_isStopPropagationForAgGrid(event)) { return; } if (this.eGui.contains(_getActiveDomElement6(this.beans))) { event.preventDefault(); _stopPropagationForAgGrid3(event); this.focusWrapper.focus(); } break; } } }); const highlightClass = "ag-advanced-filter-builder-virtual-list-item-highlight"; this.addManagedListeners(this.focusWrapper, { keydown: (event) => { if (event.key === KeyCode14.ENTER) { if (_isStopPropagationForAgGrid(event)) { return; } if (_getActiveDomElement6(this.beans) === this.focusWrapper) { event.preventDefault(); _stopPropagationForAgGrid3(event); this.eFocusableComp.getFocusableElement().focus(); } } }, 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 ag-advanced-filter-builder-item-tree-line-vertical-top ag-advanced-filter-builder-item-tree-line-horizontal" } ] } ] } ] }; var AdvancedFilterBuilderItemAddComp = class extends Component9 { constructor(item, focusWrapper) { super(ItemAddElement); this.item = item; this.focusWrapper = focusWrapper; this.eItem = RefPlaceholder14; } wireBeans(beans) { this.advFilterExpSvc = beans.advFilterExpSvc; this.registry = beans.registry; } postConstruct() { _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) ); _setAriaLabel5( this.focusWrapper, this.advFilterExpSvc.translate("ariaAdvancedFilterBuilderItem", [ this.advFilterExpSvc.translate("advancedFilterBuilderAddButtonTooltip"), `${this.item.level + 1}` ]) ); } afterAdd() { } }; // packages/ag-grid-enterprise/src/advancedFilter/builder/advancedFilterBuilderItemComp.ts import { DragSourceType as DragSourceType2, KeyCode as KeyCode16, RefPlaceholder as RefPlaceholder16, TabGuardComp, _createElement as _createElement6, _createIconNoSpan as _createIconNoSpan4, _removeAriaExpanded, _setAriaDisabled as _setAriaDisabled2, _setAriaExpanded as _setAriaExpanded4, _setAriaLabel as _setAriaLabel8, _setAriaLevel as _setAriaLevel2, _setDisplayed as _setDisplayed10, _setVisible, _stopPropagationForAgGrid as _stopPropagationForAgGrid6 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/advancedFilter/builder/conditionPillWrapperComp.ts import { Component as Component10, _exists as _exists8, _removeFromParent as _removeFromParent2, _toStringOrNull as _toStringOrNull2 } from "ag-grid-community"; var ConditionPillWrapperComp = class extends Component10 { 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 (_exists8(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" || typeof filter === "bigint" ? _toStringOrNull2(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) { _removeFromParent2(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 = _exists8(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.eOperandPill?.getGui().remove(); this.destroyBean(this.eOperandPill); this.eOperandPill = void 0; } validate() { let validationMessage = null; if (!_exists8(this.getColumnKey())) { validationMessage = this.advFilterExpSvc.translate("advancedFilterBuilderValidationSelectColumn"); } else if (!_exists8(this.getOperatorKey())) { validationMessage = this.advFilterExpSvc.translate("advancedFilterBuilderValidationSelectOption"); } else if (this.numOperands > 0 && !_exists8(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 import { AgInputDateField, AgInputNumberField, AgInputTextField as AgInputTextField2, Component as Component11, KeyCode as KeyCode15, RefPlaceholder as RefPlaceholder15, _exists as _exists9, _setAriaDescribedBy, _setAriaLabel as _setAriaLabel6, _setDisplayed as _setDisplayed9, _stopPropagationForAgGrid as _stopPropagationForAgGrid4 } from "ag-grid-community"; var inputComponentDescriptors = { number: [AgInputNumberField], bigint: [AgInputTextField2], boolean: [AgInputTextField2], object: [AgInputTextField2], text: [AgInputTextField2], date: [AgInputDateField], dateString: [AgInputDateField], dateTime: [AgInputDateField, (i) => i.setIncludeTime(true)], dateTimeString: [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 Component11 { constructor(params) { super(InputPillElement); this.params = params; this.ePill = RefPlaceholder15; this.eLabel = RefPlaceholder15; 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()}`; _setAriaDescribedBy(this.ePill, this.eLabel.id); _setAriaLabel6(this.ePill, ariaLabel); this.renderValue(); this.addManagedListeners(this.ePill, { click: (event) => { event.preventDefault(); this.showEditor(); }, keydown: (event) => { if (event.key === KeyCode15.ENTER) { event.preventDefault(); _stopPropagationForAgGrid4(event); this.showEditor(); } } }); this.addDestroyFunc(() => this.destroyBean(this.eEditor)); } getFocusableElement() { return this.ePill; } showEditor() { if (this.eEditor) { return; } _setDisplayed9(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 KeyCode15.ENTER: event.preventDefault(); _stopPropagationForAgGrid4(event); this.updateValue(true); break; case KeyCode15.ESCAPE: event.preventDefault(); _stopPropagationForAgGrid4(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()); postConstruct?.(instance); return instance; } hideEditor(keepFocus) { const { eEditor } = this; if (!eEditor) { return; } this.eEditor = void 0; eEditor.getGui().remove(); this.destroyBean(eEditor); _setDisplayed9(this.ePill, true); if (keepFocus) { this.ePill.focus(); } } renderValue() { let value; const { displayValue, eLabel, params } = this; const { type } = params; const { classList } = eLabel; classList.remove( "ag-advanced-filter-builder-value-empty", "ag-advanced-filter-builder-value-number", "ag-advanced-filter-builder-value-text" ); if (!_exists9(displayValue)) { value = this.advFilterExpSvc.translate("advancedFilterBuilderEnterValue"); classList.add("ag-advanced-filter-builder-value-empty"); } else if (type === "number" || type === "bigint") { 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 import { Component as Component12 } from "ag-grid-community"; var JoinPillWrapperComp = class extends Component12 { 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 import { AgInputTextFieldSelector as AgInputTextFieldSelector4, _setAriaLabel as _setAriaLabel7, _setAriaLabelledBy as _setAriaLabelledBy2, _stopPropagationForAgGrid as _stopPropagationForAgGrid5 } from "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: [AgInputTextFieldSelector4] }); 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); _setAriaLabelledBy2(this.eWrapper, ""); _setAriaLabel7(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) { _stopPropagationForAgGrid5(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 TabGuardComp { constructor(item, dragFeature, focusWrapper) { super(AdvancedFilterBuilderItemElement); this.item = item; this.dragFeature = dragFeature; this.focusWrapper = focusWrapper; this.eTreeLines = RefPlaceholder16; this.eDragHandle = RefPlaceholder16; this.eButtons = RefPlaceholder16; this.eValidation = RefPlaceholder16; this.eMoveUpButton = RefPlaceholder16; this.eMoveDownButton = RefPlaceholder16; this.eAddButton = RefPlaceholder16; this.eRemoveButton = RefPlaceholder16; 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 = _createElement6({ tag: "div", cls: "ag-advanced-filter-builder-item-tree-line ag-advanced-filter-builder-item-tree-line-vertical-bottom ag-advanced-filter-builder-item-tree-line-root" }); this.eTreeLines.appendChild(eTreeLine); _setDisplayed10(this.eDragHandle, false); _setDisplayed10(this.eButtons, false); _setAriaExpanded4(this.focusWrapper, true); } else { this.setupTreeLines(level); this.eDragHandle.appendChild(_createIconNoSpan4("advancedFilterBuilderDrag", this.beans)); this.setupValidation(); this.setupMoveButtons(showMove); this.setupAddButton(); this.setupRemoveButton(); this.setupDragging(); this.updateAriaExpanded(); } _setAriaLevel2(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); _setAriaDisabled2(this.eMoveUpButton, !!disableMoveUp); _setAriaDisabled2(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( _createElement6({ tag: "div", cls: "ag-advanced-filter-builder-item-tree-line" }) ); } } 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(_createIconNoSpan4("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(_createIconNoSpan4("advancedFilterBuilderRemove", this.beans)); this.addManagedListeners(this.eRemoveButton, { click: () => this.removeItem(), keydown: (event) => { if (event.key === KeyCode16.ENTER) { event.preventDefault(); _stopPropagationForAgGrid6(event); this.removeItem(); } } }); this.createOptionalManagedBean( this.registry.createDynamicBean("tooltipFeature", false, { getGui: () => this.eRemoveButton, getLocation: () => "advancedFilter", getTooltipValue: () => this.advFilterExpSvc.translate("advancedFilterBuilderRemoveButtonTooltip") }) ); _setAriaLabel8(this.eRemoveButton, this.advFilterExpSvc.translate("advancedFilterBuilderRemoveButtonTooltip")); this.activateTabIndex([this.eRemoveButton]); } setupMoveButtons(showMove) { if (showMove) { this.eMoveUpButton.appendChild(_createIconNoSpan4("advancedFilterBuilderMoveUp", this.beans)); this.addManagedListeners(this.eMoveUpButton, { click: () => this.moveItem(true), keydown: (event) => { if (event.key === KeyCode16.ENTER) { event.preventDefault(); _stopPropagationForAgGrid6(event); this.moveItem(true); } } }); this.moveUpTooltipFeature = this.createOptionalManagedBean( this.registry.createDynamicBean("tooltipFeature", false, { getGui: () => this.eMoveUpButton, getLocation: () => "advancedFilter", getTooltipValue: () => this.moveUpDisabled ? null : this.advFilterExpSvc.translate("advancedFilterBuilderMoveUpButtonTooltip") }) ); _setAriaLabel8( this.eMoveUpButton, this.advFilterExpSvc.translate("advancedFilterBuilderMoveUpButtonTooltip") ); this.eMoveDownButton.appendChild(_createIconNoSpan4("advancedFilterBuilderMoveDown", this.beans)); this.addManagedListeners(this.eMoveDownButton, { click: () => this.moveItem(false), keydown: (event) => { if (event.key === KeyCode16.ENTER) { event.preventDefault(); _stopPropagationForAgGrid6(event); this.moveItem(false); } } }); this.moveDownTooltipFeature = this.createOptionalManagedBean( this.registry.createDynamicBean("tooltipFeature", false, { getGui: () => this.eMoveDownButton, getLocation: () => "advancedFilter", getTooltipValue: () => this.moveDownDisabled ? null : this.advFilterExpSvc.translate("advancedFilterBuilderMoveDownButtonTooltip") }) ); _setAriaLabel8( this.eMoveDownButton, this.advFilterExpSvc.translate("advancedFilterBuilderMoveDownButtonTooltip") ); this.activateTabIndex([this.eMoveUpButton, this.eMoveDownButton]); } else { _setDisplayed10(this.eMoveUpButton, false); _setDisplayed10(this.eMoveDownButton, false); } } updateValidity() { _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: DragSourceType2.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]); } _setAriaLabel8(this.focusWrapper, ariaLabel); } updateAriaExpanded() { _removeAriaExpanded(this.focusWrapper); const { filterModel } = this.item; if (filterModel?.filterType === "join" && filterModel.conditions.length) { _setAriaExpanded4(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 Component13 { constructor() { super(AdvancedFilterBuilderElement); this.eList = RefPlaceholder17; } 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 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) { _removeFromParent3(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") { for (const childFilterModel of filterModel.conditions) { 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 = []; for (const item of this.items) { if (!item.valid) { invalidModels.push(item.filterModel); } } this.buildList(); if (invalidModels.length) { for (const item of this.items) { 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 = this.advFilterExpSvc.translate("advancedFilterBuilderValidationIncomplete"); } this.eButtons?.updateValidity(isValid, validationMessage); } validateItems() { const clearOperator = (filterModel) => { filterModel.type = void 0; }; const clearOperand = (filterModel) => { delete filterModel.filter; }; for (const item of this.items) { if (!item.valid || !item.filterModel || item.filterModel.filterType === "join") { continue; } 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); continue; } const operatorForType = this.advFilterExpSvc.getDataTypeExpressionOperator(columnDetails.baseCellDataType); const operator = operatorForType.operators[filterModel.type]; if (!operator) { item.valid = false; clearOperator(filterModel); clearOperand(filterModel); continue; } if (operator.numOperands > 0 && !_exists10(filterModel.filter)) { item.valid = false; } } } }; // packages/ag-grid-enterprise/src/advancedFilter/advancedFilterCtrl.ts var AdvancedFilterCtrl = class extends BeanStub5 { 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?.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 Dialog({ 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(_getAbsoluteWidth(popupParent)) - 2; const maxHeight = Math.round(_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) { _removeFromParent4(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 BeanStub6 { 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; this.filterManager = beans.filterManager; } 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", () => { const updatedValidity = this.updateValidity(); if (updatedValidity) { this.filterManager?.onFilterChanged({ source: "advancedFilter" }); } }); } 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) => _exists11(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 = _isClientSideRowModel(this.gos) || _isServerSideRowModel(this.gos); if (enabled && !isValidRowModel) { _warn4(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", // loading async values richSelectLoading: "loading" }, apiFunctions: { getAdvancedFilterModel, setAdvancedFilterModel, showAdvancedFilterBuilder, hideAdvancedFilterBuilder }, dependsOn: [ EnterpriseCoreModule, _FilterCoreModule, _SharedDragAndDropModule, _PopupModule, _FilterValueModule, TooltipModule ], css: [advancedFilterCSS] }; // packages/ag-grid-enterprise/src/aiToolkit/aiToolkitModule.ts import { ColumnApiModule } from "ag-grid-community"; // packages/ag-grid-enterprise/src/aiToolkit/structuredSchema.ts import { STRUCTURED_SCHEMA_FEATURES } from "ag-grid-community"; // packages/ag-grid-enterprise/src/aiToolkit/schemaBuilder.ts var BaseSchemaBuilder = class { constructor(description) { this._defs = {}; this._nullable = false; this.description = description; } _collectNestedDefs(schemas) { const allDefs = { ...this._defs }; for (const schema of schemas) { if (schema && typeof schema === "object" && "$defs" in schema) { Object.assign(allDefs, schema.$defs); delete schema.$defs; } } return allDefs; } _toJSON(additionalProperties = {}) { const result = { type: this._nullable ? [this.type, "null"] : this.type, description: this.description, ...additionalProperties }; if (Object.keys(this._defs).length > 0) { result.$defs = this._defs; } return result; } nullable() { this._nullable = true; return this; } define(id, schema) { this._defs[id] = schema; return this; } }; var StringSchemaBuilder = class extends BaseSchemaBuilder { constructor(descriptionOrOptions) { super(typeof descriptionOrOptions === "string" ? descriptionOrOptions : descriptionOrOptions?.description); this.type = "string"; if (typeof descriptionOrOptions === "object" && descriptionOrOptions) { this._pattern = descriptionOrOptions.pattern; this._format = descriptionOrOptions.format; } } pattern(input) { this._pattern = input; return this; } format(input) { this._format = input; return this; } toJSON() { return this._toJSON({ pattern: this._pattern, format: this._format }); } }; var NumberSchemaBuilder = class extends BaseSchemaBuilder { constructor(descriptionOrOptions) { super(typeof descriptionOrOptions === "string" ? descriptionOrOptions : descriptionOrOptions?.description); this.type = "number"; if (typeof descriptionOrOptions === "object" && descriptionOrOptions) { this._minimum = descriptionOrOptions.minimum; this._maximum = descriptionOrOptions.maximum; this._exclusiveMinimum = descriptionOrOptions.exclusiveMinimum; this._exclusiveMaximum = descriptionOrOptions.exclusiveMaximum; this._multipleOf = descriptionOrOptions.multipleOf; } } minimum(value) { this._minimum = value; return this; } exclusiveMinimum(value) { this._exclusiveMinimum = value; return this; } maximum(value) { this._maximum = value; return this; } exclusiveMaximum(value) { this._exclusiveMaximum = value; return this; } multipleOf(value) { this._multipleOf = value; return this; } toJSON() { return this._toJSON({ minimum: this._minimum, exclusiveMinimum: this._exclusiveMinimum, maximum: this._maximum, exclusiveMaximum: this._exclusiveMaximum, multipleOf: this._multipleOf }); } }; var EnumSchemaBuilder = class extends BaseSchemaBuilder { constructor(_enum, description) { super(description); this._enum = _enum; this.type = "string"; } toJSON() { return this._toJSON({ enum: this._enum }); } }; var LiteralSchemaBuilder = class extends EnumSchemaBuilder { constructor(value, description) { super([value], description); } }; var BooleanSchemaBuilder = class extends BaseSchemaBuilder { constructor(description) { super(description); this.type = "boolean"; } toJSON() { return this._toJSON(); } }; var ArraySchemaBuilder = class extends BaseSchemaBuilder { constructor(items, descriptionOrOptions) { super(typeof descriptionOrOptions === "string" ? descriptionOrOptions : descriptionOrOptions?.description); this.items = items; this.type = "array"; if (typeof descriptionOrOptions === "object" && descriptionOrOptions) { this._minItems = descriptionOrOptions.minItems; this._maxItems = descriptionOrOptions.maxItems; } } minItems(value) { this._minItems = value; return this; } maxItems(value) { this._maxItems = value; return this; } toJSON() { const itemsSchema = this.items.toJSON(); const allDefs = this._collectNestedDefs([itemsSchema]); this._defs = allDefs; return this._toJSON({ items: itemsSchema, minItems: this._minItems, maxItems: this._maxItems }); } }; var ObjectSchemaBuilder = class extends BaseSchemaBuilder { constructor(properties, description) { super(description); this.properties = properties; this.type = "object"; } toJSON() { const propertySchemas = Object.fromEntries( Object.keys(this.properties).map((key) => [key, this.properties[key].toJSON()]) ); const allDefs = this._collectNestedDefs(Object.values(propertySchemas)); this._defs = allDefs; return this._toJSON({ required: Object.keys(this.properties), additionalProperties: false, properties: propertySchemas }); } }; var UnionSchemaBuilder = class { constructor(schemas, description) { this.schemas = schemas; this._nullable = false; this._defs = {}; this.description = description; } nullable() { this._nullable = true; return this; } define(id, schema) { this._defs[id] = schema; return this; } _collectNestedDefs(schemas) { const allDefs = this._defs; for (const schema of schemas) { if (schema && typeof schema === "object" && "$defs" in schema) { Object.assign(allDefs, schema.$defs); delete schema.$defs; } } return allDefs; } toJSON() { const schemaJsons = this.schemas.map((x) => x.toJSON()); const allDefs = this._collectNestedDefs(schemaJsons); const result = { anyOf: this._nullable ? [...schemaJsons, { type: "null" }] : schemaJsons }; if (this.description) { result.description = this.description; } if (Object.keys(allDefs).length > 0) { result.$defs = allDefs; } return result; } }; var ReferenceSchemaBuilder = class { constructor(id) { this.id = id; } nullable() { return this; } toJSON() { return { $ref: `#/$defs/${this.id}` }; } }; var s = { string: (descriptionOrOptions) => new StringSchemaBuilder(descriptionOrOptions), number: (descriptionOrOptions) => new NumberSchemaBuilder(descriptionOrOptions), enum: (values, description) => new EnumSchemaBuilder(values, description), boolean: (description) => new BooleanSchemaBuilder(description), array: (items, descriptionOrOptions) => new ArraySchemaBuilder(items, descriptionOrOptions), object: (properties, description) => new ObjectSchemaBuilder(properties, description), union: (schemas, description) => new UnionSchemaBuilder(schemas, description), literal: (value, description) => new LiteralSchemaBuilder(value, description), ref: (id) => new ReferenceSchemaBuilder(id) }; // packages/ag-grid-enterprise/src/aiToolkit/features/aggregationFeatureSchema.ts var buildAggregationFeatureSchema = (beans) => { const { aggFuncSvc } = beans; if (!aggFuncSvc) { return; } const columns = beans.colModel.getCols(); const aggregatableColumns = columns.filter((col) => col.isAllowValue() && aggFuncSvc.getFuncNames(col).length > 0); if (aggregatableColumns.length === 0) { return; } return s.object( { aggregationModel: s.array( s.union( aggregatableColumns.map( (col) => s.object({ colId: s.literal(col.getColId(), "Column identifier"), aggFunc: s.enum(beans.aggFuncSvc?.getFuncNames(col) || [], "Aggregation function") }) ) ), "Array of column aggregations" ) }, "Aggregation configuration for the grid" ).nullable(); }; // packages/ag-grid-enterprise/src/aiToolkit/features/columnSizingFeatureSchema.ts var buildColumnSizingFeatureSchema = (beans) => { const columns = beans.colModel.getCols(); const resizableColumns = columns.filter((col) => col.isResizable()); if (resizableColumns.length === 0) { return; } const resizableColumnIds = resizableColumns.map((col) => col.getColId()); return s.object( { columnSizingModel: s.array( s.union([ s.object({ colId: s.ref("resizableColumnId"), width: s.number("Fixed width in pixels").minimum(20) }), s.object({ colId: s.ref("resizableColumnId"), flex: s.number("Flex sizing ratio").minimum(0) }) ]), "Array of column sizing configurations" ) }, "Column sizing configuration for the grid" ).define("resizableColumnId", s.enum(resizableColumnIds, "Column ID that supports resizing")); }; // packages/ag-grid-enterprise/src/aiToolkit/features/columnVisibilityFeatureSchema.ts var buildColumnVisibilityFeatureSchema = () => { return s.object( { hiddenColIds: s.array(s.ref("allColumnIds"), "Array of column IDs to hide") }, "Column visibility configuration for the grid" ).nullable(); }; // packages/ag-grid-enterprise/src/aiToolkit/features/advancedFilterFeatureSchema.ts var buildAdvancedFilterFeatureSchema = ({ colModel, dataTypeSvc }) => { if (!dataTypeSvc) { return; } const columns = colModel.getCols(); const dataTypes = { boolean: [], object: [], date: [], dateString: [], dateTime: [], dateTimeString: [], number: [], bigint: [], text: [] }; for (const col of columns) { const dataType = dataTypeSvc.getBaseDataType(col); if (dataType) { dataTypes[dataType].push(col.colId); } } const columnFilterModels = []; const defs = {}; for (const key of Object.keys(dataTypes)) { if (dataTypes[key].length > 0) { const ref = `${key}AdvancedFilterModel`; const builder = DataTypeSchemaBuilders[key]; defs[ref] = builder(dataTypes[key]); columnFilterModels.push({ $ref: `#/$defs/${ref}` }); } } defs.joinAdvancedFilterModel = s.object({ filterType: s.literal("join", "Filter type identifier for joining multiple advanced filter conditions"), type: s.enum(["AND", "OR"], "Logical operator to combine multiple advanced filter conditions"), conditions: s.array(s.ref("advancedFilterModel"), "Array of advanced filter conditions to be combined") }); defs.advancedFilterModel = { anyOf: [...columnFilterModels, { $ref: "#/$defs/joinAdvancedFilterModel" }] }; return s.object( { advancedFilterModel: s.ref("advancedFilterModel") }, "Advanced filter configuration for the grid" ).nullable(); }; var buildBooleanFilterSchema = (colIds) => { return s.object({ filterType: s.literal("boolean", "Filter type identifier for boolean column filters"), colId: s.enum(colIds, "Column identifier for the boolean column to filter"), type: s.enum(["true", "false"], "Boolean value to filter by") }); }; var buildObjectFilterSchema = (colIds) => { return s.object({ filterType: s.literal("object", "Filter type identifier for object column filters"), colId: s.enum(colIds, "Column identifier for the object column to filter"), filter: s.string("Filter value to compare against object column values").nullable(), type: s.enum( ["equals", "notEqual", "contains", "notContains", "startsWith", "endsWith", "blank", "notBlank"], "Object filter operation type" ) }); }; var buildDateFilterSchema = (colIds) => { return s.object({ filterType: s.literal("date", "Filter type identifier for date column filters"), colId: s.enum(colIds, "Column identifier for the date column to filter"), filter: s.string({ pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "Date value in YYYY-MM-DD format" }).nullable(), type: s.enum( [ "equals", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "blank", "notBlank" ], "Date filter operation type" ) }); }; var buildDateStringFilterSchema = (colIds) => { return s.object({ filterType: s.literal("date", "Filter type identifier for date string column filters"), colId: s.enum(colIds, "Column identifier for the date string column to filter"), filter: s.string({ pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "Date value in YYYY-MM-DD format" }).nullable(), type: s.enum( [ "equals", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "blank", "notBlank" ], "Date string filter operation type" ) }); }; var buildDateTimeFilterSchema = (colIds) => { return s.object({ filterType: s.literal("dateTime", "Filter type identifier for datetime column filters"), colId: s.enum(colIds, "Column identifier for the datetime column to filter"), filter: s.string({ pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}$", description: "DateTime value in YYYY-MM-DDTHH:mm:ss format" }).nullable(), type: s.enum( [ "equals", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "blank", "notBlank" ], "DateTime filter operation type" ) }); }; var buildDateTimeStringFilterSchema = (colIds) => { return s.object({ filterType: s.literal("dateTimeString", "Filter type identifier for datetime string column filters"), colId: s.enum(colIds, "Column identifier for the datetime string column to filter"), filter: s.string({ pattern: "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$", description: "DateTime value in YYYY-MM-DD HH:mm:ss format" }).nullable(), type: s.enum( [ "equals", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "blank", "notBlank" ], "DateTime string filter operation type" ) }); }; var buildNumberFilterSchema = (colIds) => { return s.object({ filterType: s.literal("number", "Filter type identifier for number column filters"), colId: s.enum(colIds, "Column identifier for the number column to filter"), filter: s.number("Numeric value to filter by").nullable(), type: s.enum( [ "equals", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "blank", "notBlank" ], "Number filter operation type" ) }); }; var buildBigIntFilterSchema = (colIds) => { return s.object({ filterType: s.literal("bigint", "Filter type identifier for bigint column filters"), colId: s.enum(colIds, "Column identifier for the bigint column to filter"), filter: s.string({ pattern: "^-?\\d+$", description: "BigInt value to filter by" }).nullable(), type: s.enum( [ "equals", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "blank", "notBlank" ], "BigInt filter operation type" ) }); }; var buildTextFilterSchema = (colIds) => { return s.object({ filterType: s.literal("text", "Filter type identifier for text column filters"), colId: s.enum(colIds, "Column identifier for the text column to filter"), filter: s.string("Text value to filter by").nullable(), type: s.enum( ["equals", "notEqual", "contains", "notContains", "startsWith", "endsWith", "blank", "notBlank"], "Text filter operation type" ) }); }; var DataTypeSchemaBuilders = { boolean: buildBooleanFilterSchema, object: buildObjectFilterSchema, date: buildDateFilterSchema, dateString: buildDateStringFilterSchema, dateTime: buildDateTimeFilterSchema, dateTimeString: buildDateTimeStringFilterSchema, number: buildNumberFilterSchema, bigint: buildBigIntFilterSchema, text: buildTextFilterSchema }; // packages/ag-grid-enterprise/src/aiToolkit/features/filterFeatureSchema.ts var TextFilterKey = "agTextColumnFilter"; var NumberFilterKey = "agNumberColumnFilter"; var DateFilterKey = "agDateColumnFilter"; var SetFilterKey = "agSetColumnFilter"; var MultiFilterKey = "agMultiColumnFilter"; var SimpleFilterKeys = [TextFilterKey, NumberFilterKey, DateFilterKey]; var buildFilterFeatureSchema = (beans, params) => { const { advancedFilter } = beans; if (advancedFilter?.isEnabled()) { return buildAdvancedFilterFeatureSchema(beans); } else { return buildColumnFilterFeatureSchema(beans, params); } }; var buildColumnFilterFeatureSchema = (beans, params) => { const { gos, colFilter, colModel } = beans; if (!colFilter) { return; } const columns = colModel.getCols(); const filterableColumns = columns.filter((col) => col.isFilterAllowed()); if (filterableColumns.length === 0) { return; } const filterSchemas = {}; const enableFilterHandlers = gos.get("enableFilterHandlers"); for (const column of filterableColumns) { const columnParams = params?.columns ? params.columns[column.getColId()] : void 0; const colDef = column.getColDef(); const defaultFilter = colFilter.getDefaultFilter(column); const includeSetValues = columnParams?.includeSetValues ?? false; const filter = buildColumnFilterSchema( colDef.filter, colDef.filterParams, defaultFilter, (isMulti = false, multiIndex = 0) => { if (!includeSetValues) { return []; } let handler = void 0; if (!isMulti) { handler = colFilter.getHandler(column, true); } else if (enableFilterHandlers) { const multiHandler = colFilter.getHandler(column, true); handler = multiHandler.getHandler(multiIndex); } if (!handler) { return []; } return handler.getFilterKeys(); } ); if (filter) { filterSchemas[column.colId] = filter.nullable(); } } return s.object({ filterModel: s.object(filterSchemas) }).nullable(); }; function buildColumnFilterSchema(filter, filterParams, defaultFilter, getKeys) { let filterKey = void 0; if (typeof filter === "string") { filterKey = filter; } else if (typeof filter === "object" && typeof filter.component === "string") { filterKey = filter.component; } else if (filter === true || typeof filter === "object" && filter.component === true) { filterKey = defaultFilter; } if (!filterKey) { return null; } if (SimpleFilterKeys.includes(filterKey)) { const maxConditions = filterParams?.maxNumConditions; const filterOptions = filterParams?.filterOptions ? filterParams.filterOptions.map((option) => { if (typeof option === "string") { return option; } if (typeof option === "object" && option.displayKey) { return option.displayKey; } return null; }).filter(Boolean) : void 0; const useIsoSeparator = filterParams?.useIsoSeparator || false; return buildSimpleFilterSchema(filterKey, { maxConditions, filterOptions, useIsoSeparator }); } else if (filterKey === SetFilterKey) { return buildSetFilterSchema(getKeys); } else if (filterKey === MultiFilterKey) { return buildMultiFilterSchema(filterParams.filters, defaultFilter, getKeys); } return null; } var buildSimpleFilterSchema = (filterKey, params) => { if (filterKey === DateFilterKey) { return buildDateFilterSchema2(params); } else if (filterKey === NumberFilterKey) { return buildNumberFilterSchema2(params); } else { return buildTextFilterSchema2(params); } }; var buildJoinSchema = (schema, filterType, maxConditions = 2) => { if (maxConditions === 1) { return schema; } return s.object({ filterType: s.literal(filterType, `Filter type identifier for ${filterType} filters with multiple conditions`), operator: s.enum( ["AND", "OR"], "Logical operator to combine multiple filter conditions. Must be included even with a single filter to adhere to the API." ), conditions: s.array(schema, "Array of filter conditions to be combined").minItems(2).maxItems(maxConditions) }); }; var buildTextFilterSchema2 = (params) => { const options = params.filterOptions ?? [ "contains", "notContains", "equals", "notEqual", "startsWith", "endsWith", "blank", "notBlank" ]; const schema = s.object({ filterType: s.literal("text", "Filter type identifier for text filters"), type: s.enum(options, "Text filter operation type"), filter: s.string("Primary filter value").nullable(), filterTo: s.string("Secondary filter value for range operations").nullable() }); return buildJoinSchema(schema, "text", params.maxConditions); }; var buildNumberFilterSchema2 = (params) => { const options = params.filterOptions ?? [ "equals", "notEqual", "greaterThan", "greaterThanOrEqual", "lessThan", "lessThanOrEqual", "inRange", "blank", "notBlank" ]; const schema = s.object({ filterType: s.literal("number", "Filter type identifier for number filters"), type: s.enum(options, "Number filter operation type"), filter: s.number("Primary filter value").nullable(), filterTo: s.number("Secondary filter value for range operations").nullable() }); return buildJoinSchema(schema, "number", params.maxConditions); }; var buildDateFilterSchema2 = (params) => { const options = params.filterOptions ?? [ "equals", "notEqual", "lessThan", "greaterThan", "inRange", "blank", "notBlank" ]; const pattern = params.useIsoSeparator ? "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}$" : "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$"; const schema = s.object({ filterType: s.literal("date", "Filter type identifier for date filters"), type: s.enum(options, "Date filter operation type"), dateFrom: s.string({ pattern, description: "Primary date filter value in YYYY-MM-DD HH:mm:ss format" }).nullable(), dateTo: s.string({ pattern, description: "Secondary date filter value for range operations in YYYY-MM-DD HH:mm:ss format" }).nullable() }); return buildJoinSchema(schema, "date", params.maxConditions); }; var buildSetFilterSchema = (getKeys) => { const values = getKeys ? getKeys().filter(Boolean) : []; return s.object({ filterType: s.literal("set", "Filter type identifier for set filters"), values: s.array( values.length > 0 ? s.enum(values, "Available values to filter by") : s.string("Filter values"), "Array of values to include in the filter" ) }); }; var buildMultiFilterSchema = (filters, defaultFilter, getKeys = () => []) => { return s.object({ filterType: s.literal("multi", "Filter type identifier for multi-condition filters"), filterModels: s.array( s.union( filters.map( (filter, index) => buildColumnFilterSchema( filter.filter, filter.filterParams, defaultFilter, () => getKeys(true, index) ) ), "Union of different filter types that can be combined" ).nullable(), "Array of filter conditions to be combined with AND/OR logic" ) }); }; // packages/ag-grid-enterprise/src/aiToolkit/features/pivotFeatureSchema.ts var buildPivotFeatureSchema = (beans) => { const columns = beans.colModel.getCols(); const pivotableColumnIds = columns.filter((col) => col.isAllowPivot()).map((col) => col.getColId()); if (pivotableColumnIds.length === 0) { return; } return s.object( { pivotMode: s.boolean("Whether pivot mode is enabled"), pivotColIds: s.array( s.enum(pivotableColumnIds, "Column ID that supports pivoting"), "Array of column IDs to use as pivot columns" ) }, "Pivot configuration for the grid" ).nullable(); }; // packages/ag-grid-enterprise/src/aiToolkit/features/rowGroupFeatureSchema.ts var buildRowGroupFeatureSchema = (beans) => { const columns = beans.colModel.getCols(); const groupableColumns = columns.filter((col) => col.isAllowRowGroup()); if (groupableColumns.length === 0) { return; } const groupableColumnIds = groupableColumns.map((col) => col.getColId()); return s.object( { groupColIds: s.array( s.enum(groupableColumnIds, "Column ID that supports row grouping"), "Array of column IDs to group by" ) }, "Row grouping configuration for the grid" ); }; // packages/ag-grid-enterprise/src/aiToolkit/features/sortFeatureSchema.ts var buildSortFeatureSchema = (beans) => { const { sortSvc } = beans; if (!sortSvc) { return; } const columns = beans.colModel.getCols(); const sortableColumns = columns.filter((col) => col.isSortable()); if (sortableColumns.length === 0) { return; } const sortableColumnIds = sortableColumns.map((col) => col.getColId()); return s.object( { sortModel: s.array( s.object({ colId: s.enum(sortableColumnIds, "Column ID that supports sorting"), sort: s.enum(["asc", "desc"], "Sort direction: ascending or descending"), type: s.enum(["default", "absolute"], "Sort type: default or absolute values") }), "Array of sort configurations" ) }, "Sort configuration for the grid" ).nullable(); }; // packages/ag-grid-enterprise/src/aiToolkit/structuredSchema.ts var StructuredSchemaBuilderMap = { aggregation: buildAggregationFeatureSchema, filter: buildFilterFeatureSchema, sort: buildSortFeatureSchema, pivot: buildPivotFeatureSchema, columnVisibility: buildColumnVisibilityFeatureSchema, columnSizing: buildColumnSizingFeatureSchema, rowGroup: buildRowGroupFeatureSchema }; function getStructuredSchema(beans, params) { const allColumnIds = beans.colModel.getCols().map((col) => col.getColId()); const features = {}; for (const feature of STRUCTURED_SCHEMA_FEATURES) { if (params?.exclude?.includes(feature)) { continue; } const builder = StructuredSchemaBuilderMap[feature]; const schema2 = builder(beans, params); if (schema2) { features[feature] = schema2.nullable(); } } const columnParams = params?.columns ?? {}; const descriptions = allColumnIds.map((colId) => { if (columnParams[colId]?.description) { return `${colId}: ${columnParams[colId].description}`; } else { return colId; } }).filter(Boolean).join("\n"); const schema = s.object(features).define("allColumnIds", s.enum(allColumnIds, descriptions)); return schema.toJSON(); } // packages/ag-grid-enterprise/src/aiToolkit/aiToolkitModule.ts var AiToolkitModule = { moduleName: "AiToolkit", version: VERSION, beans: [], dependsOn: [EnterpriseCoreModule, ColumnApiModule], apiFunctions: { getStructuredSchema } }; // packages/ag-grid-enterprise/src/columnToolPanel/columnsToolPanelModule.ts import { _ColumnMoveModule, _PopupModule as _PopupModule2, _SharedDragAndDropModule as _SharedDragAndDropModule2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/sideBar/sideBarModule.ts import { _HorizontalResizeModule } from "ag-grid-community"; // packages/ag-grid-enterprise/src/sideBar/sideBarApi.ts import { _unwrapUserComp } from "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, parent) { beans.sideBar?.comp.openToolPanel(key, "api", parent); } 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 _unwrapUserComp(comp); } function getSideBar(beans) { return beans.sideBar?.comp.getDef(); } // packages/ag-grid-enterprise/src/sideBar/sideBarService.ts import { BeanStub as BeanStub7 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/sideBar/agSideBar.ts import { Component as Component18, KeyCode as KeyCode18, ManagedFocusFeature, RefPlaceholder as RefPlaceholder19, _addFocusableContainerListener, _addGridCommonParams as _addGridCommonParams5, _findNextFocusableElement as _findNextFocusableElement5, _focusInto as _focusInto4, _focusNextGridCoreContainer as _focusNextGridCoreContainer3, _getActiveDomElement as _getActiveDomElement7, _isVisible as _isVisible5, _removeFromParent as _removeFromParent5, _setAriaControlsAndLabel as _setAriaControlsAndLabel2, _warn as _warn6 } from "ag-grid-community"; // 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-tool-panel-external{display:flex;flex-direction:row}:where(.ag-tool-panel-external) .ag-tool-panel-wrapper{flex-grow:1}.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}.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}.ag-side-button: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)}:where(.ag-ltr) .ag-side-button:before{left:0}:where(.ag-rtl) .ag-side-button:before{right:0}.ag-side-button:hover{background-color:var(--ag-side-button-hover-background-color);color:var(--ag-side-button-hover-text-color)}.ag-side-button.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)}.ag-side-button.ag-selected:before{background-color:var(--ag-side-button-selected-underline-color)}.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 import { Component as Component15, KeyCode as KeyCode17, _clearElement as _clearElement7, _focusNextGridCoreContainer as _focusNextGridCoreContainer2, _stopPropagationForAgGrid as _stopPropagationForAgGrid7 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/sideBar/sideBarButtonComp.ts import { Component as Component14, RefPlaceholder as RefPlaceholder18, _createIconNoSpan as _createIconNoSpan5, _setAriaExpanded as _setAriaExpanded5 } from "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 Component14 { constructor(toolPanelDef) { super(); this.toolPanelDef = toolPanelDef; this.eToggleButton = RefPlaceholder18; this.eIconWrapper = RefPlaceholder18; this.eLabel = RefPlaceholder18; } 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", _createIconNoSpan5(this.toolPanelDef.iconKey, this.beans) ); } onButtonPressed() { this.dispatchLocalEvent({ type: "toggleButtonClicked" }); } setSelected(selected) { this.toggleCss("ag-selected", selected); _setAriaExpanded5(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 Component15 { constructor() { super(SideBarElement); this.buttonComps = []; } postConstruct() { this.addManagedElementListeners(this.getFocusableElement(), { keydown: this.handleKeyDown.bind(this) }); } handleKeyDown(e) { if (e.key !== KeyCode17.TAB || !e.shiftKey) { return; } if (_focusNextGridCoreContainer2(this.beans, true)) { e.preventDefault(); return; } _stopPropagationForAgGrid7(e); } setActiveButton(id) { for (const comp of this.buttonComps) { 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); _clearElement7(this.getGui()); } destroy() { this.clearButtons(); super.destroy(); } }; var AgSideBarButtonsSelector = { selector: "AG-SIDE-BAR-BUTTONS", component: AgSideBarButtons }; // packages/ag-grid-enterprise/src/sideBar/sideBarDefParser.ts import { _warn as _warn5 } from "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 = []; for (const key of toParse) { const lookupResult = DEFAULT_BY_KEY[key]; if (!lookupResult) { _warn5(215, { key, defaultByKey: DEFAULT_BY_KEY }); continue; } comps.push(lookupResult); } if (comps.length === 0) { return void 0; } return { toolPanels: comps, defaultToolPanel: comps[0].id }; } return { toolPanels: parseComponents(toParse.toolPanels), defaultToolPanel: toParse.defaultToolPanel, hiddenByDefault: toParse.hiddenByDefault, position: toParse.position, hideButtons: toParse.hideButtons }; } function parseComponents(from) { const result = []; if (!from) { return result; } from.forEach((it) => { const parsed = parseOneComponent(it); if (!parsed) { return; } result.push(parsed); }); return result; } function parseOneComponent(it) { if (typeof it !== "string") { return it; } if (DEFAULT_BY_KEY[it]) { return DEFAULT_BY_KEY[it]; } _warn5(215, { key: it, defaultByKey: DEFAULT_BY_KEY }); return null; } // packages/ag-grid-enterprise/src/sideBar/toolPanelWrapper.ts import { Component as Component17 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/sideBar/agHorizontalResize.ts import { Component as Component16 } from "ag-grid-community"; var AgHorizontalResize = class extends Component16 { 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 Component17 { 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 Component18 { constructor() { super(AgSideBarElement, [AgSideBarButtonsSelector]); this.sideBarButtons = RefPlaceholder19; 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 ManagedFocusFeature(eGui, { onTabKeyDown: this.onTabKeyDown.bind(this), handleKeyDown: this.handleKeyDown.bind(this) }) ); _addFocusableContainerListener(beans, this, eGui); this.addManagedPropertyListener("enableAdvancedFilter", this.onAdvancedFilterChanged.bind(this)); } onTabKeyDown(e) { if (e.defaultPrevented) { return; } const { beans, sideBarButtons } = this; const eGui = this.getGui(); const sideBarGui = sideBarButtons.getGui(); const activeElement = _getActiveDomElement7(beans); const openPanel = eGui.querySelector(".ag-tool-panel-wrapper:not(.ag-hidden)"); const target = e.target; const backwards = e.shiftKey; if (!openPanel) { if (_focusNextGridCoreContainer3(beans, backwards)) { e.preventDefault(); return true; } return _focusNextGridCoreContainer3(beans, backwards, true); } if (sideBarGui.contains(activeElement)) { if (_focusInto4(openPanel, backwards)) { e.preventDefault(); } return; } if (!backwards) { return; } let nextEl = null; if (openPanel.contains(activeElement)) { nextEl = _findNextFocusableElement5(beans, openPanel, void 0, true); } else if (isTargetUnderManagedComponent(openPanel, target)) { nextEl = findFocusableElementBeforeTabGuard(openPanel, target); } if (!nextEl) { nextEl = sideBarGui.querySelector(".ag-selected button"); nextEl = _isVisible5(nextEl) ? nextEl : null; } if (nextEl && nextEl !== e.target) { e.preventDefault(); nextEl.focus(); } } handleKeyDown(e) { const currentButton = _getActiveDomElement7(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 KeyCode18.LEFT: case KeyCode18.UP: nextPos = Math.max(0, currentPos - 1); break; case KeyCode18.RIGHT: case KeyCode18.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) { this.sideBarButtons.setDisplayed(!sideBarDef.hideButtons); } if (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); for (const wrapper of this.toolPanelWrappers) { wrapper.setResizerSizerSide(resizerSide); } this.dispatchSideBarUpdated(); return this; } setDisplayed(displayed, options) { super.setDisplayed(displayed, options); this.dispatchSideBarUpdated(); } getState() { const toolPanels = {}; for (const wrapper of this.toolPanelWrappers) { 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) { _warn6(212); return false; } if (isFilterPanel(toolPanel)) { if (this.beans.filterManager?.isAdvFilterEnabled()) { _warn6(213); return false; } } return true; } createToolPanelAndSideButton(def, initialState, existingToolPanelWrapper) { if (!this.validateDef(def)) { this.destroyBean(existingToolPanelWrapper); return; } let wrapper; if (existingToolPanelWrapper) { wrapper = existingToolPanelWrapper; } else { wrapper = this.createBean(new ToolPanelWrapper()); const created = wrapper.setToolPanelDef( def, _addGridCommonParams5(this.gos, { initialState, onStateUpdated: () => this.dispatchSideBarUpdated() }) ); if (!created) { return; } } wrapper.setDisplayed(false); const wrapperGui = wrapper.getGui(); const parent = def.parent instanceof HTMLElement ? def.parent : this; if (parent === def.parent) { this.beans.environment.applyThemeClasses(parent, ["ag-external", "ag-tool-panel-external"]); wrapperGui.classList.add(this.gos.get("enableRtl") ? "ag-rtl" : "ag-ltr"); } parent.appendChild(wrapperGui); this.toolPanelWrappers.push(wrapper); const button = this.sideBarButtons.addButtonComp(def); _setAriaControlsAndLabel2(button.eToggleButton, wrapperGui); } refresh() { for (const wrapper of this.toolPanelWrappers) { wrapper.refresh(); } } renderToolPanelUnderParent(key, parent) { const selfDefOrStr = this.sideBar?.toolPanels?.find((tp) => (typeof tp === "string" ? tp : tp.id) === key); if (selfDefOrStr) { const panelDef = parseOneComponent(selfDefOrStr); if (panelDef) { const state = this.gos.get("initialState")?.sideBar?.toolPanels?.[panelDef.id]; panelDef.parent = parent; const wrapper = this.toolPanelWrappers.find((wrapper2) => wrapper2.getToolPanelId() === key); this.createToolPanelAndSideButton(panelDef, state, wrapper); } } } openToolPanel(key, source = "api", parent) { if (parent && key) { this.renderToolPanelUnderParent(key, parent); } const currentlyOpenedKey = this.openedItem(); if (currentlyOpenedKey === key) { return; } for (const wrapper of this.toolPanelWrappers) { 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) { _warn6(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; for (const wrapper of this.toolPanelWrappers) { 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 = _addGridCommonParams5(this.gos, { ...toolPanelDef.toolPanelParams ?? {}, initialState: sideBarState?.toolPanels?.[id], onStateUpdated: () => this.dispatchSideBarUpdated() }); const hasRefreshed = toolPanelWrapper.getToolPanelInstance()?.refresh(params); if (hasRefreshed !== true) { return; } this.toolPanelWrappers = this.toolPanelWrappers.filter((toolPanel) => toolPanel !== toolPanelWrapper); _removeFromParent5(toolPanelWrapper.getGui()); existingToolPanelWrappers[id] = toolPanelWrapper; }); } this.clearDownUi(); this.setSideBarDef({ sideBarDef, sideBarState, existingToolPanelWrappers }); } dispatchSideBarUpdated() { this.eventSvc.dispatchEvent({ type: "sideBarUpdated" }); } destroyToolPanelWrappers() { for (const wrapper of this.toolPanelWrappers) { _removeFromParent5(wrapper.getGui()); this.destroyBean(wrapper); } this.toolPanelWrappers.length = 0; } onAdvancedFilterChanged() { const needsRefresh = this.sideBar?.toolPanels?.some( (toolPanel) => isFilterPanel(typeof toolPanel === "string" ? toolPanel : toolPanel.toolPanel) ); if (needsRefresh) { this.setState(); } } destroy() { this.destroyToolPanelWrappers(); super.destroy(); } }; function isFilterPanel(toolPanel) { return toolPanel === "agFiltersToolPanel" || toolPanel === "agNewFiltersToolPanel"; } var AgSideBarSelector = { selector: "AG-SIDE-BAR", component: AgSideBar }; // packages/ag-grid-enterprise/src/sideBar/sideBarService.ts var SideBarService = class extends BeanStub7 { 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, _HorizontalResizeModule] }; // 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/menuItemRenderer.ts import { _warn as _warn7 } from "ag-grid-community"; var MenuItemRenderer = class extends AgMenuItemRenderer { constructor() { super({ warnNoIcon: () => _warn7(227) }); } }; // packages/ag-grid-enterprise/src/widgets/menuItemModule.ts var MenuItemModule = { moduleName: "MenuItem", version: VERSION, userComponents: { agMenuItem: MenuItemRenderer }, 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 import { Component as Component25, _addGridCommonParams as _addGridCommonParams7, _clearElement as _clearElement8, _last as _last4 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/columnToolPanel/agPrimaryCols.ts import { Component as Component24, PositionableFeature, RefPlaceholder as RefPlaceholder23 } from "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{flex:none;height:var(--ag-header-height);padding-left:var(--ag-widget-container-horizontal-padding);padding-right:var(--ag-widget-container-horizontal-padding)}.ag-column-select-column,.ag-column-select-column-group,.ag-column-select-header{align-items:center;display:flex;gap:var(--ag-widget-horizontal-spacing);position:relative}.ag-column-select-column,.ag-column-select-column-group{height:100%}: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-column-group:where(:not(:last-child)),.ag-column-select-column:where(:not(:last-child)){margin-bottom:var(--ag-widget-vertical-spacing)}.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-icon{opacity:.5}&.ag-icon-grip{opacity:.35}}.ag-column-select-column-readonly{&.ag-icon-grip,.ag-icon-grip{opacity:.35}}.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 import { AgCheckboxSelector as AgCheckboxSelector2, AgInputTextFieldSelector as AgInputTextFieldSelector5, Component as Component19, KeyCode as KeyCode19, RefPlaceholder as RefPlaceholder20, _createIconNoSpan as _createIconNoSpan6, _debounce as _debounce2, _setDisplayed as _setDisplayed11 } from "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 Component19 { constructor() { super(AgPrimaryColsHeaderElement, [AgCheckboxSelector2, AgInputTextFieldSelector5]); this.eExpand = RefPlaceholder20; this.eSelect = RefPlaceholder20; this.eFilterTextField = RefPlaceholder20; } postConstruct() { this.createExpandIcons(); this.addManagedListeners(this.eExpand, { click: this.onExpandClicked.bind(this), keydown: (e) => { if (e.key === KeyCode19.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 = _createIconNoSpan6("columnSelectOpen", beans)); this.eExpand.appendChild(this.eExpandUnchecked = _createIconNoSpan6("columnSelectClosed", beans)); this.eExpand.appendChild(this.eExpandIndeterminate = _createIconNoSpan6("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...")); _setDisplayed11(this.eFilterTextField.getGui(), showFilter); _setDisplayed11(this.eSelect.getGui(), showSelect); _setDisplayed11(this.eExpand, showExpand && groupsPresent); } onFilterTextChanged() { if (!this.onFilterTextChangedDebounced) { this.onFilterTextChangedDebounced = _debounce2( 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; _setDisplayed11(this.eExpandChecked, state === 0 /* EXPANDED */); _setDisplayed11(this.eExpandUnchecked, state === 1 /* COLLAPSED */); _setDisplayed11(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 import { Component as Component23, DragSourceType as DragSourceType5, _exists as _exists12, _setAriaLabel as _setAriaLabel11, _setAriaLevel as _setAriaLevel3, _warn as _warn11, isProvidedColumnGroup as isProvidedColumnGroup4 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/sideBar/common/toolPanelColDefService.ts import { AgProvidedColumnGroup, _warn as _warn8, isProvidedColumnGroup } from "ag-grid-community"; // packages/ag-grid-enterprise/src/sideBar/common/sideBarUtils.ts import { _last as _last3 } from "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 = _last3(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; } } for (const child of groupToMerge.children) { 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 AgProvidedColumnGroup(groupDef, groupId, false, depth); const children = []; for (const def of groupDef.children) { 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 = []; for (const colDef of colDefs) { const result = createDummyColGroup(colDef, 0); if (result) { mappedResults.push(result); } } if (invalidColIds.length > 0) { _warn8(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 (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 import { LocalEventService } from "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 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 import { isProvidedColumnGroup as isProvidedColumnGroup3 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/columnToolPanel/toolPanelColumnGroupComp.ts import { AgCheckboxSelector as AgCheckboxSelector3, Component as Component21, DragSourceType as DragSourceType3, KeyCode as KeyCode20, RefPlaceholder as RefPlaceholder21, TouchListener, _createIcon, _createIconNoSpan as _createIconNoSpan8, _getShouldDisplayTooltip, _getToolPanelClassesFromColDef, _setAriaDescribedBy as _setAriaDescribedBy2, _setAriaExpanded as _setAriaExpanded6, _setAriaLabel as _setAriaLabel9, _setDisplayed as _setDisplayed12 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/columnToolPanel/modelItemUtils.ts import { _applyColumnState } from "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) => { for (const item of items) { if (!item.passesFilter) { continue; } if (item.group) { recursiveFunc(item.children); } else { res.push(item.column); } } }; recursiveFunc(allItems); return res; } function setAllVisible(beans, columns, visible, eventType) { const colStateItems = []; for (const col of columns) { if (col.getColDef().lockVisible) { continue; } if (col.isVisible() != visible) { colStateItems.push({ colId: col.getId(), hide: !visible }); } } if (colStateItems.length > 0) { _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) { _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] }; } }); _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 import { Component as Component20, _createIconNoSpan as _createIconNoSpan7, _focusInto as _focusInto5, isColumn, isProvidedColumnGroup as isProvidedColumnGroup2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rowGrouping/rowGroupingUtils.ts function setRowNodeGroupValue(rowNode, colModel, colKey, newValue) { const column = colModel.getCol(colKey); let groupData = rowNode._groupData; if (!groupData) { groupData = {}; rowNode._groupData = groupData; } const columnId = column.getColId(); const oldValue = groupData[columnId]; if (oldValue === newValue) { return; } 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; } function getGroupingLocaleText(localeTextFunc, key, displayName) { const prefix = key === "groupBy" ? "Group by" : "Un-Group by"; const localStr = localeTextFunc(key, `${prefix} ${displayName}`, [displayName]); if (localStr.indexOf(displayName) >= 0) { return localStr; } else { return `${localStr} ${displayName}`; } } // packages/ag-grid-enterprise/src/widgets/menuItemComponent.ts import { AgPromise as AgPromise2, _STOP_PROPAGATION_CALLBACKS as _STOP_PROPAGATION_CALLBACKS3, _addGridCommonParams as _addGridCommonParams6, _warn as _warn9 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/misc/enterpriseDomUtils.ts import { _getRootNode as _getRootNode2, _isBrowserFirefox, _isBrowserSafari } from "ag-grid-community"; function _getTextSelectionRanges(beans) { const rootNode = _getRootNode2(beans); const selection = "getSelection" in rootNode ? rootNode.getSelection() : null; const ranges = []; for (let i = 0; i < (selection?.rangeCount ?? 0); i++) { const range = selection?.getRangeAt(i); if (range) { ranges.push(range); } } return { selection, ranges }; } function _preserveRangesWhile(beans, fn) { const enableCellTextSelection = beans.gos.get("enableCellTextSelection"); if (!enableCellTextSelection) { return fn(); } if (!_isBrowserFirefox() && !_isBrowserSafari()) { return fn(); } const { selection, ranges } = _getTextSelectionRanges(beans); fn(); selection?.removeAllRanges(); for (const range of ranges) { selection?.addRange(range); } } // packages/ag-grid-enterprise/src/widgets/menuItemComponent.ts var MenuItemComponentType = { name: "menuItem", optionalMethods: ["setActive", "select", "setExpanded", "configureDefaults"] }; var MENU_ITEM_CALLBACKS = { getMenuItemComp: (beans, def, params) => { const compDetails = beans.userCompFactory.getCompDetails( def, MenuItemComponentType, "agMenuItem", _addGridCommonParams6(beans.gos, params), true ); return compDetails?.newAgStackInstance() ?? AgPromise2.resolve(); }, getPostProcessPopupParams: ({ column, node }) => ({ column, rowNode: node }), preserveRangesWhile: _preserveRangesWhile, stopPropagationCallbacks: _STOP_PROPAGATION_CALLBACKS3, warnNoItem: (menuItemOrString) => { _warn9(228, { menuItemOrString }); } }; var MenuItemComponent = class extends AgMenuItemComponent { constructor() { super(MENU_ITEM_CALLBACKS); } }; // packages/ag-grid-enterprise/src/widgets/menuList.ts var MenuList = class extends AgMenuList { constructor(level, menuActionParams = { column: null, node: null, value: null }) { super(level, menuActionParams, MENU_ITEM_CALLBACKS); } }; // packages/ag-grid-enterprise/src/columnToolPanel/toolPanelContextMenu.ts var ToolPanelContextMenu = class extends Component20 { constructor(column, mouseEventOrTouch, parentEl) { super({ tag: "div", cls: "ag-menu" }); this.column = column; this.mouseEventOrTouch = mouseEventOrTouch; this.parentEl = parentEl; this.displayName = null; } postConstruct() { const { column, beans: { colNames } } = this; this.initializeProperties(column); let displayName; if (isColumn(column)) { displayName = colNames.getDisplayNameForColumn(column, "columnToolPanel"); } else { displayName = colNames.getDisplayNameForProvidedColumnGroup(null, column, "columnToolPanel"); } this.displayName = displayName; this.buildMenuItemMap(); if (this.isActive()) { const mouseEventOrTouch = this.mouseEventOrTouch; if ("preventDefault" in mouseEventOrTouch) { mouseEventOrTouch.preventDefault(); } const menuItemsMapped = this.getMappedMenuItems(); if (menuItemsMapped.length === 0) { return; } this.displayContextMenu(menuItemsMapped); } } initializeProperties(column) { let columns; if (isProvidedColumnGroup2(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" }); const rowGroupAllowed = (col) => col.isPrimary() && col.isAllowRowGroup() && !isRowGroupColLocked(col, beans); menuItemMap.set("rowGroup", { allowedFunction: rowGroupAllowed, activeFunction: (col) => col.isRowGroupActive(), activateLabel: () => getGroupingLocaleText(localeTextFunc, "groupBy", displayName), deactivateLabel: () => getGroupingLocaleText(localeTextFunc, "ungroupBy", displayName), activateFunction: () => rowGroupColsSvc?.setColumns( this.addColumnsToList(rowGroupColsSvc.columns, rowGroupAllowed), "toolPanelUi" ), deActivateFunction: () => rowGroupColsSvc?.setColumns( this.removeColumnsFromList(rowGroupColsSvc.columns, rowGroupAllowed), "toolPanelUi" ), addIcon: "menuAddRowGroup", removeIcon: "menuRemoveRowGroup" }); const valueAllowed = (col) => col.isPrimary() && col.isAllowValue(); menuItemMap.set("value", { allowedFunction: valueAllowed, 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, valueAllowed), "toolPanelUi"), deActivateFunction: () => valueColsSvc?.setColumns(this.removeColumnsFromList(valueColsSvc.columns, valueAllowed), "toolPanelUi"), addIcon: "valuePanel", removeIcon: "valuePanel" }); const pivotAllowed = (col) => isPivotMode2 && col.isPrimary() && col.isAllowPivot(); menuItemMap.set("pivot", { allowedFunction: pivotAllowed, 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, pivotAllowed), "toolPanelUi"), deActivateFunction: () => pivotColsSvc?.setColumns(this.removeColumnsFromList(pivotColsSvc.columns, pivotAllowed), "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()?.includes(col) ?? true; } addColumnsToList(columnList, predicate) { return [...columnList].concat(this.columns.filter((col) => predicate(col) && !columnList.includes(col))); } removeColumnsFromList(columnList, predicate) { return columnList.filter((col) => predicate(col) && !this.columns.includes(col)); } displayContextMenu(menuItemsMapped) { const eGui = this.getGui(); const menuList = this.createBean(new MenuList()); 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: () => _focusInto5(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.mouseEventOrTouch, 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: _createIconNoSpan7(val.addIcon, beans, null), action: () => val.activateFunction() }); } if (isActive && val.removeIcon && val.deactivateLabel) { ret.push({ name: val.deactivateLabel(displayName), icon: _createIconNoSpan7(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 Component21 { constructor(modelItem, allowDragging, eventType, focusWrapper) { super(); this.modelItem = modelItem; this.allowDragging = allowDragging; this.eventType = eventType; this.focusWrapper = focusWrapper; this.cbSelect = RefPlaceholder21; this.eLabel = RefPlaceholder21; this.eGroupOpenedIcon = RefPlaceholder21; this.eGroupClosedIcon = RefPlaceholder21; this.eColumnGroupIcons = RefPlaceholder21; this.processingColumnStateChange = false; const { columnGroup, depth, displayName } = modelItem; this.columnGroup = columnGroup; this.columnDepth = depth; this.displayName = displayName; } postConstruct() { this.setTemplate(ToolPanelColumnGroupElement, [AgCheckboxSelector3]); const { beans, cbSelect, eLabel, displayName, columnDepth, modelItem, focusWrapper, columnGroup } = this; const { registry, gos } = beans; const eDragHandle = _createIconNoSpan8("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.after(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.focusWrapper, getLocation: () => "columnToolPanelColumnGroup", shouldDisplayTooltip: _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) }); const touchListener = new TouchListener(this.getGui(), false); this.addManagedListeners(touchListener, { longTap: (e) => this.onContextMenu(e.touchStart) }); this.addDestroyFunc(touchListener.destroy.bind(touchListener)); 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 = _getToolPanelClassesFromColDef(columnGroup.getColGroupDef(), gos, null, columnGroup); for (const c of classes) { 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 KeyCode20.LEFT: e.preventDefault(); this.modelItem.expanded = false; break; case KeyCode20.RIGHT: e.preventDefault(); this.modelItem.expanded = true; break; case KeyCode20.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); for (const column of this.columnGroup.getLeafColumns()) { this.addManagedListeners(column, { visibleChanged: listener, columnValueChanged: listener, columnPivotChanged: listener, columnRowGroupChanged: listener }); } } setupDragging() { if (!this.allowDragging) { _setDisplayed12(this.eDragHandle, false); return; } const beans = this.beans; const { gos, eventSvc, dragAndDrop } = beans; let hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns"); const dragSource = { type: DragSourceType3.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 = {}; for (const col of columns) { 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(_createIcon("columnSelectClosed", beans, null)); eGroupOpenedIcon.appendChild(_createIcon("columnSelectOpen", beans, null)); const listener = this.onExpandOrContractClicked.bind(this); this.addManagedElementListeners(eGroupClosedIcon, { click: listener }); this.addManagedElementListeners(eGroupOpenedIcon, { click: listener }); const touchListener = new 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) => { for (const child of children) { if (child.passesFilter) { 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"); _setAriaLabel9(focusWrapper, `${displayName} ${columnLabel}`); cbSelect.setInputAriaLabel(`${visibilityLabel} (${state})`); _setAriaDescribedBy2(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; for (const column of visibleLeafColumns) { if (pivotMode || !column.getColDef().lockVisible) { 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; for (const col of this.columnGroup.getLeafColumns()) { 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; _setDisplayed12(this.eGroupClosedIcon, !folderOpen); _setDisplayed12(this.eGroupOpenedIcon, folderOpen); } refreshAriaExpanded() { _setAriaExpanded6(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 (isProvidedColumnGroup3(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 import { AgCheckboxSelector as AgCheckboxSelector4, Component as Component22, DragSourceType as DragSourceType4, KeyCode as KeyCode21, RefPlaceholder as RefPlaceholder22, TouchListener as TouchListener2, _createIconNoSpan as _createIconNoSpan9, _getShouldDisplayTooltip as _getShouldDisplayTooltip2, _getToolPanelClassesFromColDef as _getToolPanelClassesFromColDef2, _setAriaDescribedBy as _setAriaDescribedBy3, _setAriaLabel as _setAriaLabel10, _setDisplayed as _setDisplayed13, _warn as _warn10 } from "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 Component22 { constructor(modelItem, allowDragging, groupsExist, focusWrapper) { super(); this.modelItem = modelItem; this.allowDragging = allowDragging; this.groupsExist = groupsExist; this.focusWrapper = focusWrapper; this.eLabel = RefPlaceholder22; this.cbSelect = RefPlaceholder22; this.processingColumnStateChange = false; const { column, depth, displayName } = modelItem; this.column = column; this.columnDepth = depth; this.displayName = displayName; } postConstruct() { this.setTemplate(ToolPanelColumnElement, [AgCheckboxSelector4]); const { beans, cbSelect, displayName, eLabel, columnDepth: indent, groupsExist, column, gos, focusWrapper } = this; const eDragHandle = _createIconNoSpan9("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.after(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.focusWrapper, getLocation: () => "columnToolPanelColumn", shouldDisplayTooltip: _getShouldDisplayTooltip2(gos, () => eLabel), getAdditionalParams: () => ({ colDef: column.getColDef() }) }) ); 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) }); const touchListener = new TouchListener2(focusWrapper); this.addManagedListeners(touchListener, { longTap: (e) => this.onContextMenu(e.touchStart) }); this.addDestroyFunc(touchListener.destroy.bind(touchListener)); 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 = _getToolPanelClassesFromColDef2(column.getColDef(), gos, column, null); for (const c of classes) { 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 === KeyCode21.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"); _setAriaLabel10(focusWrapper, `${displayName} ${columnLabel}`); this.cbSelect.setInputAriaLabel(`${visibilityLabel} (${state})`); _setAriaDescribedBy3(focusWrapper, cbSelect.getInputElement().id); } setupDragging() { const eDragHandle = this.eDragHandle; if (!this.allowDragging) { _setDisplayed13(eDragHandle, false); return; } const beans = this.beans; const { gos, eventSvc, dragAndDrop } = beans; let hideColumnOnExit = !gos.get("suppressDragLeaveHidesColumns"); const dragSource = { type: DragSourceType4.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) { _warn10(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 Component23 { 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 = []; for (const f of this.destroyColumnItemFuncs) { 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) => { _setAriaLevel3(listItemElement, item.depth + 1); return this.createComponentFromItem(item, listItemElement); }); if (this.colModel.ready) { this.onColumnsChanged(); } if (isPreventMove) { return; } this.createItemDragFeature(); } createItemDragFeature() { const { gos, beans, virtualList } = this; this.createManagedBean( new VirtualListDragFeature(this, virtualList, { dragSourceType: DragSourceType5.ToolPanel, addListeners: (parent, listItemDragStart, listItemDragEnd) => { parent.addManagedEventListeners({ columnPanelItemDragStart: listItemDragStart, columnPanelItemDragEnd: listItemDragEnd }); }, 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() : null; if (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; for (const id of expandedGroupIds) { 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) => { for (const child of tree) { if (isProvidedColumnGroup4(child)) { createGroupItem(child, depth, parentList); } else { createColumnItem(child, depth, parentList); } } }; const createGroupItem = (columnGroup, depth, parentList) => { const columnGroupDef = columnGroup.getColGroupDef(); const skipThisGroup = 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()?.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; _setAriaLabel11(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) => { for (const item of items) { 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) { _warn11(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(); } if (checked) { checkedCount++; } else { uncheckedCount++; } }); if (checkedCount > 0 && uncheckedCount > 0) { return void 0; } return !(checkedCount === 0 || uncheckedCount > 0); } setFilterText(filterText) { this.filterText = _exists12(filterText) ? filterText.toLowerCase() : null; this.markFilteredColumns(); this.flattenAndFilterModel(); } markFilteredColumns() { const passesFilter = (item) => { if (!_exists12(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); for (const child of item.children) { const childPasses = recursivelyCheckFilter(child, groupPasses || parentPasses); if (childPasses) { atLeastOneChildPassed = childPasses; } } } const filterPasses = parentPasses || atLeastOneChildPassed ? true : passesFilter(item); item.passesFilter = filterPasses; return filterPasses; }; for (const item of this.allColsTree) { 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 Component24 { constructor() { super(AgPrimaryColsElement, [AgPrimaryColsHeaderSelector, AgPrimaryColsListSelector]); this.primaryColsHeaderPanel = RefPlaceholder23; this.primaryColsListPanel = RefPlaceholder23; 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 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(.ag-column-panel) .ag-column-drop-vertical: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 Component25 { 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 = _addGridCommonParams7(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() { for (const panel of [ this.primaryColsPanel, this.rowGroupDropZonePanel, this.valuesDropZonePanel, this.pivotDropZonePanel ]) { if (!panel) { continue; } 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")); for (const columnDrop of columnDrops) { columnDrop.classList.remove("ag-last-column-drop"); } const columnDropEls = eGui.querySelectorAll(".ag-column-drop:not(.ag-hidden)"); const lastVisible = _last4(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; for (const func of childDestroyFuncs) { func(); } childDestroyFuncs.length = 0; _clearElement8(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 import { BeanStub as BeanStub8 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/pivotDropZonePanel.ts import { _createIconNoSpan as _createIconNoSpan12 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/baseDropZonePanel.ts import { DragSourceType as DragSourceType7, _shouldUpdateColVisibilityAfterGroup } from "ag-grid-community"; // packages/ag-grid-enterprise/src/widgets/pillDropZonePanel.ts import { Component as Component26, KeyCode as KeyCode22, ManagedFocusFeature as ManagedFocusFeature2, PositionableFeature as PositionableFeature2, _areEqual, _clearElement as _clearElement9, _createElement as _createElement7, _createIconNoSpan as _createIconNoSpan10, _findFocusableElements as _findFocusableElements3, _findNextFocusableElement as _findNextFocusableElement6, _getActiveDomElement as _getActiveDomElement8, _isKeyboardMode as _isKeyboardMode2, _last as _last5, _setAriaHidden, _setAriaLabel as _setAriaLabel12, _setAriaPosInSet as _setAriaPosInSet3, _setAriaRole as _setAriaRole7, _setAriaSetSize as _setAriaSetSize3 } from "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}:where(.ag-column-drop-empty) .ag-column-drop-vertical-list{overflow:hidden}.ag-column-drop-cell-button{cursor:pointer;min-width:0;opacity:.75}:where(.ag-ltr) .ag-column-drop-cell-button{margin-right:calc(var(--ag-spacing)/4)}:where(.ag-rtl) .ag-column-drop-cell-button{margin-left:calc(var(--ag-spacing)/4)}.ag-column-drop-cell-button:hover{opacity:1}:where(.ag-ltr) .ag-column-drop-cell-drag-handle{margin-left:calc(var(--ag-spacing)/4)}:where(.ag-rtl) .ag-column-drop-cell-drag-handle{margin-right:calc(var(--ag-spacing)/4)}.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}: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)}.ag-select-agg-func-virtual-list-item:hover{background-color:var(--ag-selected-row-background-color)}: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 Component26 { constructor(horizontal) { super(PillDropZonePanelElement); this.horizontal = horizontal; this.state = "notDragging"; this.guiDestroyFunctions = []; this.childPillComponents = []; this.resizeEnabled = false; this.addElementClasses(this.getGui()); this.ePillDropList = _createElement7({ 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() { for (const func of this.guiDestroyFunctions) { func(); } this.guiDestroyFunctions.length = 0; this.childPillComponents.length = 0; _clearElement9(this.getGui()); _clearElement9(this.ePillDropList); } init(params) { this.params = params ?? {}; this.createManagedBean( new ManagedFocusFeature2(this.getFocusableElement(), { onTabKeyDown: this.onTabKeyDown.bind(this), handleKeyDown: this.onKeyDown.bind(this) }) ); this.setupDropTarget(); this.positionableFeature = new PositionableFeature2(this.getGui()); this.createManagedBean(this.positionableFeature); this.refreshGui(); _setAriaLabel12(this.ePillDropList, this.getAriaLabel()); } onTabKeyDown(e) { const focusableElements = _findFocusableElements3(this.getFocusableElement(), null, true); const len = focusableElements.length; if (len === 0) { return; } const { shiftKey } = e; const activeEl = _getActiveDomElement8(this.beans); const isFirstFocused = activeEl === focusableElements[0]; const isLastFocused = activeEl === _last5(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 === KeyCode22.DOWN; let isPrevious = key === KeyCode22.UP; if (!isVertical) { const isRtl = this.gos.get("enableRtl"); isNext = !isRtl && key === KeyCode22.RIGHT || isRtl && key === KeyCode22.LEFT; isPrevious = !isRtl && key === KeyCode22.LEFT || isRtl && key === KeyCode22.RIGHT; } if (!isNext && !isPrevious) { return; } e.preventDefault(); if (e.shiftKey) { this.moveFocusedItem(isPrevious); } else { const el = _findNextFocusableElement6(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 (_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 = _isKeyboardMode2(); let alternateElement = null; if (isKeyboardMode) { alternateElement = _findNextFocusableElement6(this.beans, eGridDiv) ?? _findNextFocusableElement6(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 = _getActiveDomElement8(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; _setAriaRole7(ePillDropList, len === 0 ? "presentation" : "listbox"); for (let i = 0; i < len; i++) { const comp = childPillComponents[i]; const eGui = comp.getGui(); _setAriaPosInSet3(eGui, i + 1); _setAriaSetSize3(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 = _createElement7({ tag: "div" }); _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 = _createElement7({ 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 = _createElement7({ 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 = _createIconNoSpan10(enableRtl ? "panelDelimiterRtl" : "panelDelimiter", this.beans); this.addElementClasses(icon, "cell-separator"); eParent.appendChild(icon); } } }; // packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/dropZoneColumnComp.ts import { Component as Component28, DragSourceType as DragSourceType6, KeyCode as KeyCode24, RefPlaceholder as RefPlaceholder25, _createElement as _createElement8 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/widgets/pillDragComp.ts import { Component as Component27, KeyCode as KeyCode23, RefPlaceholder as RefPlaceholder24, TouchListener as TouchListener3, _createIconNoSpan as _createIconNoSpan11, _setAriaLabel as _setAriaLabel13, _setDisplayed as _setDisplayed14 } from "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 Component27 { constructor(dragSourceDropTarget, ghost, horizontal, template, agComponents) { super(); this.dragSourceDropTarget = dragSourceDropTarget; this.ghost = ghost; this.horizontal = horizontal; this.template = template; this.agComponents = agComponents; this.eText = RefPlaceholder24; this.eDragHandle = RefPlaceholder24; this.eButton = RefPlaceholder24; } 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(_createIconNoSpan11("columnDrag", beans)); eButton.appendChild(_createIconNoSpan11("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); _setAriaLabel13(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() { _setDisplayed14(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 TouchListener3(this.eButton); this.addManagedListeners(touchListener, { tap: () => this.dispatchLocalEvent(agEvent) }); this.addDestroyFunc(touchListener.destroy.bind(touchListener)); } onKeyDown(e) { const isDelete = e.key === KeyCode23.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 = RefPlaceholder25; 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 === KeyCode24.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 === KeyCode24.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 = _createElement8({ 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 === KeyCode24.ENTER || e.key === KeyCode24.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, additionalParams: { 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 DragSourceType6.ToolPanel; } destroy() { super.destroy(); this.column = null; } }; var AggItemComp = class extends Component28 { 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 === DragSourceType7.HeaderCell || type === DragSourceType7.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() && _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: _createIconNoSpan12("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 import { _createIconNoSpan as _createIconNoSpan13 } from "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: _createIconNoSpan13("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 import { _createIconNoSpan as _createIconNoSpan14 } from "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: _createIconNoSpan14("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 import { AgToggleButtonSelector, Component as Component29, RefPlaceholder as RefPlaceholder26 } from "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 Component29 { constructor() { super(...arguments); this.cbPivotMode = RefPlaceholder26; } postConstruct() { this.setTemplate(PivotModePanelElement, [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" }); for (const c of ctrlsSvc.getHeaderRowContainerCtrls()) { 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 BeanStub8 { 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, _ColumnMoveModule, _SharedDragAndDropModule2, _PopupModule2, MenuItemModule ] }; // packages/ag-grid-enterprise/src/menu/menuModule.ts import { _ColumnMoveModule as _ColumnMoveModule2, _PopupModule as _PopupModule3, _SharedDragAndDropModule as _SharedDragAndDropModule3, _SharedMenuModule } from "ag-grid-community"; // packages/ag-grid-enterprise/src/menu/chartMenuItemMapper.ts import { BeanStub as BeanStub9, _createIconNoSpan as _createIconNoSpan15, _warn as _warn12 } from "ag-grid-community"; var ChartMenuItemMapper = class extends BeanStub9 { 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?.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; for (const s2 of m?.subMenu ?? []) { removeKeys(s2); } return m; }; return removeKeys(menuItem); } buildLookup(menuItem) { const itemLookup = {}; const addItem = (item) => { itemLookup[item._key] = item; if (item.subMenu) { for (const s2 of item.subMenu) { addItem(s2); } } }; 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) { _warn12(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) { _warn12(174, { group, chartType }); return void 0; } return menuItemLookup[itemKey]; }).filter((s2) => s2 !== 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: _createIconNoSpan15("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: _createIconNoSpan15("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 import { BeanStub as BeanStub10, _addGridCommonParams as _addGridCommonParams8, _findNextFocusableElement as _findNextFocusableElement7 } from "ag-grid-community"; var ColumnChooserFactory = class extends BeanStub10 { 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, _addGridCommonParams8(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 Dialog({ title: translate("chooseColumns", "Choose Columns"), component: columnSelectPanel, width: 300, height: 300, resizable: true, movable: true, centered: true, closable: true, afterGuiAttached: () => { _findNextFocusableElement7(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 import { BeanStub as BeanStub12, _addGridCommonParams as _addGridCommonParams9, _getDisplaySortForColumn, _getGrandTotalRow, _isClientSideRowModel as _isClientSideRowModel2, _isLegacyMenuEnabled } from "ag-grid-community"; // packages/ag-grid-enterprise/src/menu/menuItemMapper.ts import { BeanStub as BeanStub11, _createIconNoSpan as _createIconNoSpan16, _exists as _exists13, _getRowNode, _normalizeSortType, _resetColumnState, _warn as _warn13 } from "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", sortAbsoluteAscending: "Sort", sortAbsoluteDescending: "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 SORT_MENU_ITEM_TO_MENU_ACTION_PARAMS = { sortAscending: { fallback: "Sort Ascending", getSortDef: () => ({ type: "default", direction: "asc" }) }, sortDescending: { fallback: "Sort Descending", getSortDef: () => ({ type: "default", direction: "desc" }) }, sortAbsoluteAscending: { fallback: "Sort Absolute Ascending", getSortDef: () => ({ type: "absolute", direction: "asc" }) }, sortAbsoluteDescending: { fallback: "Sort Absolute Descending", getSortDef: () => ({ type: "absolute", direction: "desc" }) }, sortUnSort: { fallback: "Clear Sort", getSortDef: (column) => ({ type: _normalizeSortType(column.getSortDef()?.type), direction: null }) } }; var MenuItemMapper = class extends BeanStub11 { 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: _createIconNoSpan16("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: _createIconNoSpan16("rowPin", beans, column2), subMenu } : null; } case "pinTop": return pinnedRowModel?.isManual() ? { name: localeTextFunc("pinTop", "Pin to Top"), icon: _createIconNoSpan16("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: _createIconNoSpan16("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: _createIconNoSpan16("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: _createIconNoSpan16("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: () => column2 && 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: getGroupingLocaleText( localeTextFunc, "groupBy", colNames.getDisplayNameForColumn(column2, "header") ), disabled: gos.get("functionsReadOnly") || column2?.isRowGroupActive() || !column2?.getColDef().enableRowGroup, action: () => rowGroupColsSvc.addColumns([column2], source2), icon: _createIconNoSpan16("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 = getGroupingLocaleText(localeTextFunc, "ungroupBy", ungroupByName); disabled = gos.get("functionsReadOnly") || isRowGroupColLocked(underlyingColumn, beans); action = () => { rowGroupColsSvc.removeColumns([showRowGroup], source2); }; } else { name = getGroupingLocaleText( localeTextFunc, "ungroupBy", 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: _createIconNoSpan16("menuRemoveRowGroup", beans, null) }; } else { return null; } } case "resetColumns": return { name: localeTextFunc("resetColumns", "Reset Columns"), action: () => _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: _createIconNoSpan16("clipboardCopy", beans, null), action: () => clipboardSvc.copyToClipboard() } : null; case "copyWithHeaders": return clipboardSvc ? { name: localeTextFunc("copyWithHeaders", "Copy with Headers"), // shortcut: localeTextFunc('ctrlC','Ctrl+C'), icon: _createIconNoSpan16("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: _createIconNoSpan16("clipboardCopy", beans, null), action: () => clipboardSvc.copyToClipboard({ includeHeaders: true, includeGroupHeaders: true }) } : null; case "cut": if (clipboardSvc) { const focusedCell = focusSvc.getFocusedCell(); const rowNode = focusedCell ? _getRowNode(beans, focusedCell) : null; const isEditable = rowNode ? focusedCell?.column.isCellEditable(rowNode) : false; return { name: localeTextFunc("cut", "Cut"), shortcut: localeTextFunc("ctrlX", "Ctrl+X"), icon: _createIconNoSpan16("clipboardCut", beans, null), disabled: !isEditable || gos.get("suppressCutToClipboard"), action: () => clipboardSvc.cutToClipboard(void 0, "contextMenu") }; } else { return null; } case "paste": if (clipboardSvc) { const isPasteBlocked = gos.get("suppressClipboardApi") || gos.get("suppressClipboardPaste") || !column2 || !node || !column2.isCellEditable(node) || column2.isSuppressPaste(node); return { name: localeTextFunc("paste", "Paste"), shortcut: localeTextFunc("ctrlV", "Ctrl+V"), icon: _createIconNoSpan16("clipboardPaste", beans, null), disabled: isPasteBlocked, action: () => clipboardSvc.pasteFromClipboard() }; } else { return 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: _createIconNoSpan16("save", beans, null) } : null; } case "csvExport": return csvCreator ? { name: localeTextFunc("csvExport", "CSV Export"), icon: _createIconNoSpan16("csvExport", beans, null), action: () => csvCreator.exportDataAsCsv() } : null; case "excelExport": return excelCreator ? { name: localeTextFunc("excelExport", "Excel Export"), icon: _createIconNoSpan16("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: _createIconNoSpan16("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: _createIconNoSpan16("columns", beans, null), action: () => colChooserFactory.showColumnChooser({ column: column2, eventSource: sourceElement2(), headerPosition }) } : null; } case "sortUnSort": case "sortAscending": case "sortDescending": case "sortAbsoluteAscending": case "sortAbsoluteDescending": { if (!sortSvc || !column2) { return null; } const { fallback, getSortDef } = SORT_MENU_ITEM_TO_MENU_ACTION_PARAMS[key]; return { name: localeTextFunc(key, fallback), icon: _createIconNoSpan16(key, beans, null), action: () => sortSvc.setSortForColumn(column2, getSortDef(column2), false, source2) }; } default: { _warn13(176, { key }); return null; } } }; for (const menuItemOrString of originalList) { let result; if (typeof menuItemOrString === "string") { result = getStockMenuItem(menuItemOrString, column, sourceElement, source); } else { result = { ...menuItemOrString }; } if (!result) { continue; } 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 = _exists13(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 }); for (const funcName of funcNames) { 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 BeanStub12 { constructor() { super(...arguments); this.beanName = "colMenuFactory"; } createMenu(parent, menuItems, column, sourceElement) { const menuList = parent.createManagedBean( new MenuList(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( _addGridCommonParams9(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 = _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 grandTotalRow = _getGrandTotalRow(gos); const treeData = gos.get("treeData"); const isPrimary = column.isPrimary(); const allowValueAgg = !isPrimary || aggFuncSvc && column.isAllowValue() && (doingGrouping || grandTotalRow || treeData); if (sortSvc && !isLegacyMenuEnabled && column.isSortable()) { const { isDefaultSortAllowed, isAbsoluteSortAllowed, isAbsoluteSort, isDefaultSort, isAscending, isDescending, direction } = _getDisplaySortForColumn(column, beans); if (isDefaultSortAllowed && !(isAscending && isDefaultSort)) { result.push("sortAscending"); } if (isDefaultSortAllowed && !(isDescending && isDefaultSort)) { result.push("sortDescending"); } if (isAbsoluteSortAllowed && !(isAscending && isAbsoluteSort)) { result.push("sortAbsoluteAscending"); } if (isAbsoluteSortAllowed && !(isDescending && isAbsoluteSort)) { result.push("sortAbsoluteDescending"); } if (direction) { 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) { if (!colDef.suppressAutoSize) { 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 && (_isClientSideRowModel2(gos) || gos.get("ssrmExpandAllAffectsAllRows")) && (treeData || rowGroupCount > (colModel.isPivotMode() ? 1 : 0))) { result.push("expandAll"); result.push("contractAll"); } return result; } }; // packages/ag-grid-enterprise/src/menu/contextMenu.ts import { BeanStub as BeanStub13, _addGridCommonParams as _addGridCommonParams10, _attemptToRestoreCellFocus, _exists as _exists14, _getGrandTotalRow as _getGrandTotalRow2, _isIOSUserAgent } from "ag-grid-community"; var CSS_CONTEXT_MENU_OPEN = "ag-context-menu-open"; var ContextMenuService = class extends BeanStub13 { constructor() { super(...arguments); this.beanName = "contextMenuSvc"; this.focusedCell = null; } postConstruct() { this.menu = this.createManagedBean( new AgContextMenuService({ menuItemCallbacks: MENU_ITEM_CALLBACKS, getMenuItems: this.getMenuItems.bind(this), mapMenuItems: this.mapWithStockItems.bind(this), beforeMenuOpen: this.beforeMenuOpen.bind(this), onMenuOpen: this.onMenuOpen.bind(this), onMenuClose: this.onMenuClose.bind(this), afterMenuDestroyed: this.afterMenuDestroyed.bind(this), onVisibleChanged: this.dispatchVisibleChangedEvent.bind(this), // overlay was displayed shouldBlockMenuOpen: () => !!this.beans.overlays?.exclusive }) ); } hideActiveMenu() { this.menu.hideActiveMenu(); } getMenuItems(menuActionParams, mouseEvent) { const { column, node, value } = menuActionParams; const defaultMenuOptions = []; const { clipboardSvc, chartSvc, csvCreator, excelCreator, colModel, rangeSvc, gos } = this.beans; if (_exists14(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 (_exists14(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 = _getGrandTotalRow2(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 = _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( _addGridCommonParams10(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, node: rowNode, from: "edit" }).value; } if (anchorToElement == null) { anchorToElement = this.getContextMenuAnchorElement(rowNode, column); } this.beans.menuUtils.onContextMenu({ mouseEvent: params.mouseEvent ?? null, touchEvent: params.touchEvent ?? null, showMenuCallback: (eventOrTouch) => this.menu.showMenu({ node: 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, "edit") : null; const gridBodyCon = ctrlsSvc.getGridBodyCtrl(); const anchorToElement = cellCtrl ? cellCtrl.eGui : gridBodyCon.eGridBody; this.showContextMenu({ mouseEvent, touchEvent, rowNode, column, value, anchorToElement, source: "ui" }); } beforeMenuOpen(menuActionParams) { if (!menuActionParams.column) { this.beans.focusSvc.clearFocusedCell(); } } onMenuOpen() { const { ctrlsSvc, focusSvc } = this.beans; ctrlsSvc.getGridBodyCtrl().eGridBody.classList.add(CSS_CONTEXT_MENU_OPEN); this.focusedCell = focusSvc.getFocusedCell(); } onMenuClose() { this.beans.ctrlsSvc.getGridBodyCtrl().eGridBody.classList.remove(CSS_CONTEXT_MENU_OPEN); } afterMenuDestroyed() { const { beans, focusedCell } = this; _attemptToRestoreCellFocus(beans, focusedCell); } dispatchVisibleChangedEvent(visible, source) { 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; } mapWithStockItems(menuItems, menuActionParams, getGui) { const { column, node } = menuActionParams; return this.beans.menuItemMapper.mapWithStockItems( menuItems, column, node, getGui, "contextMenu" ); } }; // packages/ag-grid-enterprise/src/menu/enterpriseMenu.ts import { AgPromise as AgPromise3, BeanStub as BeanStub14, Component as Component30, FilterComp, RefPlaceholder as RefPlaceholder27, _createElement as _createElement9, _createIconNoSpan as _createIconNoSpan17, _error, _focusInto as _focusInto6, _isColumnMenuAnchoringEnabled, _isLegacyMenuEnabled as _isLegacyMenuEnabled2, _setColMenuVisible, _warn as _warn14, isColumn as isColumn2 } from "ag-grid-community"; 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 BeanStub14 { 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, additionalParams: { 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 && isColumn2(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 = _isLegacyMenuEnabled2(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, additionalParams: { 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) { _setColMenuVisible(column, false, "contextMenu"); menuUtils.restoreFocusOnClose(restoreFocusParams, eComp, e); } onClosedCallback?.(); }); const translate = this.getLocaleTextFunc(); popupSvc.addPopup({ modal: true, eChild: eMenuGui, closeOnEsc: true, closedCallback: (e) => { for (const f of closedFuncs) { 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 (_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) { _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 (_isLegacyMenuEnabled2(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 ?? (_isLegacyMenuEnabled2(this.gos) ? TAB_GENERAL : "columnMenu"), column: column ?? null, columnGroup: columnGroup ?? null }); } isMenuEnabled(column) { if (!_isLegacyMenuEnabled2(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 BeanStub14 { 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 AgTabbedLayout({ 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) { _warn14(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: _createIconNoSpan17("legacyMenu", beans, column), titleLabel: TAB_GENERAL.replace("MenuTab", ""), bodyPromise: AgPromise3.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 FilterComp(this.column, "COLUMN_MENU")) : null; this.filterComp = comp; if (!comp?.hasFilter()) { _error(119); } const afterAttachedCallback = (params) => comp?.afterGuiAttached(params); const afterDetachedCallback = () => comp?.afterGuiDetached(); this.tabItemFilter = { title: _createIconNoSpan17("filterTab", this.beans, this.column), titleLabel: TAB_FILTER.replace("MenuTab", ""), bodyPromise: AgPromise3.resolve(comp?.getGui()), afterAttachedCallback, afterDetachedCallback, name: TAB_FILTER }; return this.tabItemFilter; } createColumnsPanel() { const eWrapperDiv = _createElement9({ 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: _createIconNoSpan17("columns", beans, column), //createColumnsIcon(), titleLabel: TAB_COLUMNS.replace("MenuTab", ""), bodyPromise: AgPromise3.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 Component30 { 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 = RefPlaceholder27; } 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()); } // eslint-disable-next-line sonarjs/no-identical-functions onHidePopup(event) { this.beans.menuUtils.closePopupAndRestoreFocusOnSelect( this.hidePopupFunc, this.restoreFocusParams, event ); } afterGuiAttached({ hidePopup }) { if (hidePopup) { this.hidePopupFunc = hidePopup; this.addDestroyFunc(hidePopup); } _focusInto6(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 import { BeanStub as BeanStub15, _findTabbableParent, _getActiveDomElement as _getActiveDomElement9, _isNothingFocused as _isNothingFocused2, _isVisible as _isVisible6, _last as _last6 } from "ag-grid-community"; var MenuUtils = class extends BeanStub15 { 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 = _getActiveDomElement9(this.beans); if ( // focus is outside of comp !eComp.contains(activeEl) && // something else has focus !_isNothingFocused2(this.beans) ) { return; } this.focusHeaderCell(restoreFocusParams); } closePopupAndRestoreFocusOnSelect(hidePopupFunc, restoreFocusParams, event) { let keyboardEvent; if (event?.keyboardEvent) { keyboardEvent = event.keyboardEvent; } hidePopupFunc(keyboardEvent && { keyboardEvent }); const beans = this.beans; const focusSvc = beans.focusSvc; const focusedCell = focusSvc.getFocusedCell(); if (_isNothingFocused2(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?.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 && _isVisible6(eventSource)) { const focusableEl = _findTabbableParent(eventSource); if (focusableEl) { headerNavigation?.scrollToColumn(column); focusableEl.focus(); } } else if (headerPosition && columnIndex !== -1) { const allColumns = visibleCols.allCols; const columnToFocus = allColumns[columnIndex] || _last6(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 is sorted absolute ascending sortAbsoluteAscending: "aasc", // show on column header when column is sorted absolute descending sortAbsoluteDescending: "adesc", // show on column header when column has no sort, only when enabled with colDef.unSortIcon=true sortUnSort: "none" }, dependsOn: [EnterpriseCoreModule, _PopupModule3, _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, _SharedDragAndDropModule3, _ColumnMoveModule2] }; 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 import { _EditCoreModule } from "ag-grid-community"; // packages/ag-grid-enterprise/src/richSelect/richSelectCellEditor.ts import { AgAbstractCellEditor, KeyCode as KeyCode25, _addGridCommonParams as _addGridCommonParams11, _missing, _warn as _warn15 } from "ag-grid-community"; var RichSelectCellEditor = class extends AgAbstractCellEditor { constructor() { super({ tag: "div", cls: "ag-cell-edit-wrapper" }); this.currentSearchRequest = 0; this.onSearchCallback = (searchString) => { const currentRequest = ++this.currentSearchRequest; const richSelect = this.eEditor; richSelect.setValueList({ refresh: true, valueList: void 0 }); const params = this.params; params.search = searchString; if (!params.search) { return; } if (typeof params.values !== "function") { if (this.isFullAsync()) { _warn15(294); } return; } const valuesPromise = params.values(params); if (Array.isArray(valuesPromise)) { if (this.isFullAsync()) { _warn15(294); } richSelect.setValueList({ refresh: true, valueList: valuesPromise }); return; } richSelect.setValueList({ valueList: valuesPromise.then((results) => { if (currentRequest === this.currentSearchRequest) { return results; } }), refresh: true }); }; } initialiseEditor(_params) { const { cellStartedEdit, values, eventKey } = this.params; if (_missing(values)) { _warn15(180); } const { params: richSelectParams, valueList } = this.buildRichSelectParams(); const richSelect = this.createManagedBean(new AgRichSelect(richSelectParams)); this.eEditor = richSelect; richSelect.addCss("ag-cell-editor"); this.appendChild(richSelect); if (this.isFullAsync()) { richSelect.showPicker(); } this.eEditor.setValueList({ valueList, refresh: true, isInitial: true }); const isOneTimeAsync = valueList && !Array.isArray(valueList); if (isOneTimeAsync) { valueList.then((values2) => { 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)); } } getPlaceholderText() { const { valuePlaceholder } = this.params; if (valuePlaceholder !== void 0) { return valuePlaceholder; } const i18n = this.getLocaleTextFunc(); return this.isFullAsync() ? i18n("typeToSearchOoo", "Type to search...") : i18n("advancedFilterBuilderSelectOption", "Select an option..."); } isFullAsync() { const { allowTyping, filterListAsync, values } = this.params; const isSyncOrAsyncOrFullAsync = typeof values === "function"; if (!isSyncOrAsyncOrFullAsync && filterListAsync) { _warn15(294); } return !!(allowTyping && filterListAsync && typeof values === "function"); } getInitialValueList() { const params = this.params; const { values } = params; const maybeItIsFullAsync = this.isFullAsync(); const isSync = Array.isArray(values) || !values; const isSyncOrAsyncOrFullAsync = typeof values === "function"; if (isSync) { return values ?? []; } if (!isSyncOrAsyncOrFullAsync) { return []; } if (maybeItIsFullAsync) { return; } return values({ ...params }); } buildRichSelectParams() { const params = this.params; const { cellRenderer, cellRendererParams, cellHeight, value, values, formatValue, searchDebounceDelay, valueListGap, valueListMaxHeight, valueListMaxWidth, allowTyping, filterList, searchType, highlightMatch, eventKey, multiSelect, suppressDeselectAll, suppressMultiSelectPillRenderer } = params; const ret = { value, cellRenderer, cellRendererParams, 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: this.getPlaceholderText(), initialInputValue: eventKey?.length === 1 ? eventKey : eventKey === KeyCode25.BACKSPACE ? "" : void 0, multiSelect, suppressDeselectAll, suppressMultiSelectPillRenderer }; const valueList = this.getInitialValueList(); const maybeItIsFullAsync = this.isFullAsync(); const isSync = Array.isArray(values); const isSyncOrAsyncOrFullAsync = typeof values === "function"; if (isSync) { ret.valueList = valueList; ret.searchStringCreator = this.getSearchStringCallback(valueList); } else if (isSyncOrAsyncOrFullAsync && maybeItIsFullAsync) { ret.onSearch = this.onSearchCallback; ret.allowNoResultsCopy = true; ret.filterList = true; } if (multiSelect && allowTyping) { params.allowTyping = false; ret.allowTyping = false; _warn15(181); } return { params: ret, valueList }; } 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) { _warn15(266); const { column, node, data } = params; return (values2) => values2.map((value) => { const keyParams = _addGridCommonParams11(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(); } this.processEventKey(eventKey); }); } processEventKey(eventKey) { if (!eventKey) { return; } if (eventKey === KeyCode25.BACKSPACE) { this.eEditor.searchTextFromString(null); } else 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", // loading async values richSelectLoading: "loading" }, dependsOn: [EnterpriseCoreModule, _EditCoreModule] }; // packages/ag-grid-enterprise/src/setFilter/setFilterModule.ts import { _ColumnFilterModule } from "ag-grid-community"; // packages/ag-grid-enterprise/src/setFilter/setFilter.ts import { AgInputTextFieldSelector as AgInputTextFieldSelector6, KeyCode as KeyCode26, ProvidedFilter, RefPlaceholder as RefPlaceholder29, _areEqual as _areEqual2, _createIconNoSpan as _createIconNoSpan18, _exists as _exists15, _getActiveDomElement as _getActiveDomElement10, _makeNull as _makeNull4, _setDisplayed as _setDisplayed16, _warn as _warn19 } from "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, getUseFormatterFromColumn) { this.valueSvc = valueSvc; this.getValueFormatter = getValueFormatter; this.formatter = formatter; this.column = column; this.getUseFormatterFromColumn = getUseFormatterFromColumn; /** 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, this.getUseFormatterFromColumn() ); 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 import { AgCheckboxSelector as AgCheckboxSelector5, Component as Component31, RefPlaceholder as RefPlaceholder28, _addGridCommonParams as _addGridCommonParams12, _createIcon as _createIcon2, _getCellRendererDetails, _getShouldDisplayTooltip as _getShouldDisplayTooltip3, _isShowTooltipWhenTruncated, _setAriaChecked as _setAriaChecked2, _setAriaDescribedBy as _setAriaDescribedBy4, _setAriaExpanded as _setAriaExpanded7, _setAriaLabel as _setAriaLabel14, _setAriaLabelledBy as _setAriaLabelledBy3, _setAriaLevel as _setAriaLevel4, _setDisplayed as _setDisplayed15, _toStringOrNull as _toStringOrNull3, _warn as _warn16 } from "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 Component31 { constructor(params) { super(params.isGroup ? SetFilterGroupElement : SetFilterElement, [AgCheckboxSelector5]); this.eCheckbox = RefPlaceholder28; this.eGroupOpenedIcon = RefPlaceholder28; this.eGroupClosedIcon = RefPlaceholder28; this.eGroupIndeterminateIcon = RefPlaceholder28; this.formattedValue = null; this.focusWrapper = params.focusWrapper; this.value = params.value; this.params = params.params; this.translate = params.translate; this.valueFormatter = params.valueFormatter; this.useFormatterFromColumn = params.shouldUseFormatterFromColumn; 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.focusWrapper, getLocation: () => "setFilterValue", shouldDisplayTooltip: () => this.shouldDisplayTooltip?.() ?? true, getAdditionalParams: () => { const { colDef, column } = this.params; const additionalParams = { colDef, column, valueFormatted: this.formattedValue ?? void 0 }; if (this.isTree) { additionalParams.level = this.depth; } return additionalParams; } }) ); 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"); } _setAriaLevel4(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(_createIcon2("setFilterGroupClosed", beans, null)); eGroupOpenedIcon.appendChild(_createIcon2("setFilterGroupOpen", beans, null)); const listener = this.onExpandOrContractClicked.bind(this); this.addManagedElementListeners(eGroupClosedIcon, { click: listener }); this.addManagedElementListeners(eGroupOpenedIcon, { click: listener }); if (hasIndeterminateExpandState) { eGroupIndeterminateIcon.appendChild(_createIcon2("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; _setDisplayed15(eGroupClosedIcon, hasIndeterminateExpandState ? isExpanded === false : !isExpanded); _setDisplayed15(eGroupOpenedIcon, isExpanded === true); if (hasIndeterminateExpandState) { _setDisplayed15(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"); _setAriaLabelledBy3(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(); _setAriaLabel14(ariaEl, `${value} ${itemLabel}`); _setAriaDescribedBy4(ariaEl, this.eCheckbox.getInputElement().id); } refreshAriaChecked() { const ariaEl = this.getAriaElement(); _setAriaChecked2(ariaEl, this.eCheckbox.getValue()); } refreshAriaExpanded() { _setAriaExpanded7(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 = _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 = _toStringOrNull3(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 && (!_isShowTooltipWhenTruncated(gos) || !this.params.cellRenderer)) { const newTooltipText = formattedValue != null ? formattedValue : _toStringOrNull3(value); this.shouldDisplayTooltip = _getShouldDisplayTooltip3( gos, () => this.eCheckbox.getGui().querySelector(".ag-label") ); this.tooltipFeature?.setTooltipAndRefresh(newTooltipText); } this.cellRendererParams = _addGridCommonParams12(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, !!this.useFormatterFromColumn); } renderCell() { const compDetails = _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") { _warn16(208); valueToRender = ""; } this.eCheckbox.setLabel(valueToRender); this.setupFixedAriaLabels(valueToRender); } getComponentHolder() { return this.params.column.getColDef(); } }; // packages/ag-grid-enterprise/src/setFilter/setFilterUtils.ts import { _defaultComparator, _last as _last7, _makeNull as _makeNull3, _toStringOrNull as _toStringOrNull4, _translate, _warn as _warn17 } from "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) => _toStringOrNull4(_makeNull3(treeKey))); if (!treeData && groupAllowUnbalanced && processedDataPath.some((treeKey) => treeKey == null)) { if (_last7(processedDataPath) == null) { return null; } return processedDataPath.filter((treeKey) => treeKey != null); } return processedDataPath; } function translateForSetFilter(bean, key, variableValues) { return _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; _warn17(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 = _defaultComparator(aValue[i], bValue[i]); if (diff !== 0) { return diff; } } return 0; }; } // packages/ag-grid-enterprise/src/setFilter/treeSetDisplayValueModel.ts import { _getDateParts, _warn as _warn18 } from "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) => _getDateParts(value, false); } _warn18(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); } }; for (const item of this.activeDisplayedItemsFlat) { 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 ProvidedFilter { constructor() { super("setFilter", "set-filter"); this.filterType = "set"; this.eMiniFilter = RefPlaceholder29; this.eFilterLoading = RefPlaceholder29; this.eFilterLoadingIcon = RefPlaceholder29; this.eSetFilterList = RefPlaceholder29; this.eFilterNoMatches = RefPlaceholder29; 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, () => this.handler.shouldUseValueFormatterFromColumn() ); handler.valueModel.allKeys.then((values) => { if (!this.isAlive()) { return; } 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(true); } updateHandler(handler) { const oldHandler = this.handler; if (oldHandler !== handler) { for (const func of this.handlerDestroyFuncs ?? []) { 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; } 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 [AgInputTextFieldSelector6]; } handleKeyDown(e) { super.handleKeyDown(e); if (e.defaultPrevented) { return; } const getComponentForKeyEvent = () => { if (!this.eSetFilterList.contains(_getActiveDomElement10(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 KeyCode26.SPACE: getComponentForKeyEvent()?.toggleSelected(); break; case KeyCode26.ENTER: this.handleKeyEnter(e); break; case KeyCode26.LEFT: getComponentForKeyEvent()?.setExpanded(false); break; case KeyCode26.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, true); 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 _areEqual2(a.values, b.values); } setIsLoading(isLoading) { _setDisplayed16(this.eFilterLoading, isLoading); if (!isLoading) { this.hardRefreshVirtualList = true; } } initialiseFilterBodyUi() { this.initVirtualList(); this.initMiniFilter(); this.initLoading(); } initLoading() { const loadingIcon = _createIconNoSpan18("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, shouldUseFormatterFromColumn: this.handler.shouldUseValueFormatterFromColumn(), 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?.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) { _warn19(283); this.handler.setFilterValues(values); } /** * @deprecated v34 Use the same method on the filter handler (`api.getColumnFilterHandler()`) instead. */ resetFilterValues() { _warn19(283); this.handler.resetFilterValues(); } /** * @deprecated v34 Use the same method on the filter handler (`api.getColumnFilterHandler()`) instead. */ refreshFilterValues() { _warn19(283); this.doRefreshFilterValues(); } doRefreshFilterValues() { this.handler.refreshFilterValues(); } /** * @deprecated v34 Internal method - should only be called by the grid. */ onAnyFilterChanged() { } onMiniFilterInput(silent) { if (!this.doSetMiniFilter(this.eMiniFilter.getValue())) { return; } if (silent) { this.showOrHideResults(); 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; _setDisplayed16(this.eFilterNoMatches, hideResults); _setDisplayed16(this.eSetFilterList, !hideResults); } resetMiniFilter() { this.eMiniFilter.setValue(null, true); this.doSetMiniFilter(null); } onMiniFilterKeyDown(e) { const { excelMode, readOnly } = this.params; if (e.key === KeyCode26.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, silent) { this.eMiniFilter.setValue(newMiniFilter, silent); this.onMiniFilterInput(silent); } /** Sets mini filter value. Returns true if it changed from last value, otherwise false. */ doSetMiniFilter(value) { value = _makeNull4(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() { _warn19(283); return this.handler.getFilterKeys(); } /** * @deprecated v34 Use the same method on the filter handler (`api.getColumnFilterHandler()`) instead. */ getFilterValues() { _warn19(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).includes(formattedFilterText); 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() && _exists15(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(_makeNull4(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); for (const func of this.handlerDestroyFuncs ?? []) { 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 import { BeanStub as BeanStub18, _addGridCommonParams as _addGridCommonParams14, _debounce as _debounce3, _error as _error3, _isClientSideRowModel as _isClientSideRowModel3, _last as _last8, _makeNull as _makeNull7, _toStringOrNull as _toStringOrNull5 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/setFilter/clientSideValueExtractor.ts import { AgPromise as AgPromise4, BeanStub as BeanStub16, _makeNull as _makeNull5 } from "ag-grid-community"; var ClientSideValuesExtractor = class extends BeanStub16 { 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 AgPromise4((resolve) => { if (this.beans.rowModel.rowCountReady) { 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 = _makeNull5(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)) { for (const x of value) { 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 import { AgPromise as AgPromise5, BeanStub as BeanStub17, _addGridCommonParams as _addGridCommonParams13, _defaultComparator as _defaultComparator2, _error as _error2, _makeNull as _makeNull6, _warn as _warn20 } from "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 BeanStub17 { 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]) => _defaultComparator2(aValue, bValue); } else { entryComparator = ([_aKey, aValue], [_bKey, bValue]) => keyComparator(aValue, bValue); } this.entryComparator = entryComparator; this.keyComparator = keyComparator ?? _defaultComparator2; this.compareByValue = !!(usingComplexObjects && keyComparator || treeDataOrGrouping || treeList && !treeListPathGetter); } updateAllValues() { this.allKeys = new AgPromise5((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 = _addGridCommonParams13(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 AgPromise5((resolve) => { if (this.showAvailableOnly()) { this.allKeys.then((keys) => { const updatedKeys = keys ?? []; this.updateAvailableKeys(updatedKeys); resolve(true); }); return; } resolve(false); }); } refreshAll() { return new AgPromise5((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) { _error2(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) ?? AgPromise5.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; for (const value of values ?? []) { const valueToUse = _makeNull6(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) { _warn20(209); } else { _warn20(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); window.setTimeout(() => { if (this.isAlive()) { this.dispatchLocalEvent({ type: "availableValuesChanged" }); } }); } }; // packages/ag-grid-enterprise/src/setFilter/setFilterHandler.ts var SetFilterHandler = class extends BeanStub18 { 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; this.useValueFormatterFromColumn = 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 = _isClientSideRowModel3(gos, beans.rowModel) ? this.createManagedBean( new ClientSideValuesExtractor( createKey, caseFormat, params.getValue, isTreeDataOrGrouping, isTreeData ) ) : void 0; const valueModel = this.createManagedBean( new SetValueModel(clientSideValuesExtractor, caseFormat, createKey, isTreeDataOrGrouping, { handlerParams: params, usingComplexObjects: !!(params.filterParams.keyCreator ?? params.colDef.keyCreator) }) ); this.addManagedListeners(valueModel, { availableValuesChanged: params.onModelAsStringChange }); this.valueModel = valueModel; 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 } } = 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(resolvedKeyCreator, params); } 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.isTreeDataOrGrouping() && Array.isArray(value)) { const shouldUseLast = this.noValueFormatterSupplied || this.useValueFormatterFromColumn; if (shouldUseLast) { value = _last8(value); } } const formattedValue = this.beans.valueSvc.formatValue( this.params.column, null, value, this.valueFormatter, this.useValueFormatterFromColumn ); return (formattedValue == null ? _toStringOrNull5(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(); } /** * @param suppressAvailableValuesCheck when refreshing values via the API, the model will be reset if all available values are selected. * When refreshing due to internal changes, set this to `true` to do the reset check based on all values instead. */ refreshFilterValues(suppressAvailableValuesCheck) { if (!this.valueModel.isInitialised()) { return; } this.valueModel.refreshAll().then(() => { this.dispatchLocalEvent({ type: "dataChanged", hardRefresh: true }); this.validateModel(this.params, void 0, !suppressAvailableValuesCheck); }); } 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 = _debounce3(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(_makeNull7(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; const filterParams = params.filterParams; if (numNewValues === 0 && filterParams.excelMode) { params.onModelChange(null, additionalEventAttributes); return; } const clearOnAllSelected = !filterParams.defaultToNothingSelected && (this.valueModel.valuesType === setValueModel_default.TAKEN_FROM_GRID_VALUES || !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); } }); } 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) { _error3(250); return () => null; } if (keyCreator) { return (value, node = null) => { const params = this.getKeyCreatorParams(value, node); return _makeNull7(keyCreator(params)); }; } return (value) => _makeNull7(_toStringOrNull5(value)); } getKeyCreatorParams(value, node = null) { const { colDef, column } = this.params; return _addGridCommonParams14(this.gos, { value, colDef, column, node, data: node?.data }); } setValueFormatter(keyCreator, params) { const { colDef: { refData, valueFormatter }, filterParams: { treeList, valueFormatter: providedValueFormatter } } = params; const hasKeyCreatorButNoFormatterNorTreeList = keyCreator && !(providedValueFormatter || treeList || valueFormatter); if (hasKeyCreatorButNoFormatterNorTreeList) { _error3(249); this.valueFormatter = void 0; this.noValueFormatterSupplied = true; this.useValueFormatterFromColumn = false; return; } let resolvedFormatter = providedValueFormatter; if (!resolvedFormatter && !valueFormatter && !refData) { resolvedFormatter = (params2) => _toStringOrNull5(params2.value); } this.valueFormatter = resolvedFormatter; this.noValueFormatterSupplied = !providedValueFormatter && !valueFormatter; this.useValueFormatterFromColumn = !providedValueFormatter && !!valueFormatter; } shouldUseValueFormatterFromColumn() { return this.useValueFormatterFromColumn && !this.valueFormatter; } getCrossFilterModel(callback) { const { createKey, valueModel, params } = this; return callback(createKey, valueModel.availableKeys, params.model?.values); } destroy() { this.appliedModel.destroy(); super.destroy(); this.valueModel = void 0; } }; // packages/ag-grid-enterprise/src/setFilter/setFloatingFilter.ts import { AgInputTextFieldSelector as AgInputTextFieldSelector7, Component as Component32, RefPlaceholder as RefPlaceholder30, _error as _error4 } from "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 Component32 { constructor() { super(SetFloatingFilterElement, [AgInputTextFieldSelector7]); this.eFloatingFilterText = RefPlaceholder30; } 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)) { _error4(248); return; } cb(filter); }); } updateFloatingFilterText(parentModel) { 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)); }); } } }; // 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, _ColumnFilterModule] }; // packages/ag-grid-enterprise/src/statusBar/statusBarModule.ts import { _KeyboardNavigationModule } from "ag-grid-community"; // packages/ag-grid-enterprise/src/statusBar/agStatusBar.ts import { AgPromise as AgPromise6, Component as Component33, RefPlaceholder as RefPlaceholder31, _addGridCommonParams as _addGridCommonParams15, _clearElement as _clearElement10, _removeFromParent as _removeFromParent6, _warn as _warn21 } from "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 AgStatusBarValidationMap = { agAggregationComponent: { rowModels: ["clientSide", "serverSide"], warnArgs: [221] }, agFilteredRowCountComponent: { rowModels: ["clientSide"], warnArgs: [222] }, agSelectedRowCountComponent: { rowModels: ["clientSide", "serverSide"], warnArgs: [223] }, agTotalAndFilteredRowCountComponent: { rowModels: ["clientSide"], warnArgs: [224] }, agTotalRowCountComponent: { rowModels: ["clientSide"], warnArgs: [225] } }; 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 Component33 { constructor() { super(AgStatusBarElement); this.updateQueued = false; this.panelsPromise = AgPromise6.resolve(); this.eStatusBarLeft = RefPlaceholder31; this.eStatusBarCenter = RefPlaceholder31; this.eStatusBarRight = RefPlaceholder31; 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)); } getValidPanels() { const gos = this.gos; const statusPanels = gos.get("statusBar")?.statusPanels; if (!statusPanels) { return statusPanels; } return statusPanels.filter((panel) => { const { rowModels, warnArgs } = AgStatusBarValidationMap[panel.statusPanel] ?? {}; if (!rowModels) { return true; } if (rowModels.includes(gos.get("rowModelType"))) { return true; } _warn21(...warnArgs); return false; }); } processStatusPanels(existingStatusPanelsToReuse) { const statusPanels = this.getValidPanels(); 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 = AgPromise6.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.getValidPanels(); const validStatusBarPanelsProvided = Array.isArray(statusPanels) && statusPanels.length > 0; this.setDisplayed(validStatusBarPanelsProvided); const existingStatusPanelsToReuse = /* @__PURE__ */ new Map(); if (validStatusBarPanelsProvided) { for (const statusPanelConfig of statusPanels) { const key = statusPanelConfig.key ?? statusPanelConfig.statusPanel; const existingStatusPanel = this.statusBarSvc.getStatusPanel(key); if (existingStatusPanel?.refresh) { const newParams = _addGridCommonParams15(this.gos, { ...statusPanelConfig.statusPanelParams ?? {}, key }); const hasRefreshed = existingStatusPanel.refresh(newParams); if (hasRefreshed) { existingStatusPanelsToReuse.set(key, existingStatusPanel); delete this.compDestroyFunctions[key]; _removeFromParent6(existingStatusPanel.getGui()); } } } } this.resetStatusBar(); if (validStatusBarPanelsProvided) { this.processStatusPanels(existingStatusPanelsToReuse); } } resetStatusBar() { _clearElement10(this.eStatusBarLeft); _clearElement10(this.eStatusBarCenter); _clearElement10(this.eStatusBarRight); this.destroyComponents(); this.statusBarSvc.unregisterAllComponents(); } destroy() { this.destroyComponents(); super.destroy(); } destroyComponents() { for (const func of Object.values(this.compDestroyFunctions)) { func(); } this.compDestroyFunctions = {}; } createAndRenderComponents(statusBarComponents, ePanelComponent, existingStatusPanelsToReuse) { const componentDetails = []; for (const componentConfig of statusBarComponents) { const key = componentConfig.key || componentConfig.statusPanel; const existingStatusPanel = existingStatusPanelsToReuse.get(key); let promise; if (existingStatusPanel) { promise = AgPromise6.resolve(existingStatusPanel); } else { const compDetails = getStatusPanelCompDetails( this.userCompFactory, componentConfig, _addGridCommonParams15(this.gos, { key }) ); if (compDetails == null) { continue; } promise = compDetails.newAgStackInstance(); } componentDetails.push({ key, promise }); } return AgPromise6.all(componentDetails.map((details) => details.promise)).then(() => { for (const componentDetail of componentDetails) { 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 import { Component as Component35, RefPlaceholder as RefPlaceholder33, _createCellId, _exists as _exists16, _formatNumberCommas, _getRowBelow, _getRowNode as _getRowNode2, _isRowBefore, _missing as _missing2, _parseBigIntOrNull as _parseBigIntOrNull2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/statusBar/providedPanels/agNameValue.ts import { Component as Component34, RefPlaceholder as RefPlaceholder32, _addGridCommonParams as _addGridCommonParams16 } from "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 MIN_SAFE_BIGINT = BigInt(Number.MIN_SAFE_INTEGER); var MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER); var AgNameValue = class extends Component34 { constructor() { super(AgNameValueElement); this.eLabel = RefPlaceholder32; this.eValue = RefPlaceholder32; } setLabel(key, defaultValue) { this.setDisplayed(false); this.eLabel.textContent = this.getLocaleTextFunc()(key, defaultValue); } setValue(value, totalRows) { let numericValue = null; let bigintValue; if (typeof value === "bigint") { bigintValue = value; if (value >= MIN_SAFE_BIGINT && value <= MAX_SAFE_BIGINT) { numericValue = Number(value); } } else { numericValue = value; } this.eValue.textContent = this.valueFormatter( _addGridCommonParams16(this.gos, { value: numericValue, bigintValue, 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 _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 Component35 { constructor() { super(AggregationCompElement, [AgNameValueSelector]); this.sumAggregationComp = RefPlaceholder33; this.countAggregationComp = RefPlaceholder33; this.minAggregationComp = RefPlaceholder33; this.maxAggregationComp = RefPlaceholder33; this.avgAggregationComp = RefPlaceholder33; } postConstruct() { 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 ?? ((params2) => { const { value, bigintValue } = params2; if (bigintValue != null) { return bigintValue.toString(); } return _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 (_exists16(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]; } /** * Aggregation notes: * - Uses bigint aggregation when bigint values are present and all numeric values are safe integers. * - Non-integer or unsafe integer numbers fall back to number aggregation to avoid precision loss. * - Avg uses integer division when bigint aggregation is active, discarding the fractional part. * - String values are trimmed; finite numeric strings are aggregated as numbers, while integer strings beyond the * safe integer range are parsed as bigint. */ onCellSelectionChanged() { const beans = this.beans; const { rangeSvc, valueSvc } = beans; const cellRanges = rangeSvc?.getCellRanges(); let sum = 0; let sumBigint = 0n; let hasBigInt = false; let seenNonInteger = false; let count = 0; let numericCount = 0; let min = null; let max = null; let minBigint = null; let maxBigint = null; const addValue = (value) => { if (typeof value === "number") { sum += value; if (min === null || value < min) { min = value; } if (max === null || value > max) { max = value; } if (!Number.isInteger(value) || !Number.isSafeInteger(value)) { seenNonInteger = true; } else { const bigintValue = BigInt(value); sumBigint += bigintValue; if (minBigint === null || bigintValue < minBigint) { minBigint = bigintValue; } if (maxBigint === null || bigintValue > maxBigint) { maxBigint = bigintValue; } } } else { hasBigInt = true; sumBigint += value; if (minBigint === null || value < minBigint) { minBigint = value; } if (maxBigint === null || value > maxBigint) { maxBigint = value; } const numberValue = Number(value); sum += numberValue; if (min === null || numberValue < min) { min = numberValue; } if (max === null || numberValue > max) { max = numberValue; } } numericCount++; }; 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 = _missing2(currentRow) || !currentRow || _isRowBefore(lastRow, currentRow); if (finishedAllRows || !currentRow || !cellRange.columns) { break; } cellRange.columns.forEach((col) => { if (currentRow === null) { return; } const cellId = _createCellId({ rowPinned: currentRow.rowPinned, column: col, rowIndex: currentRow.rowIndex }); if (cellsSoFar[cellId]) { return; } cellsSoFar[cellId] = true; const rowNode = _getRowNode2(beans, currentRow); if (_missing2(rowNode)) { return; } let value = valueSvc.getValue(col, rowNode, "data"); if (_missing2(value) || value === "") { return; } count++; if (typeof value === "object" && "value" in value) { value = value.value; if (value === "") { return; } } if (typeof value === "string") { const trimmedValue = value.trim(); if (trimmedValue === "") { return; } const asNumber = Number(trimmedValue); if (!Number.isFinite(asNumber)) { return; } if (sum + asNumber >= Number.MAX_SAFE_INTEGER || sum + asNumber <= Number.MIN_SAFE_INTEGER || asNumber >= Number.MAX_SAFE_INTEGER || asNumber <= Number.MIN_SAFE_INTEGER) { value = _parseBigIntOrNull2(trimmedValue); if (value === null) { value = asNumber; } } else { value = asNumber; } } if (typeof value === "number" && !isNaN(value) || typeof value === "bigint") { addValue(value); } }); currentRow = _getRowBelow(beans, currentRow); } } } const moreThanOneValue = count > 1; const moreThanOneNum = numericCount > 1; const useBigintAggregation = hasBigInt && !seenNonInteger; let avg; if (useBigintAggregation) { avg = sumBigint / BigInt(numericCount); } else { avg = sum / numericCount; } const sumValue = moreThanOneNum ? useBigintAggregation ? sumBigint : sum : null; const minValue = moreThanOneNum ? useBigintAggregation ? minBigint : min : null; const maxValue = moreThanOneNum ? useBigintAggregation ? maxBigint : max : null; const avgValue = moreThanOneNum ? avg : null; const showAvg = moreThanOneNum; this.setAggregationComponentValue("count", count, moreThanOneValue); this.setAggregationComponentValue("sum", sumValue, moreThanOneNum); this.setAggregationComponentValue("min", minValue, moreThanOneNum); this.setAggregationComponentValue("max", maxValue, moreThanOneNum); this.setAggregationComponentValue("avg", avgValue, showAvg); } }; // packages/ag-grid-enterprise/src/statusBar/providedPanels/filteredRowsComp.ts import { _formatNumberCommas as _formatNumberCommas2 } from "ag-grid-community"; var FilteredRowsComp = class extends AgNameValue { postConstruct() { this.setLabel("filteredRows", "Filtered"); 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 }) => _formatNumberCommas2(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 import { _formatNumberCommas as _formatNumberCommas3 } from "ag-grid-community"; var SelectedRowsComp = class extends AgNameValue { postConstruct() { 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 _formatNumberCommas3(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 import { _formatNumberCommas as _formatNumberCommas4 } from "ag-grid-community"; var TotalAndFilteredRowsComp = class extends AgNameValue { postConstruct() { 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 = _formatNumberCommas4(value, getLocaleTextFunc); const totalRowCount = _formatNumberCommas4(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 import { _formatNumberCommas as _formatNumberCommas5 } from "ag-grid-community"; var TotalRowsComp = class extends AgNameValue { postConstruct() { this.setLabel("totalRows", "Total Rows"); 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 }) => _formatNumberCommas5(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 import { _unwrapUserComp as _unwrapUserComp2 } from "ag-grid-community"; function getStatusPanel(beans, key) { const comp = beans.statusBarSvc?.getStatusPanel(key); return _unwrapUserComp2(comp); } // packages/ag-grid-enterprise/src/statusBar/statusBarService.ts import { BeanStub as BeanStub19 } from "ag-grid-community"; var StatusBarService = class extends BeanStub19 { // 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, _KeyboardNavigationModule] }; // packages/ag-grid-enterprise/src/excelExport/excelExportModule.ts import { _SharedExportModule } from "ag-grid-community"; // packages/ag-grid-enterprise/src/excelExport/excelExportApi.ts import { _warn as _warn22 } from "ag-grid-community"; function assertNotExcelMultiSheet(beans) { if (beans.excelCreator?.getFactoryMode() === "MULTI_SHEET") { _warn22(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: [_SharedExportModule, EnterpriseCoreModule] }; // packages/ag-grid-enterprise/src/multiFilter/multiFilterModule.ts import { _ColumnFilterModule as _ColumnFilterModule2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/multiFilter/multiFilter.ts import { AgPromise as AgPromise8, FilterWrapperComp, LocalEventService as LocalEventService2, ProvidedFilter as ProvidedFilter3, _getFilterModel, _refreshFilterUi, _refreshHandlerAndUi, _removeFromArray, _updateFilterModel } from "ag-grid-community"; // packages/ag-grid-enterprise/src/multiFilter/baseMultiFilter.ts import { AgPromise as AgPromise7, KeyCode as KeyCode27, TabGuardComp as TabGuardComp2, _createElement as _createElement10, _focusInto as _focusInto7, _getActiveDomElement as _getActiveDomElement11, _isNothingFocused as _isNothingFocused3, _setAriaRole as _setAriaRole8 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/multiFilter/multiFilterUtil.ts import { ProvidedFilter as ProvidedFilter2 } from "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 ProvidedFilter2 ? 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 TabGuardComp2 { 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 AgPromise7.resolve(); } this.tabGuardFeature.removeAllChildrenExceptTabGuards(); this.destroyChildren(); return AgPromise7.all( this.getFilterWrappers().map((wrapper, index) => { if (!wrapper) { return AgPromise7.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 = AgPromise7.resolve(group.getGui()); } else { filterGuiPromise = AgPromise7.resolve(comp.getGui()); } return filterGuiPromise; }) ).then((filterGuis) => { filterGuis.forEach((filterGui, index) => { if (!filterGui) { return; } if (index > 0) { this.appendChild(_createElement10({ tag: "div", cls: "ag-filter-separator" })); } this.appendChild(filterGui); }); this.filterGuis = filterGuis; this.lastOpenedInContainer = container; }); } destroyChildren() { for (const func of this.guiDestroyFuncs) { func(); } this.guiDestroyFuncs.length = 0; this.filterGuis.length = 0; } insertFilterMenu(comp, filter, name) { const eGui = comp.getGui(); _setAriaRole8(eGui, "dialog"); const menuItem = this.createBean(new MenuItemComponent()); 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: MenuItemRenderer, 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 KeyCode27.UP: case KeyCode27.RIGHT: case KeyCode27.DOWN: case KeyCode27.LEFT: e.preventDefault(); if (key === KeyCode27.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 = AgPromise7.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 (!_focusInto7(filterGui)) { filterGui.focus({ preventScroll: true }); } hasFocused = true; } } }); } const activeEl = _getActiveDomElement11(beans); if (!hasFocused && (_isNothingFocused3(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 = _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 AgPromise8((resolve) => { AgPromise8.all(filterPromises).then((wrappers) => { this.wrappers = wrappers; this.refreshGui("columnMenu").then(() => { resolve(); }); }); }).then(() => { for (const f of this.afterFiltersReadyFuncs) { 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 AgPromise8((resolve) => { const promise = filter.setModel(filterModel); if (promise) { promise.then(resolve); } else { 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) { const newState = { model: modelForFilter, state: state?.state }; wrapper.state = newState; wrapper.model = modelForFilter; promises.push( _refreshHandlerAndUi( () => AgPromise8.resolve({ filter, filterParams }), handler, handlerParams, modelForFilter, newState, "api" ).then(() => { this.updateActiveListForHandler(index, wrapper.model); }) ); } else { promises.push( setFilterModel(filter, modelForFilter).then(() => { this.updateActiveListForFilter(index, filter); }) ); } }); return AgPromise8.all(promises).then(() => { }); } applyModel(source = "api") { let result = false; for (const wrapper of this.wrappers) { if (wrapper) { const filter = wrapper.filter; if (filter instanceof ProvidedFilter3) { result = filter.applyModel(source) || result; } } } return result; } getChildFilterInstance(index) { return this.wrappers[index]?.filter; } getNumChildFilters() { return this.wrappers.length; } destroy() { for (const wrapper of this.wrappers) { 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 onModelChange = (model, additionalEventAttributes) => { const wrapper = this.wrappers[index]; if (!wrapper) { return; } const newState = { model, state: wrapper.state?.state }; wrapper.state = newState; wrapper.model = model; _refreshHandlerAndUi( () => AgPromise8.resolve({ filter: wrapper.filter, filterParams: wrapper.filterParams }), wrapper.handler, wrapper.handlerParams, model, newState, "ui" ).then(() => { this.onHandlerModelChanged(index, wrapper.model, additionalEventAttributes); }); }; 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, onModelChange ); } return updatedParams; } ); if (!createFilterUi) { return AgPromise8.resolve(null); } let handlerParams; if (handler) { const { doesRowPassOtherFilter, getValue } = originalHandlerParams; handlerParams = { ...originalHandlerParams, onModelChange, 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, onModelChange) { const column = this.params.column; const eventSvc = new LocalEventService2(); displayParams.model = initialModelForFilter; displayParams.state = { model: initialModelForFilter }; displayParams.onModelChange = onModelChange; 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); _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; _updateFilterModel({ action, filterParams: wrapper.filterParams, getFilterUi: () => { const promise = AgPromise8.resolve(wrapper.filter); return { created: true, filterParams: wrapper.filterParams, compDetails: getCompDetails(), create: () => promise, promise }; }, getModel, getState: () => wrapper?.state ?? { model: getModel() }, updateState: (state) => updateState(wrapper, state), updateModel: (newModel) => wrapper.filterParams?.onModelChange(newModel, additionalEventAttributes), processModelToApply: wrapper.handler?.processModelToApply?.bind(wrapper.handler) }); }; 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 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; _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 import { BeanStub as BeanStub20, _removeFromArray as _removeFromArray2, _warn as _warn23 } from "ag-grid-community"; var MultiFilterHandler = class extends BeanStub20 { 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) { _warn23(278, { colId: params.column.getColId() }); return; } const { handler, handlerParams } = wrapper; handler.init?.({ ...this.updateHandlerParams(handlerParams, index, true), 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 updatedParams = this.updateHandlerParams(params, index, false, filters?.[index].filterParams); wrapper.handlerParams = updatedParams; wrapper.handler.refresh?.({ ...updatedParams, model: getFilterModelForIndex(model, index), source }); } }); if (params.source !== "floating" && params.source !== "ui") { this.resetActiveList(params.model); } if (params.additionalEventAttributes?.fromButtons) { this.onAnyFilterChanged(); } } updateHandlerParams(params, index, isInit, providedFilterParams) { 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), filterParams: this.updateFilterParams(params, isInit, providedFilterParams) }; return handlerParams; } updateFilterParams(params, isInit, providedFilterParams) { const originalFilterParams = params.filterParams; if (providedFilterParams?.buttons && isInit) { _warn23(292, { colId: params.column.getColId() }); } const filterParamsForFilter = providedFilterParams ? { ...originalFilterParams, ...providedFilterParams } : originalFilterParams; if (!filterParamsForFilter.buttons) { return filterParamsForFilter; } if (providedFilterParams) { delete filterParamsForFilter.buttons; return filterParamsForFilter; } const { buttons: _, ...filterParamsForFilterWithoutButtons } = filterParamsForFilter; return filterParamsForFilterWithoutButtons; } 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; _removeFromArray2(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() { for (const wrapper of this.handlerWrappers) { this.destroyBean(wrapper?.handler); } this.handlerWrappers.length = 0; super.destroy(); } }; // packages/ag-grid-enterprise/src/multiFilter/multiFilterService.ts import { BeanStub as BeanStub21, _getDefaultSimpleFilter, _getFilterParamsForDataType } from "ag-grid-community"; var MultiFilterService = class extends BeanStub21 { constructor() { super(...arguments); this.beanName = "multiFilter"; } getParamsForDataType(existingFilterParams, existingFilterValueGetter, dataTypeDefinition, formatValue) { let filters = existingFilterParams?.filters; const beans = this.beans; if (!filters) { const simpleFilter = _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 } = _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 import { AgPromise as AgPromise9, _getFilterDetails, _isUseApplyButton, _refreshFilterUi as _refreshFilterUi2, _warn as _warn24 } from "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; const filterDefs = getMultiFilterDefs(params).map((filterDef) => { if (filterDef.filterParams?.buttons) { _warn24(292, { colId: params.column.getColId() }); const newParams = { ...filterDef.filterParams }; delete newParams.buttons; return { ...filterDef, filterParams: newParams }; } return filterDef; }); this.filterDefs = filterDefs; this.allState = params.state; const filterPromises = this.filterDefs.map( (filterDef, index) => this.createFilter(filterDef, index) ); return new AgPromise9((resolve) => { AgPromise9.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) }; _refreshFilterUi2(filter, filterParams[index], modelForFilter, stateForFilter, source); }); return true; } getLastActiveFilterIndex() { return this.getHandler().getLastActiveFilterIndex?.() ?? null; } getChildFilterInstance(index) { return this.filters[index] ?? void 0; } getNumChildFilters() { return this.filters.length; } destroy() { for (const filter of this.filters) { 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 = _getFilterDetails( userCompFactory, filterDef, filterParams, "agTextColumnFilter" ); if (!compDetails) { return AgPromise9.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 (_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 import { AgPromise as AgPromise10, Component as Component36, _clearElement as _clearElement11, _error as _error5, _getDefaultFloatingFilterType, _getFloatingFilterCompDetails, _mergeDeep as _mergeDeep2, _setDisplayed as _setDisplayed17 } from "ag-grid-community"; var MultiFloatingFilterElement = { tag: "div", cls: "ag-multi-floating-filter ag-floating-filter-input" }; var MultiFloatingFilterComp = class extends Component36 { 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 AgPromise10.all(floatingFilterPromises).then((floatingFilters) => { floatingFilters.forEach((floatingFilter, index) => { this.floatingFilters.push(floatingFilter); const gui = floatingFilter.getGui(); this.appendChild(gui); if (index > 0) { _setDisplayed17(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) => { _setDisplayed17(filter.getGui(), i === 0); }); } else { const lastActiveFloatingFilterIndex = reactiveParams.getHandler()?.getLastActiveFilterIndex?.(); this.floatingFilters.forEach((filter, i) => { const shouldShow = lastActiveFloatingFilterIndex == null ? i === 0 : i === lastActiveFloatingFilterIndex; _setDisplayed17(filter.getGui(), shouldShow); }); } } } else { _clearElement11(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); }; } _mergeDeep2(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?.afterFloatingFilter) { return; } this.parentMultiFilterInstance((parent) => { if (model == null) { this.floatingFilters.forEach((filter, i) => { filter.onParentModelChanged(null, event); _setDisplayed17(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; _setDisplayed17(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 = _getDefaultFloatingFilterType( frameworkOverrides, filterDef, () => colFilter.getDefaultFloatingFilter(this.params.column) ) ?? "agReadOnlyFloatingFilter"; return _getFloatingFilterCompDetails(userCompFactory, filterDef, params, defaultComponentName); } parentMultiFilterInstance(cb) { this.params.parentFilterInstance((parent) => { if (!(parent instanceof MultiFilter || parent instanceof MultiFilterUi)) { _error5(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, _ColumnFilterModule2, MenuItemModule] }; // packages/ag-grid-enterprise/src/rowGrouping/rowGroupingModule.ts import { _ColumnFilterModule as _ColumnFilterModule3, _PopupModule as _PopupModule4 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/aggregation/aggColumnNameService.ts import { BeanStub as BeanStub22, _exists as _exists17 } from "ag-grid-community"; var AggColumnNameService = class extends BeanStub22 { 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 = _exists17(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 isGrouping = rowGroupColsSvc?.columns.length !== 0; const aggregationPresent = colModel.isPivotMode() || isGrouping || this.gos.get("treeData"); 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 import { BeanStub as BeanStub23, _exists as _exists18, _last as _last9 } from "ag-grid-community"; var defaultAggFuncNames = { sum: "Sum", first: "First", last: "Last", min: "Min", max: "Max", count: "Count", avg: "Average" }; var AggFuncService = class extends BeanStub23 { 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 = _exists18(this.aggFuncsMap[func]); return allowed && funcExists; } getDefaultFuncLabel(fctName) { return defaultAggFuncNames[fctName] ?? fctName; } getDefaultAggFunc(column) { const defaultAgg = column.getColDef().defaultAggFunc; if (_exists18(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 ? _last9(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 import { BeanStub as BeanStub24, _getGrandTotalRow as _getGrandTotalRow3, _getGroupAggFiltering, _isClientSideRowModel as _isClientSideRowModel4 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/aggregation/aggUtils.ts import { _addGridCommonParams as _addGridCommonParams17, _warn as _warn25 } from "ag-grid-community"; function _aggregateValues({ beans, values, aggFuncOrString, column, rowNode, pivotResultColumn, aggregatedChildren }) { const aggFunc = typeof aggFuncOrString === "string" ? beans.aggFuncSvc.getAggFunc(aggFuncOrString) : aggFuncOrString; if (typeof aggFunc !== "function") { _warn25(109, { inputValue: aggFuncOrString.toString(), allSuggestions: beans.aggFuncSvc.getFuncNames(column) }); return null; } const params = _addGridCommonParams17(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, aggregatedChildren }); return aggFunc(params); } // packages/ag-grid-enterprise/src/aggregation/aggregationStage.ts var AggregationStage = class extends BeanStub24 { constructor() { super(...arguments); this.beanName = "aggStage"; this.step = "aggregate"; this.refreshProps = [ "getGroupRowAgg", "alwaysAggregateAtRootLevel", "suppressAggFilteredOnly", "grandTotalRow" ]; this.clientSide = false; } wireBeans(beans) { this.colModel = beans.colModel; this.pivotColsSvc = beans.pivotColsSvc; this.valueColsSvc = beans.valueColsSvc; this.pivotResultCols = beans.pivotResultCols; this.valueSvc = beans.valueSvc; this.clientSide = _isClientSideRowModel4(beans.gos); } // it's possible to recompute the aggregate without doing the other parts // + api.refreshClientSideRowModel('aggregate') execute(changedPath) { const noValueColumns = !this.valueColsSvc?.columns?.length; const noUserAgg = !this.gos.getCallback("getGroupRowAgg"); if (noValueColumns && noUserAgg && changedPath?.active) { return; } const aggDetails = this.createAggDetails(changedPath); this.recursivelyCreateAggData(aggDetails); } createAggDetails(changedPath) { 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: !!_getGrandTotalRow3(this.gos), changedPath, valueColumns: measureColumns ?? [], pivotColumns, filteredOnly: !this.isSuppressAggFilteredOnly(), userAggFunc: this.gos.getCallback("getGroupRowAgg") }; return aggDetails; } isSuppressAggFilteredOnly() { const isGroupAggFiltering = _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.setAggDataWithSiblings(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.setAggDataWithSiblings(rowNode, aggResult); } aggregateRowNodeUsingValuesAndPivot(rowNode) { const result = {}; const secondaryColumns = this.pivotResultCols?.getPivotResultCols()?.list ?? []; let canSkipTotalColumns = true; const beans = this.beans; const valueSvc = this.valueSvc; for (let i = 0; i < secondaryColumns.length; i++) { const secondaryCol = secondaryColumns[i]; const colDef = secondaryCol.getColDef(); if (colDef.pivotTotalColumnIds != null) { canSkipTotalColumns = false; continue; } let values; let aggregatedChildren; const pivotValueColumn = colDef.pivotValueColumn; if (rowNode.leafGroup) { aggregatedChildren = getNodesFromMappedSet(rowNode.childrenMapped, colDef.pivotKeys); values = getValuesFromNodes(valueSvc, aggregatedChildren, pivotValueColumn); } else { aggregatedChildren = rowNode.childrenAfterFilter; values = getAggDataFromNodes(aggregatedChildren, secondaryCol.getId()); } result[colDef.colId] = _aggregateValues({ beans, values, aggFuncOrString: pivotValueColumn.getAggFunc(), column: pivotValueColumn, rowNode, pivotResultColumn: secondaryCol, aggregatedChildren: aggregatedChildren ?? [] }); } if (!canSkipTotalColumns) { for (let i = 0; i < secondaryColumns.length; i++) { const secondaryCol = secondaryColumns[i]; const colDef = secondaryCol.getColDef(); if (!colDef.pivotTotalColumnIds?.length) { continue; } const aggResults = colDef.pivotTotalColumnIds.map( (currentColId) => result[currentColId] ); result[colDef.colId] = _aggregateValues({ beans, values: aggResults, aggFuncOrString: colDef.pivotValueColumn.getAggFunc(), column: colDef.pivotValueColumn, rowNode, pivotResultColumn: secondaryCol, aggregatedChildren: rowNode.childrenAfterFilter ?? [] }); } } 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 aggregatedChildren = (filteredOnly ? rowNode.childrenAfterFilter : rowNode.childrenAfterGroup) ?? []; const values2d = getValuesFromNodesMultiColumn(this.valueSvc, aggregatedChildren, changedValueColumns); const oldValues = rowNode.aggData; const beans = this.beans; changedValueColumns.forEach((valueColumn, index) => { result[valueColumn.getId()] = _aggregateValues({ beans, values: values2d[index], aggFuncOrString: valueColumn.getAggFunc(), column: valueColumn, rowNode, pivotResultColumn: void 0, aggregatedChildren }); }); if (notChangedValueColumns && oldValues) { for (const valueColumn of notChangedValueColumns) { result[valueColumn.getId()] = oldValues[valueColumn.getId()]; } } return result; } getAggregatedChildren(rowNode, col) { if (!rowNode?.group || !this.clientSide) { return []; } if (rowNode.rowPinned) { const sourceRow = rowNode.pinnedSibling; if (!sourceRow) { return []; } rowNode = sourceRow; } const colDef = col?.getColDef(); const pivotKeys = colDef?.pivotKeys; if (pivotKeys) { if (rowNode.leafGroup && pivotKeys.length && !colDef.pivotTotalColumnIds) { return getNodesFromMappedSet(rowNode.childrenMapped, pivotKeys) ?? []; } return rowNode.childrenAfterFilter ?? rowNode.childrenAfterGroup ?? []; } if (this.isSuppressAggFilteredOnly()) { return rowNode.childrenAfterGroup ?? []; } return rowNode.childrenAfterFilter ?? rowNode.childrenAfterGroup ?? []; } /** * Sets aggData on a row node and all its siblings (footer sibling and pinned siblings). * This ensures all related nodes stay in sync when aggregation data changes. */ setAggDataWithSiblings(rowNode, newAggData) { this.setAggData(rowNode, newAggData); const pinnedSibling = rowNode.pinnedSibling; if (pinnedSibling) { this.setAggData(pinnedSibling, newAggData); } const sibling = rowNode.sibling; if (sibling) { this.setAggData(sibling, newAggData); const siblingPinnedSibling = sibling.pinnedSibling; if (siblingPinnedSibling) { this.setAggData(siblingPinnedSibling, newAggData); } } } 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); } } } } } }; var getValuesFromNodes = (valueSvc, nodes, column) => { if (!nodes) { return []; } const len = nodes.length; const result = new Array(len); for (let i = 0; i < len; ++i) { result[i] = valueSvc.getValue(column, nodes[i], "data"); } return result; }; var getValuesFromNodesMultiColumn = (valueSvc, nodes, columns) => { const columnCount = columns.length; const values = new Array(columnCount); for (let j = 0; j < columnCount; j++) { values[j] = []; } const rowCount = nodes.length; for (let i = 0; i < rowCount; i++) { const childNode = nodes[i]; for (let j = 0; j < columnCount; j++) { values[j].push(valueSvc.getValue(columns[j], childNode, "data")); } } return values; }; var getAggDataFromNodes = (nodes, columnId) => { if (!nodes) { return []; } const len = nodes.length; const result = new Array(len); for (let i = 0; i < len; i++) { result[i] = nodes[i].aggData?.[columnId]; } return result; }; var getNodesFromMappedSet = (mappedSet, keys) => { if (!keys) { return void 0; } let mapPointer = mappedSet; for (let i = 0; i < keys.length && mapPointer; i++) { mapPointer = mapPointer[keys[i]]; } if (Array.isArray(mapPointer)) { return mapPointer; } return void 0; }; // packages/ag-grid-enterprise/src/aggregation/filterAggregatesStage.ts import { BeanStub as BeanStub25, _getGroupAggFiltering as _getGroupAggFiltering2 } from "ag-grid-community"; var FilterAggregatesStage = class extends BeanStub25 { constructor() { super(...arguments); this.beanName = "filterAggStage"; this.step = "filter_aggregates"; this.refreshProps = []; } wireBeans(beans) { this.filterManager = beans.filterManager; } execute(changedPath) { const isPivotMode2 = this.beans.colModel.isPivotMode(); const isAggFilterActive = this.filterManager?.isAggregateFilterPresent() || this.filterManager?.isAggregateQuickFilterPresent(); const defaultPrimaryColumnPredicate = (params) => !params.node.group; const defaultSecondaryColumnPredicate = (params) => params.node.leafGroup; const applyFilterToNode = _getGroupAggFiltering2(this.gos) || (isPivotMode2 ? defaultSecondaryColumnPredicate : defaultPrimaryColumnPredicate); const preserveChildren = (node, recursive = false) => { if (node.childrenAfterFilter) { node.childrenAfterAggFilter = node.childrenAfterFilter; if (recursive) { for (const child of node.childrenAfterAggFilter) { 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 import { BeanStub as BeanStub26, _addGridCommonParams as _addGridCommonParams18, _getGrandTotalRow as _getGrandTotalRow4, _getGroupTotalRowCallback, _warn as _warn26 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/aggregation/footerUtils.ts import { _createRowNodeSibling } from "ag-grid-community"; function _createRowNodeFooter(rowNode, beans) { if (rowNode.sibling) { return; } const footerNode = _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) { const sibling = rowNode.sibling; if (!sibling) { return; } sibling._destroy(false); rowNode.sibling = void 0; sibling.sibling = void 0; } // packages/ag-grid-enterprise/src/aggregation/footerService.ts var FooterService = class extends BeanStub26 { constructor() { super(...arguments); this.beanName = "footerSvc"; } addTotalRows(startIndex, node, callback, includeFooterNodes, isRootNode, position) { let index = startIndex; if (isRootNode) { const grandTotal = includeFooterNodes && _getGrandTotalRow4(this.gos); if (_positionMatchesGrandTotalRow(position, grandTotal)) { _createRowNodeFooter(node, this.beans); callback(node.sibling, index++); } return index; } const isGroupIncludeFooter = _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?.columns[0] === col; } return !!node.rowGroupColumn && col?.isRowGroupDisplayed(node.rowGroupColumn.getId()); } applyTotalPrefix(value, formattedValue, node, column) { const totalValueGetter = column.getColDef().cellRendererParams?.totalValueGetter; if (totalValueGetter) { const valueGetterParams = _addGridCommonParams18(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); } _warn26(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 import { BaseColsService, _exists as _exists19, _removeFromArray as _removeFromArray3, _warn as _warn27 } from "ag-grid-community"; var ValueColsSvc = class extends 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) => _removeFromArray3(this.columns, column) }; } extractCols(source, oldProvidedCols) { this.columns = super.extractCols(source, oldProvidedCols); for (const col of this.columns) { 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 (_exists19(aggFunc)) { _warn27(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/groupHierarchy/groupHierarchyColService.ts import { AgColumn, BeanStub as BeanStub27, GROUP_HIERARCHY_COLUMN_ID_PREFIX, _addColumnDefaultAndTypes, _areColIdsEqual, _columnsMatch, _destroyColumnTree, _removeAllFromArray, _updateColsMap } from "ag-grid-community"; // packages/ag-grid-enterprise/src/groupHierarchy/groupHierarchyUtils.ts import { _MONTHS, _getDateParts as _getDateParts2, _parseDateTimeFromString as _parseDateTimeFromString2 } from "ag-grid-community"; var getDate = ({ valueSvc, dataTypeSvc }, sourceCol, node) => { const innerValue = valueSvc.getValue(sourceCol, node, "data"); let date = null; if (innerValue instanceof Date) { date = innerValue; } else if (typeof innerValue === "string") { const parseDate = dataTypeSvc?.getDateParserFunction(sourceCol) ?? _parseDateTimeFromString2; date = parseDate(innerValue) ?? null; } return date; }; var getDatePartValueGetter = (beans, col, index, map) => (params) => { const date = getDate(beans, col, params.node); const parts = _getDateParts2(date); if (!parts) { return null; } return map?.(parts[index]) ?? parts[index]; }; var getHeaderValueGetter = ({ colNames }, col, part) => (params) => { const sourceName = colNames.getDisplayNameForColumn(col, params.location); if (sourceName) { return `${sourceName} (${part})`; } return ""; }; var MONTH_TO_LOCALE_KEY = Object.fromEntries(_MONTHS.map((m) => [m, m.toLowerCase()])); var numericalMonthToNamedMonth = (monthStr) => { const month = _MONTHS[Number.parseInt(monthStr, 10) - 1] ?? monthStr; const localeKey = MONTH_TO_LOCALE_KEY[month] ?? monthStr; return { month, localeKey }; }; function _getGroupHierarchy(colDef) { return colDef.groupHierarchy ?? colDef.rowGroupingHierarchy; } // packages/ag-grid-enterprise/src/groupHierarchy/groupHierarchyColService.ts var GroupHierarchyColService = class extends BeanStub27 { constructor() { super(...arguments); this.beanName = "groupHierarchyColSvc"; this.columns = null; /** Map from primary column to virtual (i.e. generated) columns */ this.sourceColumnMap = /* @__PURE__ */ new WeakMap(); /** Map from virtual column to associated primary column. Inverse of `sourceColumnMap` */ this.inverseColumnMap = /* @__PURE__ */ new WeakMap(); } addColumns(cols) { const groupHierarchyCols = this.columns; if (groupHierarchyCols == null) { return; } cols.list = groupHierarchyCols.list.filter((col) => !cols.list.some((c) => c.getColId() === col.getColId())).concat(cols.list); cols.tree = groupHierarchyCols.tree.filter((col) => !cols.tree.some((c) => c.getId() === col.getId())).concat(cols.tree); _updateColsMap(cols); } createColumns(cols) { const newSourceColumnMap = /* @__PURE__ */ new WeakMap(); const newInverseColumnMap = /* @__PURE__ */ new WeakMap(); const list = this.createGroupHierarchyColumns(cols, newSourceColumnMap, newInverseColumnMap); const areSame = _areColIdsEqual(list, this.columns?.list ?? []); if (areSame) { return; } _destroyColumnTree(this.beans, this.columns?.tree); this.columns = null; const { colGroupSvc } = this.beans; const treeDepth = colGroupSvc?.findDepth(cols.tree) ?? 0; const tree = colGroupSvc?.balanceTreeForAutoCols(list, treeDepth) ?? []; this.columns = { list, tree, treeDepth, map: {} }; this.sourceColumnMap = newSourceColumnMap; this.inverseColumnMap = newInverseColumnMap; } updateColumns(_event) { } getColumn(key) { return this.columns?.list.find((col) => _columnsMatch(col, key)) ?? null; } getColumns() { return this.columns?.list ?? null; } expandColumnInto(target, col) { const expanded = this.getVirtualColumnsForColumn(col).concat(col); for (const expandedCol of expanded) { if (!target.some((_c) => _columnsMatch(_c, expandedCol) || _c.getColId() === expandedCol.getColId())) { target.push(expandedCol); } } } compareVirtualColumns(colA, colB) { const sourceA = this.inverseColumnMap.get(colA); const sourceB = this.inverseColumnMap.get(colB); if (sourceA && sourceA === sourceB) { const hierarchyCols = this.sourceColumnMap.get(sourceA) ?? []; return hierarchyCols?.indexOf(colA) - hierarchyCols?.indexOf(colB); } if (this.sourceColumnMap.get(colA)?.includes(colB)) { return 1; } if (this.sourceColumnMap.get(colB)?.includes(colA)) { return -1; } return null; } insertVirtualColumnsForCol(columns, col) { const hierarchyCols = this.getVirtualColumnsForColumn(col); if (!hierarchyCols) { return []; } let idxCol = columns.indexOf(col); if (idxCol < 0) { idxCol = columns.length - 1; } _removeAllFromArray(columns, hierarchyCols); columns.splice(idxCol, 0, ...hierarchyCols); return hierarchyCols; } getVirtualColumnsForColumn(col) { if (this.isGroupHierarchyColsEnabledForCol(col)) { return this.sourceColumnMap.get(col) ?? []; } return []; } isGroupHierarchyColsEnabled(cols) { return cols.list.some((col) => this.isGroupHierarchyColsEnabledForCol(col)); } isGroupHierarchyColsEnabledForCol(col) { const def = col.getColDef(); const groupHierarchy = _getGroupHierarchy(def); return !!(groupHierarchy && (def.rowGroup || def.enableRowGroup || def.rowGroupIndex != null || def.pivot || def.enablePivot || def.pivotIndex != null)); } createGroupHierarchyColDefs(sourceCol) { const colDefs = []; const sourceColDef = sourceCol.getColDef(); const groupHierarchy = _getGroupHierarchy(sourceColDef); if (!groupHierarchy) { return colDefs; } if (!this.isGroupHierarchyColsEnabledForCol(sourceCol)) { return colDefs; } for (const part of groupHierarchy) { let colDef = null; if (typeof part === "string") { colDef = this.createColDefForPart(part, sourceCol, sourceColDef); } else { colDef = part; } if (colDef) { colDefs.push(colDef); } } return colDefs; } createGroupHierarchyColumns(cols, sourceColMap, inverseColMap) { if (!this.isGroupHierarchyColsEnabled(cols)) { return []; } const newCols = []; for (const col of cols.list) { for (const colDef of this.createGroupHierarchyColDefs(col)) { const colId = colDef.colId; this.gos.validateColDef(colDef, colId, true); const newCol = new AgColumn(colDef, null, colId, true); this.createBean(newCol); newCols.push(newCol); updateMap(sourceColMap, col, newCol); inverseColMap.set(newCol, col); } } return newCols; } createColDefForPart(part, sourceCol, sourceColDef) { const { beans, gos } = this; const colId = `${GROUP_HIERARCHY_COLUMN_ID_PREFIX}-${sourceCol.getColId()}-${part}`; const defaults = { enableRowGroup: sourceColDef.enableRowGroup, rowGroup: sourceColDef.rowGroup, enablePivot: sourceColDef.enablePivot, hide: true, editable: false }; const groupHierarchyConfig = gos.get("groupHierarchyConfig") ?? {}; if (part in groupHierarchyConfig) { const colDef = { ...defaults, ...groupHierarchyConfig[part] }; colDef.colId ?? (colDef.colId = colId); return _addColumnDefaultAndTypes(beans, colDef, colDef.colId, true); } const base = _addColumnDefaultAndTypes(beans, { colId, ...defaults }, colId, true); const translate = this.getLocaleTextFunc(); const translatePart = (part2, fallback) => translate?.(part2, fallback) ?? fallback; switch (part) { case "year": return { ...base, headerValueGetter: getHeaderValueGetter(beans, sourceCol, translatePart(part, "Year")), valueGetter: getDatePartValueGetter(beans, sourceCol, 0) }; case "quarter": return { ...base, headerValueGetter: getHeaderValueGetter(beans, sourceCol, translatePart(part, "Quarter")), valueGetter: getDatePartValueGetter( beans, sourceCol, 1, (month) => (Math.floor(Number(month) / 4) + 1).toString() ) }; case "month": return { ...base, headerValueGetter: getHeaderValueGetter(beans, sourceCol, translatePart(part, "Month")), valueGetter: getDatePartValueGetter(beans, sourceCol, 1) }; case "formattedMonth": return { ...base, headerValueGetter: getHeaderValueGetter(beans, sourceCol, translatePart("month", "Month")), valueGetter: getDatePartValueGetter(beans, sourceCol, 1, (month) => { const nm = numericalMonthToNamedMonth(month); return translatePart(nm.localeKey, nm.month); }) }; case "day": return { ...base, headerValueGetter: getHeaderValueGetter(beans, sourceCol, translatePart(part, "Day")), valueGetter: getDatePartValueGetter(beans, sourceCol, 2) }; case "hour": return { ...base, headerValueGetter: getHeaderValueGetter(beans, sourceCol, translatePart(part, "Hour")), valueGetter: getDatePartValueGetter(beans, sourceCol, 3) }; case "minute": return { ...base, headerValueGetter: getHeaderValueGetter(beans, sourceCol, translatePart(part, "Minute")), valueGetter: getDatePartValueGetter(beans, sourceCol, 4) }; case "second": return { ...base, headerValueGetter: getHeaderValueGetter(beans, sourceCol, translatePart(part, "Second")), valueGetter: getDatePartValueGetter(beans, sourceCol, 5) }; default: return null; } } }; function updateMap(wm, key, value) { const existing = wm.get(key); wm.set(key, (existing ?? []).concat(value)); } // packages/ag-grid-enterprise/src/groupHierarchy/groupHierarchyModule.ts var GroupHierarchyModule = { moduleName: "GroupHierarchy", version: VERSION, beans: [GroupHierarchyColService] }; // packages/ag-grid-enterprise/src/pivot/pivotColsSvc.ts import { BaseColsService as BaseColsService2, _removeFromArray as _removeFromArray4 } from "ag-grid-community"; var PivotColsSvc = class extends BaseColsService2 { 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) => { if (!this.columns.includes(column)) { this.columns.push(column); } }, removeCol: (column) => _removeFromArray4(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; if (pivot) { const addedCols = this.beans.groupHierarchyColSvc?.insertVirtualColumnsForCol(this.columns, column); addedCols?.forEach((c) => this.setColPivotActive(c, pivot, source)); } column.dispatchColEvent("columnPivotChanged", source); } column.dispatchStateUpdatedEvent("pivot"); } }; // packages/ag-grid-enterprise/src/rowGrouping/rowGroupColsSvc.ts import { BaseColsService as BaseColsService3, _removeFromArray as _removeFromArray5, _shouldUpdateColVisibilityAfterGroup as _shouldUpdateColVisibilityAfterGroup2 } from "ag-grid-community"; var RowGroupColsSvc = class extends BaseColsService3 { 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) => { if (!this.columns.includes(column)) { this.columns.push(column); } }, removeCol: (column) => _removeFromArray5(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); const isGroupHierarchyCol = this.beans.groupHierarchyColSvc?.getColumn(column); if (_shouldUpdateColVisibilityAfterGroup2(this.gos, active) && !isGroupHierarchyCol) { this.colModel.setColsVisible([column], !active, source); } } setColRowGroupActive(column, rowGroup, source) { if (column.rowGroupActive !== rowGroup) { column.rowGroupActive = rowGroup; if (rowGroup) { const addedCols = this.beans.groupHierarchyColSvc?.insertVirtualColumnsForCol(this.columns, column); addedCols?.forEach((c) => this.setColRowGroupActive(c, rowGroup, source)); } column.dispatchColEvent("columnRowGroupChanged", source); } column.dispatchStateUpdatedEvent("rowGroup"); } }; // packages/ag-grid-enterprise/src/rowHierarchy/autoColService.ts import { AgColumn as AgColumn2, BeanStub as BeanStub28, GROUP_AUTO_COLUMN_ID, _addColumnDefaultAndTypes as _addColumnDefaultAndTypes2, _applyColumnState as _applyColumnState2, _areColIdsEqual as _areColIdsEqual2, _columnsMatch as _columnsMatch2, _convertColumnEventSourceType, _destroyColumnTree as _destroyColumnTree2, _getColumnStateFromColDef, _isColumnsSortingCoupledToGroup, _isGroupMultiAutoColumn, _isGroupUseEntireRow, _mergeDeep as _mergeDeep3, _missing as _missing3, _updateColsMap as _updateColsMap2, _warn as _warn28, isColumnGroupAutoCol } from "ag-grid-community"; var AutoColService = class extends BeanStub28 { 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); _updateColsMap2(cols); } createColumns(cols, updateOrders, source) { const beans = this.beans; const { colModel, gos, rowGroupColsSvc, colGroupSvc } = beans; const isPivotMode2 = colModel.isPivotMode(); const groupFullWidthRow = _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) { _destroyColumnTree2(beans, this.columns.tree); this.columns = null; } }; if (noAutoCols) { destroyPrevious(); return; } const list = this.generateAutoCols(rowGroupCols); const autoColsSame = _areColIdsEqual2(list, this.columns?.list || null); const newTreeDepth = cols.treeDepth; const oldTreeDepth = this.columns ? this.columns.treeDepth : -1; const treeDepthSame = oldTreeDepth == newTreeDepth; if (autoColsSame && treeDepthSame) { const colsMap = new Map(list.map((col) => [col.getId(), col])); for (const col of this.columns?.list ?? []) { const newDef = colsMap.get(col.getId()); if (newDef) { col.setColDef(newDef.getColDef(), null, source); } } 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) => !isColumnGroupAutoCol(col)); return [...list, ...colsFiltered]; }; updateOrders(putAutoColsFirstInList); } updateColumns(event) { const source = _convertColumnEventSourceType(event.source); this.columns?.list.forEach((col, index) => this.updateOneAutoCol(col, index, source)); } getColumn(key) { return this.columns?.list.find((groupCol) => _columnsMatch2(groupCol, key)) ?? null; } getColumns() { return this.columns?.list ?? null; } generateAutoCols(rowGroupCols = []) { const autoCols = []; const { gos } = this; const doingTreeData = gos.get("treeData"); let doingMultiAutoColumn = _isGroupMultiAutoColumn(gos); if (doingTreeData && doingMultiAutoColumn) { _warn28(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 = `${GROUP_AUTO_COLUMN_ID}-${rowGroupCol.getId()}`; } else { colId = GROUP_AUTO_COLUMN_ID; } const colDef = this.createAutoColDef(colId, rowGroupCol, index); colDef.colId = colId; const newCol = new AgColumn2(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); _applyColumnState2(beans, { state: [_getColumnStateFromColDef(colDef, colId)] }, source); } createAutoColDef(colId, underlyingColumn, index) { let res = this.createBaseColDef(underlyingColumn); const autoGroupColumnDef = this.gos.get("autoGroupColumnDef"); _mergeDeep3(res, autoGroupColumnDef); res = _addColumnDefaultAndTypes2(this.beans, res, colId, true); if (!this.gos.get("treeData")) { const noFieldOrValueGetter = _missing3(res.field) && _missing3(res.valueGetter) && _missing3(res.filterValueGetter) && res.filter !== "agGroupColumnFilter"; if (noFieldOrValueGetter) { res.filter = false; } } if (index && index > 0) { res.headerCheckboxSelection = false; } const isSortingCoupled = _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() { _destroyColumnTree2(this.beans, this.columns?.tree); super.destroy(); } }; // packages/ag-grid-enterprise/src/rowHierarchy/clientSideExpansionService.ts import { _exists as _exists20 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rowHierarchy/baseExpansionService.ts import { BeanStub as BeanStub29, _createGlobalRowEvent, _setAriaExpanded as _setAriaExpanded8 } from "ag-grid-community"; var BaseExpansionService = class extends BeanStub29 { 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 = { ..._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); _setAriaExpanded8(gui.element, expandable && expanded); }); } dispatchStateUpdatedEvent() { this.eventSvc.dispatchEvent({ type: "rowExpansionStateChanged" }); } }; // packages/ag-grid-enterprise/src/rowHierarchy/clientSideExpansionService.ts var ClientSideExpansionService = class extends BaseExpansionService { constructor() { super(...arguments); this.beanName = "expansionSvc"; this.events = null; this.dispatchExpandedDebounced = null; } destroy() { super.destroy(); this.events = null; this.dispatchExpandedDebounced = null; } setExpansionState(state) { const rowIdsToExpandSet = new Set(state.expandedRowGroupIds); this.beans.rowModel.forEachNode((node) => { const id = node.id; if (!id) { return; } node.expanded = rowIdsToExpandSet.has(id); }); this.onGroupExpandedOrCollapsed(); } getInternalExpansionState(allowCollapsed = false) { const expandedRowGroupIds = []; const collapsedRowGroupIds = []; this.beans.rowModel.forEachNode((node) => { const id = node.id; if (!id) { return; } if (node.expanded) { expandedRowGroupIds.push(id); } else if (allowCollapsed && node.isExpandable()) { collapsedRowGroupIds.push(id); } }); return { expandedRowGroupIds, collapsedRowGroupIds }; } getExpansionState() { return this.getInternalExpansionState(); } expandAll(expand) { const { gos, rowModel, colModel, eventSvc } = this.beans; const usingTreeData = gos.get("treeData"); const usingPivotMode = colModel.isPivotActive(); const recursiveExpandOrCollapse = (rowNodes) => { if (!rowNodes) { return; } for (const rowNode of rowNodes) { const actionRow = () => { rowNode.expanded = expand; recursiveExpandOrCollapse(rowNode.childrenAfterGroup); }; if (rowNode.master) { actionRow(); continue; } if (usingTreeData) { const hasChildren = _exists20(rowNode.childrenAfterGroup); if (hasChildren) { actionRow(); } continue; } if (usingPivotMode) { const notLeafGroup = !rowNode.leafGroup; if (notLeafGroup) { actionRow(); } continue; } const isRowGroup = rowNode.group; if (isRowGroup) { actionRow(); } } }; const rootNode = rowModel.rootNode; if (rootNode) { recursiveExpandOrCollapse(rootNode.childrenAfterGroup); } this.onGroupExpandedOrCollapsed(); eventSvc.dispatchEvent({ type: "expandOrCollapseAll", source: expand ? "expandAll" : "collapseAll" }); } onGroupExpandedOrCollapsed() { this.dispatchStateUpdatedEvent(); this.beans.rowModel.reMapRows(); } setDetailsExpansionState(detailGridApi) { const expansionState = this.getInternalExpansionState(true); const allExpanded = expansionState.collapsedRowGroupIds.length === 0; const allCollapsed = expansionState.expandedRowGroupIds.length === 0; if (allCollapsed === allExpanded) { return; } return allExpanded ? detailGridApi.expandAll() : detailGridApi.collapseAll(); } /** * 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 ?? (this.events = [])).push(event); if (forceSync) { this.dispatchExpandedEvents(); return; } let dispatch = this.dispatchExpandedDebounced; if (!dispatch) { if (!this.isAlive()) { return; } dispatch = this.debounce(() => this.dispatchExpandedEvents()); this.dispatchExpandedDebounced = dispatch; } dispatch(); } dispatchExpandedEvents() { const { eventSvc, rowRenderer } = this.beans; const eventsToDispatch = this.events; const eventsLen = eventsToDispatch?.length; if (!eventsLen) { return; } this.events = null; const rowNodes = new Array(eventsLen); for (let i = 0; i < eventsLen; ++i) { rowNodes[i] = eventsToDispatch[i].node; eventSvc.dispatchEvent(eventsToDispatch[i]); } this.dispatchStateUpdatedEvent(); rowRenderer.refreshCells({ rowNodes }); } // 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 import { BeanStub as BeanStub30 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rowHierarchy/flattenUtils.ts import { _getGrandTotalRow as _getGrandTotalRow5, _getGroupTotalRowCallback as _getGroupTotalRowCallback2, _isGroupMultiAutoColumn as _isGroupMultiAutoColumn2 } from "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: _isGroupMultiAutoColumn2(gos), hideOpenParents: gos.get("groupHideOpenParents"), grandTotalRow: _getGrandTotalRow5(gos), groupTotalRow: _getGroupTotalRowCallback2(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 BeanStub30 { constructor() { super(...arguments); this.beanName = "flattenStage"; this.step = "map"; this.refreshProps = [ "groupHideParentOfSingleChild", "groupRemoveSingleChildren", "groupRemoveLowestSingleChildren", "groupTotalRow", "masterDetail" ]; } execute() { const { beans, gos } = this; const result = []; const rootNode = beans.rowModel.rootNode; if (!rootNode) { return result; } const skipLeafNodes = beans.colModel.isPivotMode(); const showRootNode = skipLeafNodes && rootNode.leafGroup && rootNode.aggData; const topList = showRootNode ? [rootNode] : rootNode.childrenAfterSort; const details = _getFlattenDetails(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, 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/groupEditService.ts import { BeanStub as BeanStub31, ChangedPath, _ChangedRowNodes, _csrmFirstLeaf, _csrmReorderAllLeafs, _getCellByPosition, _isClientSideRowModel as _isClientSideRowModel5, _prevOrNextDisplayedRow } from "ag-grid-community"; var GroupEditService = class extends BeanStub31 { constructor() { super(...arguments); this.beanName = "groupEditSvc"; this.pendingEditRefresh = null; this.dropGroupTarget = null; this.dropGroupTimer = null; this.dropGroupThrottled = false; this.draggingGroups = null; } postConstruct() { if (_isClientSideRowModel5(this.gos)) { this.addManagedListeners(this.eventSvc, { cellValueChanged: (event) => this.onCsrmCellChange(event), batchEditingStopped: () => this.flushGroupEdits() }); } } destroy() { this.stopDragging(true); super.destroy(); } /** Checks if the drop operation described by `rowsDrop` is a grouping edit */ isGroupingDrop(rowsDrop) { if (!rowsDrop.rowDragManaged || !rowsDrop.sameGrid) { return false; } if (!this.gos.get("refreshAfterGroupEdit")) { return false; } return !!this.beans.rowGroupColsSvc?.columns?.length && !this.beans.colModel.isPivotMode(); } initDraggingGroups(rowsDrop) { const structure = /* @__PURE__ */ new Map(); const recurse = (row) => { const childrenAfterGroup = row.childrenAfterGroup; if (childrenAfterGroup) { if (structure.has(row)) { return; } const children = childrenAfterGroup.slice(); structure.set(row, children); for (const child of children) { recurse(child); } } }; for (const row of rowsDrop.rows) { if (row.group) { recurse(row); } } this.draggingGroups = structure; } /** Checks if the drop operation described by `rowsDrop` can set a new parent */ canSetParent(rowsDrop) { if (!rowsDrop.sameGrid) { return false; } if (this.beans.groupStage?.treeData) { return true; } if (rowsDrop.rowDragManaged && !this.gos.get("refreshAfterGroupEdit")) { return false; } return !!this.beans.rowGroupColsSvc?.columns?.length; } canDropRow(rowNode, rowsDrop) { if (this.beans.groupStage?.treeData) { return !wouldCycle(rowNode, rowsDrop.newParent); } const { position, target, newParent, rootNode } = rowsDrop; const currentParent = rowNode.parent; if (rowNode.group && (isAncestorOrSelf(rowNode, target) || isAncestorOrSelf(rowNode, newParent))) { return false; } if (position === "inside") { return true; } if (newParent && newParent !== currentParent) { return newParent !== rootNode || currentParent === rootNode; } const comparisonParent = newParent ?? target?.parent ?? rootNode; if (comparisonParent !== currentParent) { return false; } const sourceLevel = rowNode.group ? rowNode.level : currentParent.level ?? -1; let targetLevel = -1; if (target) { targetLevel = target.group ? target.level : target.parent?.level ?? -1; } else if (comparisonParent) { targetLevel = comparisonParent.level; } if (sourceLevel >= 0 && targetLevel >= 0 && targetLevel !== sourceLevel) { return false; } return true; } fixRowsDrop(rowsDrop, canSetParent, fromNudge, yDelta) { const treeData = !!this.beans.groupStage?.treeData; rowsDrop.treeData = treeData; const isRowGrouping = !!this.beans.rowGroupColsSvc?.columns?.length || this.gos.get("pivotMode"); if (!isRowGrouping && !treeData) { return; } if (!this.draggingGroups && this.isGroupingDrop(rowsDrop) && !rowsDrop.suppressMoveWhenRowDragging) { this.initDraggingGroups(rowsDrop); } let target = rowsDrop.target; let newParent = null; let inside = false; const rootNode = rowsDrop.rootNode; const rowModel = this.beans.rowModel; const canStartGroup = this.canStartGroup(target, treeData); this.updateDropTarget(rowsDrop, fromNudge, canStartGroup); const lastRowIndex = this.beans.pageBounds?.getLastRow?.() ?? rowModel.getRowCount() - 1; if (canSetParent) { if (!target || yDelta >= 0.5 && target.rowIndex === lastRowIndex) { newParent = rootNode; } else if (rowsDrop.moved && target && this.dropGroupThrottled && this.shouldDropTargetBeParent(rowsDrop)) { newParent = target; } if (!newParent) { newParent = target?.parent ?? rootNode; } } if (!fromNudge && target && canStartGroup && !(target.group && target.expanded)) { this.startDropGroupDelay(target); } if (newParent) { if (target && newParent === target && newParent !== rootNode) { const firstRow = newParent.expanded ? _prevOrNextDisplayedRow(rowModel, 1, target) : null; if (firstRow?.parent === newParent) { target = firstRow; yDelta = -0.5; } else { inside = true; } } if (target && !inside) { let current = target; while (current && current !== rootNode && current !== newParent) { target = current; current = current.parent; } } } rowsDrop.target = target; rowsDrop.newParent = newParent; rowsDrop.yDelta = yDelta; rowsDrop.inside = inside; } clearNewSameParent(rowsDrop, canSetParent) { const newParent = rowsDrop.newParent; if (newParent && (!canSetParent || rowsHaveSameParent(rowsDrop.rows, newParent))) { rowsDrop.newParent = null; } } updateDropTarget(rowsDrop, fromNudge, canStartGroup) { const target = canStartGroup ? rowsDrop.target : null; if (this.dropGroupTarget && this.dropGroupTarget !== target) { this.resetDragGroup(); } if (!target?.childrenAfterSort?.length) { return; } if (fromNudge && this.dropGroupThrottled && !target.expanded && target.isExpandable?.()) { target.setExpanded(true, void 0, true); } if (this.canDropInTarget(target, rowsDrop)) { this.dropGroupThrottled = true; this.dropGroupTarget = target; } } canDropInTarget(target, rowsDrop) { if (target.expanded) { return true; } if (!target.group) { return false; } if (rowsDrop.pointerPos === "inside") { return true; } if (rowsDrop.treeData) { return false; } const rows = rowsDrop.rows; const targetLevel = target.level; for (let i = 0, len = rows.length; i < len; ++i) { const row = rows[i]; if (row !== target && row.group && row.level !== targetLevel) { return false; } } return true; } startDropGroupDelay(target) { if (this.dropGroupTarget && this.dropGroupTarget !== target) { this.resetDragGroup(); } this.dropGroupTarget = target; if (this.dropGroupTimer !== null) { return; } const delay = this.gos.get("rowDragInsertDelay"); this.dropGroupTimer = window.setTimeout(() => { this.dropGroupTimer = null; this.dropGroupThrottled = true; this.beans.dragAndDrop?.nudge(); }, delay); } resetDragGroup() { if (this.dropGroupTimer !== null) { window.clearTimeout(this.dropGroupTimer); this.dropGroupTimer = null; } this.dropGroupTarget = null; this.dropGroupThrottled = false; } stopDragging(final) { if (final) { this.draggingGroups = null; } this.resetDragGroup(); } shouldDropTargetBeParent({ target, rows, pointerPos, treeData }) { if (!target || pointerPos === "none") { return false; } if (pointerPos === "inside") { return true; } if (!treeData && target.group && !target.expanded) { return true; } if (pointerPos === "above") { return false; } const rowModel = this.beans.rowModel; const targetRowIndex = target.rowIndex; let nextRowIndex = targetRowIndex + 1; let nextRow; do { nextRow = rowModel.getRow(nextRowIndex++); } while (nextRow?.footer); const childrenAfterGroup = this.draggingGroups?.get(target) ?? target.childrenAfterGroup; if (nextRow && nextRow.parent === target && childrenAfterGroup?.length) { const rowsSet = new Set(rows); for (let i = 0, len = childrenAfterGroup.length; i < len; ++i) { const child = childrenAfterGroup[i]; if (child.rowIndex !== null && !rowsSet.has(child)) { return true; } } } return false; } /** Performs the grouping edit described by `rowsDrop` */ dropGroupEdit(rowsDrop) { const { beans } = this; const position = rowsDrop.position; const target = rowsDrop.target ?? null; const rootNode = rowsDrop.rootNode; const parentForValues = rowsDrop.newParent ?? target?.parent ?? rootNode; const focusSvc = beans.focusSvc; const cellPosition = focusSvc.getFocusedCell(); const cellCtrl = cellPosition && _getCellByPosition(beans, cellPosition); const leafs = /* @__PURE__ */ new Set(); const changedRowNodes = new _ChangedRowNodes(); const updates = changedRowNodes.updates; let newGroupValues; const processLeaf = (leafRow) => { if (leafs.has(leafRow)) { return; } leafs.add(leafRow); newGroupValues ?? (newGroupValues = this.newGroupValues(parentForValues)); if (this.setRowGroup(leafRow, newGroupValues)) { updates.add(leafRow); } }; const visitGroupedChildren = (groupNode) => { const children = this.draggingGroups?.get(groupNode) ?? groupNode.childrenAfterGroup; const childrenLen = children?.length; if (childrenLen) { for (let i = 0; i < childrenLen; ++i) { const child = children[i]; if (child.sourceRowIndex >= 0) { processLeaf(child); } else { visitGroupedChildren(child); } } } }; for (const row of rowsDrop.rows) { if (row.group) { visitGroupedChildren(row); } else { const firstLeaf = row.sourceRowIndex >= 0 && !row.destroyed ? row : this.csrmFirstLeaf(row); if (firstLeaf) { processLeaf(firstLeaf); } } } const reorderPosition = position === "inside" ? "above" : position; const reorderTarget = position === "inside" ? this.findFirstLeafForParent(parentForValues, leafs) ?? target : target; let orderChanged = false; if (leafs.size && reorderPosition !== "none") { orderChanged = _csrmReorderAllLeafs(rootNode._leafs, leafs, reorderTarget, reorderPosition === "above"); } if (!updates.size && !orderChanged) { return false; } changedRowNodes.reordered = orderChanged; for (const leaf of leafs) { changedRowNodes.updates.add(leaf); } this.csrmRefresh(changedRowNodes); if (cellCtrl) { cellCtrl.focusCell(); } else { focusSvc.clearFocusedCell(); } return true; } canStartGroup(target, treeData) { if (!target || target.level < 0 || target.footer || target.detail) { return false; } if (target.group) { return true; } return treeData; } /** Flushes any pending group edits for batch processing */ flushGroupEdits() { const pending = this.pendingEditRefresh; if (pending) { this.pendingEditRefresh = null; this.csrmRefresh(pending); } } /** Refreshes the grouping for the provided rows */ csrmRefresh(changedRowNodes) { const clientSideRowModel = this.beans.rowModel; const rootNode = clientSideRowModel.rootNode; if (!rootNode) { return; } clientSideRowModel.refreshModel({ step: "group", keepRenderedRows: true, animate: !this.gos.get("suppressAnimationFrame"), changedPath: new ChangedPath(false, rootNode), changedRowNodes }); } newGroupValues(parent) { const columns = this.beans.rowGroupColsSvc?.columns ?? []; const values = new Array(columns.length); let maxLevel = -1; let current = parent; while (current && current.level >= 0) { const column = columns[current.level]; if (column) { const colId = column.getColId(); const level = current.level; values[level] = current.groupData?.[colId] ?? current.key ?? void 0; if (level > maxLevel) { maxLevel = level; } } current = current.parent; } return { values, columns, maxLevel }; } setRowGroup(row, { values, columns, maxLevel }) { if (maxLevel < 0) { return false; } const { valueSvc } = this.beans; let changed = false; for (let level = 0; level < columns.length; ++level) { const column = columns[level]; if (!column || level > maxLevel) { continue; } const newValue = values[level]; const currentValue = valueSvc.getValue(column, row, "data"); if (currentValue === newValue || currentValue == null && newValue == null) { continue; } let valueToSet = newValue; const parsedValue = valueSvc.parseValue(column, row, newValue, currentValue); if (parsedValue !== void 0) { valueToSet = parsedValue; } const updated = row.setDataValue(column, valueToSet, "rowDrag"); if (updated) { changed = true; } } return changed; } onCsrmCellChange(event) { const { column, node, source } = event; if (!this.gos.get("refreshAfterGroupEdit")) { return; } if (source === "rowDrag") { return; } if (!column?.isRowGroupActive()) { return; } if (node.group || !node.data) { return; } const editSvc = this.beans.editSvc; if (editSvc?.isBatchEditing()) { let pending = this.pendingEditRefresh; if (!pending) { pending = newEditChangedRowNodes(); this.pendingEditRefresh = pending; } pending.updates.add(node); } else { const changedRowNodes = newEditChangedRowNodes(); changedRowNodes.updates.add(node); this.csrmRefresh(changedRowNodes); } } csrmFirstLeaf(parent) { if (!parent) { return null; } const draggingGroups = this.draggingGroups; let children = draggingGroups?.get(parent) ?? parent.childrenAfterGroup; while (children?.length) { const child = children[0]; if (child.sourceRowIndex >= 0) { if (!child.destroyed) { return child; } return this.firstAliveChildLeaf(child); } children = draggingGroups?.get(child) ?? child.childrenAfterGroup; } return _csrmFirstLeaf(parent); } firstAliveChildLeaf(parent) { const children = this.draggingGroups?.get(parent) ?? parent.childrenAfterGroup; if (children) { for (const grandChild of children) { if (grandChild.sourceRowIndex >= 0 && !grandChild.destroyed) { return grandChild; } } } return null; } findFirstLeafForParent(parent, exclude) { if (!parent) { return null; } const children = this.draggingGroups?.get(parent) ?? parent?.childrenAfterGroup; if (!children) { return null; } for (let i = 0, len = children.length; i < len; ++i) { const child = children[i]; if (child.sourceRowIndex >= 0 && !exclude.has(child)) { return child; } const found = this.findFirstLeafForParent(child, exclude); if (found !== null) { return found; } } return null; } }; var newEditChangedRowNodes = () => { const result = new _ChangedRowNodes(); result.reordered = true; return result; }; var isAncestorOrSelf = (candidate, node) => { if (!candidate || !node) { return false; } let current = node; while (current) { if (current === candidate) { return true; } current = current.parent; } return false; }; var wouldCycle = (row, newParent) => { if (!newParent || row.parent === newParent) { return false; } let current = newParent; const rowId = row.id; while (current) { if (current === row) { return true; } if (rowId != null && current.id === rowId) { return true; } current = current.parent; } return false; }; var rowsHaveSameParent = (rows, newParent) => { for (let i = 0, len = rows.length; i < len; ++i) { if (rows[i].parent !== newParent) { return false; } } return true; }; // packages/ag-grid-enterprise/src/rowHierarchy/groupStage.ts import { BeanStub as BeanStub32 } from "ag-grid-community"; var GroupStage = class extends BeanStub32 { constructor() { super(...arguments); this.beanName = "groupStage"; this.step = "group"; this.refreshProps = [ "groupAllowUnbalanced", "groupDefaultExpanded", "groupDisplayType", "groupHideOpenParents", "initialGroupOrderComparator", "treeData", "treeDataChildrenField", "treeDataParentIdField" ]; this.treeData = false; this.hasTreeData = false; this.needReset = false; this.nested = false; this.strategy = void 0; } postConstruct() { const gos = this.gos; if (gos.isModuleRegistered("TreeData")) { this.hasTreeData = true; this.treeData = gos.get("treeData"); } this.addManagedEventListeners({ showRowGroupColsSetChanged: () => this.strategy?.onShowRowGroupColsSetChanged() }); } invalidateGroupCols() { this.strategy?.invalidateGroupCols?.(); } destroy() { this.strategy = this.destroyBean(this.strategy); super.destroy(); } getNonLeaf(id) { return this.strategy?.nonLeafsById?.get(id); } getNestedDataGetter() { return this.getStrategy()?.nestedDataGetter; } onPropChange(changedProps) { const gos = this.gos; const oldNestedDataGetter = this.strategy?.nestedDataGetter; if (changedProps.has("treeData")) { const value = gos.get("treeData") && this.hasTreeData; if (this.treeData !== value) { this.beans.rowDragSvc?.cancelRowDrag(); this.treeData = value; this.needReset = true; this.strategy = this.destroyBean(this.strategy); } } this.strategy?.onPropChange?.(changedProps); return this.getNestedDataGetter() !== oldNestedDataGetter; } extractData() { const rootNode = this.beans.rowModel.rootNode; const nodes = this.nested ? rootNode?.childrenAfterGroup : rootNode?._leafs; if (!nodes) { return this.gos.get("rowData") ?? []; } const len = nodes.length; const result = new Array(len); let writeIdx = 0; for (let i = 0; i < len; ++i) { const data = nodes[i].data; if (data != null) { result[writeIdx++] = data; } } result.length = writeIdx; return result; } execute(params) { const beans = this.beans; const rootNode = beans.rowModel.rootNode; if (!rootNode) { return false; } const strategy = this.getStrategy(); const nested = !!strategy?.nestedDataGetter; const needReset = this.needReset; this.nested = nested; if (needReset) { this.needReset = false; beans.rowDragSvc?.cancelRowDrag(); params.animate = false; resetGrouping(rootNode, !nested); } return strategy ? strategy.execute(rootNode, params) || needReset : void 0; } loadLeafs(node) { return node.footer ? loadFooterLeafs(node) : loadRealLeafs(node); } loadGroupData(node) { const strategy = this.getStrategy(); if (strategy) { return strategy.loadGroupData(node); } node._groupData = null; return null; } clearNonLeafs() { this.strategy?.clearNonLeafs(); } getStrategy() { let strategy = this.strategy; if (strategy !== void 0 && this.isAlive()) { return strategy; } strategy = this.beans.registry.createDynamicBean(this.treeData ? "treeGroupStrategy" : "groupStrategy", false) ?? null; this.strategy = strategy && this.createBean(strategy); return strategy; } }; var loadFooterLeafs = (node) => { const sibling = node.sibling; if (!sibling) { return null; } const siblingLeafs = sibling._leafs; if (siblingLeafs !== void 0) { return siblingLeafs; } return loadRealLeafs(sibling); }; var loadRealLeafs = (node) => { const childrenAfterGroup = node.childrenAfterGroup; const childrenAfterGroupLen = childrenAfterGroup?.length; node._leafs = null; if (!childrenAfterGroupLen) { return null; } let leafs; const onlyChild = childrenAfterGroupLen === 1 ? childrenAfterGroup[0] : null; if (onlyChild?.group && onlyChild.sourceRowIndex < 0) { leafs = onlyChild._leafs; if (leafs === void 0) { leafs = loadRealLeafs(onlyChild); } } else if (node.leafGroup) { leafs = childrenAfterGroup; } else { leafs = []; for (let i = 0; i < childrenAfterGroupLen; ++i) { const child = childrenAfterGroup[i]; if (child.sourceRowIndex >= 0) { leafs.push(child); } if (!child.group) { continue; } let childLeafs = child._leafs; if (childLeafs === void 0) { childLeafs = loadRealLeafs(child); } if (childLeafs) { for (let j = 0, len = childLeafs.length; j < len; ++j) { leafs.push(childLeafs[j]); } } } } node._leafs = leafs; return leafs; }; var resetGrouping = (rootNode, canResetTreeNode) => { const allLeafs = rootNode._leafs; const rootSibling = rootNode.sibling; rootNode.treeNodeFlags = 0; rootNode.childrenAfterGroup = allLeafs; rootNode.childrenMapped = null; rootNode._groupData = void 0; if (rootSibling) { rootSibling.childrenAfterGroup = rootNode.childrenAfterGroup; rootSibling.childrenAfterAggFilter = rootNode.childrenAfterAggFilter; rootSibling.childrenAfterFilter = rootNode.childrenAfterFilter; rootSibling.childrenAfterSort = rootNode.childrenAfterSort; rootSibling.childrenMapped = null; rootSibling._groupData = void 0; } for (let i = 0, allLeafsLen = allLeafs.length ?? 0; i < allLeafsLen; ++i) { const row = allLeafs[i]; const sibling = row.sibling; row._leafs = void 0; resetChildRowGrouping(row); if (sibling) { resetChildRowGrouping(sibling); } row.parent = rootNode; if (canResetTreeNode) { row.treeParent = null; } row.group = false; row.updateHasChildren(); } rootNode.updateHasChildren(); }; var resetChildRowGrouping = (row) => { row.key = null; row.treeNodeFlags = 0; row.allChildrenCount = null; row.childrenAfterGroup = null; row.childrenAfterAggFilter = null; row.childrenAfterFilter = null; row.childrenAfterSort = null; row.childrenMapped = null; row.level = 0; row._groupData = void 0; }; // packages/ag-grid-enterprise/src/rowHierarchy/rendering/groupCellRenderer.ts import { Component as Component37, RefPlaceholder as RefPlaceholder34, _setAriaRole as _setAriaRole9, _setDisplayed as _setDisplayed18 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rowHierarchy/rendering/groupCellRendererCtrl.ts import { BeanStub as BeanStub33, KeyCode as KeyCode28, _createIconNoSpan as _createIconNoSpan19, _getCellRendererDetails as _getCellRendererDetails2, _getCheckboxLocation, _getCheckboxes, _getInnerCellRendererDetails, _isElementInEventPath, _isRowSelection, _isStopPropagationForAgGrid as _isStopPropagationForAgGrid2, _removeAriaExpanded as _removeAriaExpanded2, _setAriaExpanded as _setAriaExpanded9, _stopPropagationForAgGrid as _stopPropagationForAgGrid8 } from "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 BeanStub33 { 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 = _createIconNoSpan19(iconName, this.beans, null); if (icon) { element.appendChild(icon); this.addDestroyFunc(() => icon.remove()); } }; 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); _setAriaExpanded9(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); _removeAriaExpanded2(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 = _getInnerCellRendererDetails( userCompFactory, groupRowRendererParams, params ); if (groupRowInnerCompDetails) { return groupRowInnerCompDetails; } if (findSvc?.isMatch(params.node, null)) { return _getInnerCellRendererDetails( userCompFactory, { ...groupRowRendererParams, innerRenderer: "agFindCellRenderer" }, params ); } return void 0; } const isGroupRowRenderer = (details) => details && details.componentClass == this.compClass; const innerCompDetails = _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 = _getCellRendererDetails2(userCompFactory, relatedColDef, params); if (relatedCompDetails) { if (isGroupRowRenderer(relatedCompDetails)) { if (relatedColDef?.cellRendererParams?.innerRenderer) { return _getInnerCellRendererDetails( userCompFactory, relatedColDef.cellRendererParams, params ); } } else { return relatedCompDetails; } } } if (findSvc?.isMatch(params.node, params.column)) { return _getCellRendererDetails2( 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 = node.uiLevel; if (colDef && colDef.showRowGroup !== true) { level = 0; } 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 || !_isRowSelection(this.gos)) { return; } const { node, column } = this.params; const rowSelection = this.gos.get("rowSelection"); const checkboxLocation = _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" ? _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?.getGui().remove(); this.cbComp = this.destroyBean(this.cbComp); } /** * Called when the expand / contract icon is clicked. */ onExpandClicked(mouseEvent) { if (_isStopPropagationForAgGrid2(mouseEvent)) { return; } _stopPropagationForAgGrid8(mouseEvent); this.onExpandOrContract(mouseEvent); } /** * Called on cell key press - only handles 'Enter' key for expand/collapse */ onKeyDown(event) { const isEnterKey = event.key === KeyCode28.ENTER; if (!isEnterKey || this.params.suppressEnterExpand) { return; } const cellEditable = 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 (_isStopPropagationForAgGrid2(mouseEvent)) { return; } const targetIsExpandIcon = _isElementInEventPath(this.eExpanded, mouseEvent) || _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 Component37 { constructor() { super(GroupCellRendererElement); this.eExpanded = RefPlaceholder34; this.eContracted = RefPlaceholder34; this.eCheckbox = RefPlaceholder34; this.eValue = RefPlaceholder34; this.eChildCount = RefPlaceholder34; } 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) => _setDisplayed18(this.eContracted, expanded), setExpandedDisplayed: (expanded) => _setDisplayed18(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) { _setAriaRole9(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 import { BeanStub as BeanStub34 } from "ag-grid-community"; var ShowRowGroupColValueService = class extends BeanStub34 { constructor() { super(...arguments); this.beanName = "showRowGroupColValueSvc"; } /** * Get the value for display in the group column. Also returns the displayedNode from which the value was * taken in cases of groupHideOpenParents and showOpenedGroup. * * Always uses 'data' mode because group column values represent structural position in the row hierarchy. * The actual grouping (via getKeyForNode) uses committed data, so the display should match - showing * a different group value while the row is still in its original group would be misleading. */ getGroupValue(node, column, ignoreAggData) { 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, "data", ignoreAggData) }; } } const value = valueSvc.getValue(column, node, "data", ignoreAggData); if (value == null) { const displayedNode = this.getDisplayedNode(node, column); if (displayedNode) { return { displayedNode, value: valueSvc.getValue(column, displayedNode, "data", ignoreAggData) }; } } 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 import { BeanStub as BeanStub35 } from "ag-grid-community"; var ShowRowGroupColsService = class extends BeanStub35 { constructor() { super(...arguments); this.beanName = "showRowGroupCols"; this.columns = []; this.colsSet = /* @__PURE__ */ new Set(); this.colsMap = /* @__PURE__ */ new Map(); } destroy() { super.destroy(); this.columns.length = 0; this.colsSet.clear(); this.colsMap.clear(); } refresh() { const { colModel, rowGroupColsSvc } = this.beans; const showRowGroupCols = this.columns; const showRowGroupColsSet = this.colsSet; const showRowGroupColsMap = this.colsMap; showRowGroupColsMap.clear(); const oldShowRowGroupColsLLen = showRowGroupCols.length; let showRowGroupColsCount = 0; let showRowGroupColsSetChanged = false; const cols = colModel.getCols(); for (let colIdx = 0, colsLen = cols.length; colIdx < colsLen; ++colIdx) { const col = cols[colIdx]; const colDef = col.getColDef(); const showRowGroup = colDef.showRowGroup; if (typeof showRowGroup === "string") { showRowGroupColsMap.set(showRowGroup, col); } else if (showRowGroup === true) { const groupColumns = rowGroupColsSvc?.columns; if (groupColumns) { for (let grpColIdx = 0, grpColsLen = groupColumns.length; grpColIdx < grpColsLen; ++grpColIdx) { showRowGroupColsMap.set(groupColumns[grpColIdx].getId(), col); } } } else { continue; } showRowGroupColsSetChanged || (showRowGroupColsSetChanged = showRowGroupColsCount >= oldShowRowGroupColsLLen || !showRowGroupColsSet.has(col)); showRowGroupCols[showRowGroupColsCount++] = col; } showRowGroupColsSetChanged || (showRowGroupColsSetChanged = showRowGroupColsCount !== oldShowRowGroupColsLLen); if (showRowGroupColsSetChanged) { showRowGroupCols.length = showRowGroupColsCount; showRowGroupColsSet.clear(); for (let j = 0; j < showRowGroupColsCount; ++j) { showRowGroupColsSet.add(showRowGroupCols[j]); } this.eventSvc.dispatchEvent({ type: "showRowGroupColsSetChanged" }); } } getShowRowGroupCol(id) { return this.colsMap.get(id); } getSourceColumnsForGroupColumn(groupCol) { const sourceColumnId = groupCol.getColDef().showRowGroup; if (!sourceColumnId) { return null; } const { rowGroupColsSvc, colModel } = this.beans; if (sourceColumnId === true && rowGroupColsSvc) { return rowGroupColsSvc.columns; } const column = colModel.getColDefCol(sourceColumnId); return column ? [column] : null; } isRowGroupDisplayed(column, colId) { const showRowGroup = column.getColDef()?.showRowGroup; return showRowGroup === true || showRowGroup != null && showRowGroup === colId; } }; // packages/ag-grid-enterprise/src/rowHierarchy/stickyRowService.ts import { BeanStub as BeanStub37, _isClientSideRowModel as _isClientSideRowModel7, _isGroupRowsSticky as _isGroupRowsSticky2, _isServerSideRowModel as _isServerSideRowModel2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rowHierarchy/stickyRowFeature.ts import { BeanStub as BeanStub36, _getRowHeightForNode, _isClientSideRowModel as _isClientSideRowModel6, _isGroupRowsSticky, _last as _last10 } from "ag-grid-community"; var StickyRowFeature = class extends BeanStub36 { 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 = _isClientSideRowModel6(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 newStickyRows = /* @__PURE__ */ new Set(); const { rowModel, rowRenderer, pinnedRowModel, pageBounds, rowContainerHeight } = this.beans; const { pageFirstPixel, pageLastPixel } = pageBounds.getCurrentPagePixelRange(); const pixelAtContainerBoundary = isTop ? rowRenderer.firstVisibleVPixel - this.extraTopHeight : rowRenderer.lastVisibleVPixel - this.extraTopHeight; const divStretchOffset = rowContainerHeight.divStretchOffset ?? 0; const pageFirstPixelWithOffset = pageFirstPixel + divStretchOffset; const pageLastPixelWithOffset = pageLastPixel + divStretchOffset; 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; } if (isTop && firstPixelAfterStickyRows < pageFirstPixelWithOffset) { firstPixelAfterStickyRows = pageFirstPixelWithOffset; } else if (!isTop && firstPixelAfterStickyRows > pageLastPixelWithOffset) { firstPixelAfterStickyRows = pageLastPixelWithOffset; } 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 = _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(); } for (const ctrl of newCtrlsList) { ctrl.setRowTop(ctrl.rowNode.stickyRowTop); } const pageBounds = this.beans.pageBounds; let extraHeight = 0; if (isTop) { for (const node of newStickyNodes) { if (node.rowIndex < pageBounds.getFirstRow()) { extraHeight += node.rowHeight; } } if (extraHeight > this.topContainerHeight) { extraHeight = this.topContainerHeight; } this.setOffsetTop(extraHeight); } else { for (const node of newStickyNodes) { 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 = _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 = _last10(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 BeanStub37 { constructor() { super(...arguments); this.beanName = "stickyRowSvc"; } createStickyRowFeature(ctrl, createRowCon, destroyRowCtrls) { const gos = this.gos; if (_isGroupRowsSticky2(gos) && _isClientSideRowModel7(gos) || _isServerSideRowModel2(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] }; var GroupEditModule = { moduleName: "GroupEdit", version: VERSION, beans: [GroupEditService], dependsOn: [EnterpriseCoreModule, ClientSideRowModelHierarchyModule] }; // packages/ag-grid-enterprise/src/rowGrouping/columnDropZones/agGridHeaderDropZones.ts import { Component as Component38, _createElement as _createElement11 } from "ag-grid-community"; var AgGridHeaderDropZones = class extends Component38 { 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 = _createElement11({ 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 import { AgPromise as AgPromise11, AgSelect, FilterComp as FilterComp2, RefPlaceholder as RefPlaceholder35, TabGuardComp as TabGuardComp3, _clearElement as _clearElement12, _createElement as _createElement12, _setDisplayed as _setDisplayed19, _warn as _warn29 } from "ag-grid-community"; function processGroupFilterParams(params) { if (params.buttons) { params.buttons = []; } return params; } var GroupFilterElement = { tag: "div", cls: "ag-group-filter", children: [ { tag: "div", ref: "eGroupField" }, { tag: "div", ref: "eUnderlyingFilter" } ] }; var GroupFilter = class extends TabGuardComp3 { constructor() { super(GroupFilterElement); this.filterType = "group"; this.eGroupField = RefPlaceholder35; this.eUnderlyingFilter = RefPlaceholder35; } 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) { _warn29(234); } if (colDef.filterValueGetter) { _warn29(235); } if (colDef.filterParams) { _warn29(236); } } addHandlerListeners(listener) { const destroyFunctions = this.addManagedListeners(this.getHandler(), { sourceColumnsChanged: () => { this.updateGroups(); }, destroyed: () => { for (const func of destroyFunctions) { 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; _clearElement12(eGroupField); if (this.eGroupFieldSelect) { this.destroyBean(this.eGroupFieldSelect); } if (hasMultipleColumns && sourceColumns) { this.createGroupFieldSelectElement(sourceColumns, selectedColumn); eGroupField.appendChild(this.eGroupFieldSelect.getGui()); eGroupField.appendChild(_createElement12({ tag: "div", cls: "ag-filter-separator" })); } _setDisplayed19(eGroupField, hasMultipleColumns); return { sourceColumns, selectedColumn }; } createGroupFieldSelectElement(sourceColumns, selectedColumn) { const eGroupFieldSelect = this.createManagedBean(new 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 AgPromise11.resolve(); } const filterPromises = []; const filterColumnPairs = []; const colFilter = this.beans.colFilter; for (const column of sourceColumns) { 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 AgPromise11.all(filterPromises).then(() => { this.filterColumnPairs = filterColumnPairs; }); } addUnderlyingFilterElement(selectedColumn) { _clearElement12(this.eUnderlyingFilter); if (!selectedColumn) { return AgPromise11.resolve(); } const comp = this.createManagedBean(new FilterComp2(selectedColumn, "COLUMN_MENU")); this.filterComp = comp; if (!comp.hasFilter()) { return AgPromise11.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(); } }) ?? AgPromise11.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() { _clearElement12(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 import { BeanStub as BeanStub38, _warn as _warn30 } from "ag-grid-community"; var GroupFilterHandler = class extends BeanStub38 { 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")) { _warn30(237); return []; } const sourceColumns = this.beans.groupFilter.getSourceColumns(groupColumn); if (!sourceColumns) { _warn30(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 import { BeanStub as BeanStub39 } from "ag-grid-community"; var GroupFilterService = class extends BeanStub39 { 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 import { AgInputTextField as AgInputTextField3, AgPromise as AgPromise12, Component as Component39, RefPlaceholder as RefPlaceholder36, _clearElement as _clearElement13, _isGroupMultiAutoColumn as _isGroupMultiAutoColumn3 } from "ag-grid-community"; var GroupFloatingFilterElement = { tag: "div", ref: "eFloatingFilter", cls: "ag-group-floating-filter ag-floating-filter-input", role: "presentation" }; var GroupFloatingFilterComp = class extends Component39 { constructor() { super(GroupFloatingFilterElement); this.eFloatingFilter = RefPlaceholder36; this.haveAddedColumnListeners = false; } init(params) { this.params = params; const canShowUnderlyingFloatingFilter = _isGroupMultiAutoColumn3(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 AgPromise12((resolve) => setupFilterElement(resolve)).then(() => { this.addHandlerListeners(params, onColChange); }); } else { return new AgPromise12((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: () => { for (const func of destroyFunctions) { func(); } this.addHandlerListeners(this.params, listener); } }); } setupReadOnlyFloatingFilterElement() { if (!this.eFloatingFilterText) { this.eFloatingFilterText = this.createManagedBean(new AgInputTextField3()); 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; _clearElement13(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 AgPromise12.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 import { BeanStub as BeanStub40, RowNode, _csrmFirstLeaf as _csrmFirstLeaf2, _warn as _warn31 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rowGrouping/groupStrategy/groupColumns.ts var makeGroupColumns = (columns, result) => { if (!columns) { result.length = 0; return; } const len = columns.length; result.length = 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 }; } }; 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 BeanStub40 { 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.groupCols = []; this.nonLeafsById = /* @__PURE__ */ new Map(); this.checkGroupCols = true; this.pivotMode = false; this.groupEmpty = false; } invalidateGroupCols() { this.checkGroupCols = true; } destroy() { super.destroy(); this.groupCols.length = 0; this.nonLeafsById.clear(); } clearNonLeafs() { const nonLeafsById = this.nonLeafsById; for (const node of nonLeafsById.values()) { node._destroy(false); } nonLeafsById.clear(); } loadGroupData(node) { if (!node.group) { node._groupData = null; return null; } const rowGroupCol = node.rowGroupColumn; const { valueSvc, showRowGroupCols } = this.beans; const groupData = {}; node._groupData = groupData; if (!rowGroupCol) { return groupData; } const leafNode = _csrmFirstLeaf2(node); const rowGroupColId = rowGroupCol.getId(); if (!showRowGroupCols) { return groupData; } const groupDisplayCols = showRowGroupCols.columns; for (let i = 0, len = groupDisplayCols.length; i < len; ++i) { const col = groupDisplayCols[i]; if (col.isRowGroupDisplayed(rowGroupColId)) { groupData[col.getColId()] = valueSvc.getValue(rowGroupCol, leafNode, "data"); } } return groupData; } execute(rootNode, params) { const changedPath = params.changedPath; if (this.initRefresh(params)) { const changedRowNodes = params.changedRowNodes; if (changedRowNodes) { this.handleDeltaUpdate(rootNode, changedPath, changedRowNodes, !!params.animate); } else { this.shotgunResetEverything(rootNode); } } this.positionLeafsAndGroups(changedPath); this.orderGroups(rootNode); this.beans.selectionSvc?.updateSelectableAfterGrouping(changedPath); } positionLeafsAndGroups(changedPath) { changedPath.forEachChangedNodeDepthFirst((group) => { const children = group.childrenAfterGroup; const childrenLen = children?.length; if (!childrenLen) { return; } const newChildren = new Array(childrenLen); let writeIdx = 0; let changed = false; let unbalancedNode; for (let readIdx = 0; readIdx < childrenLen; ++readIdx) { const node = children[readIdx]; if (!node.childrenAfterGroup?.length) { changed || (changed = writeIdx !== readIdx); newChildren[writeIdx++] = node; } else if (!unbalancedNode && node.key === "") { unbalancedNode = node; const last = childrenLen - 1; changed || (changed = readIdx !== last); newChildren[last] = node; } } if (changed) { for (let readIdx = 0; readIdx < childrenLen; ++readIdx) { const node = children[readIdx]; if (node.childrenAfterGroup?.length && node !== unbalancedNode) { newChildren[writeIdx++] = node; } } group.childrenAfterGroup = newChildren; const sibling = group.sibling; if (sibling) { sibling.childrenAfterGroup = newChildren; } } }, false); } initRefresh(params) { const { rowGroupColsSvc, colModel, gos } = this.beans; const pivotMode = colModel.isPivotMode(); this.pivotMode = pivotMode; this.groupEmpty = pivotMode || !gos.get("groupAllowUnbalanced"); const cols = rowGroupColsSvc?.columns; const groupCols = this.groupCols; const afterColumnsChanged = params.afterColumnsChanged; if (afterColumnsChanged || !groupCols || this.checkGroupCols) { this.checkGroupCols = false; if (groupCols && !groupColumnsChanged(groupCols, cols)) { if (afterColumnsChanged) { return false; } } else { params.animate = false; makeGroupColumns(cols, this.groupCols); } } return true; } handleDeltaUpdate(rootNode, changedPath, { removals, updates, adds, reordered }, animate) { const parentsWithRemovals = /* @__PURE__ */ new Set(); let activeChangedPath = changedPath; if (!activeChangedPath.active) { activeChangedPath = null; } for (let i = 0, len = removals.length; i < len; ++i) { const rowNode = removals[i]; const oldParent = this.removeFromParent(rowNode); if (!parentsWithRemovals.has(oldParent)) { parentsWithRemovals.add(oldParent); activeChangedPath?.addParentNode(oldParent); } } for (const rowNode of updates) { const oldParent = rowNode.parent; activeChangedPath?.addParentNode(oldParent); if (this.moveNodeInWrongPath(rootNode, rowNode)) { parentsWithRemovals.add(oldParent); const newParent = rowNode.parent; activeChangedPath?.addParentNode(newParent); reordered || (reordered = (newParent?.childrenAfterGroup?.length ?? 0) > 1); } } if (adds.size) { for (const rowNode of adds) { this.insertOneNode(rootNode, rowNode); const newParent = rowNode.parent; activeChangedPath?.addParentNode(newParent); reordered || (reordered = (newParent?.childrenAfterGroup?.length ?? 0) > 1); } } if (parentsWithRemovals.size) { batchedRemove(parentsWithRemovals); this.removeEmptyGroups(parentsWithRemovals, animate); } if (reordered) { this.sortChildren(changedPath); } } // this is used when doing delta updates, eg Redux, keeps nodes in right order sortChildren(changedPath) { changedPath.forEachChangedNodeDepthFirst( (node) => { const didSort = sortGroupChildren(node.childrenAfterGroup); if (didSort && changedPath.active) { changedPath.addParentNode(node); } }, false, true ); } orderGroups(rootNode) { const initialGroupOrderComparator = this.gos.getCallback("initialGroupOrderComparator"); if (!initialGroupOrderComparator) { return; } const beans = this.beans; const api = beans.gridApi; const context = beans.gridOptions.context; const comparer = (nodeA, nodeB) => initialGroupOrderComparator({ api, context, nodeA, nodeB }); const recursiveSort = (rowNode) => { const childrenAfterGroup = rowNode.childrenAfterGroup; const childrenAfterGroupLen = childrenAfterGroup?.length; if (!childrenAfterGroupLen || rowNode.leafGroup) { return; } if (childrenAfterGroupLen > 1) { childrenAfterGroup.sort(comparer); } for (let i = 0, len = childrenAfterGroupLen; i < len; ++i) { recursiveSort(childrenAfterGroup[i]); } }; recursiveSort(rootNode); } moveNodeInWrongPath(rootNode, childNode) { const { valueSvc } = this.beans; const createGroupForEmpty = this.groupEmpty; let ancestor = childNode.parent; let changed = false; const groupCols = this.groupCols; if (!groupCols) { return false; } for (let idx = groupCols.length - 1; idx >= 0; --idx) { const { col } = groupCols[idx]; let key = valueSvc.getKeyForNode(col, childNode); if (key == null || key === "") { if (!createGroupForEmpty) { continue; } key = ""; } if (!ancestor?.parent || ancestor.key !== key) { changed = true; break; } ancestor = ancestor.parent; } changed || (changed = !!ancestor?.parent); if (!changed) { return false; } this.removeFromParent(childNode); this.insertOneNode(rootNode, childNode); childNode.setData(childNode.data); return true; } 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; } removeEmptyGroups(parents, animate) { const selectionSvc = this.beans.selectionSvc; let nodesToUnselect; const possibleEmptyGroups = Array.from(parents); const groupsById = this.nonLeafsById; do { parents.clear(); for (let idx = 0; idx < possibleEmptyGroups.length; ++idx) { let pointer = possibleEmptyGroups[idx]; while (pointer) { const parent = pointer.parent; if (pointer.destroyed) { possibleEmptyGroups[idx] = parent; pointer = parent; continue; } if (!parent) { break; } if (!this.groupShouldBeRemoved(pointer)) { pointer = parent; continue; } parents.add(parent); this.removeFromParent(pointer); if (selectionSvc && pointer.isSelected()) { nodesToUnselect ?? (nodesToUnselect = []); nodesToUnselect.push(pointer); } possibleEmptyGroups[idx] = parent; groupsById.delete(pointer.id); pointer._destroy(animate); pointer = parent; } } batchedRemove(parents); } while (parents.size); if (nodesToUnselect) { selectionSvc.setNodesSelected({ nodes: nodesToUnselect, newValue: false, source: "rowGroupChanged" }); } } // 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) { const oldParent = child.parent; if (oldParent) { const mapKey = this.getChildrenMappedKey(child.key, child.rowGroupColumn); const childParentChildrenMapped = oldParent.childrenMapped; if (childParentChildrenMapped) { delete childParentChildrenMapped[mapKey]; } } child.setRowTop(null); child.setRowIndex(null); return oldParent; } /** * 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; let childrenAfterGroup = parent.childrenAfterGroup; if (!childrenAfterGroup) { parent.childrenAfterGroup = childrenAfterGroup = []; const sibling = parent.sibling; if (sibling) { sibling.childrenAfterGroup = parent.childrenAfterGroup; } } childrenAfterGroup.push(child); setRowNodeGroup(parent, this.beans, true); invalidateAllLeafChildren(parent); } } shotgunResetEverything(rootNode) { this.beans.selectionSvc?.filterFromSelection?.((node) => !node.group); this.nonLeafsById.clear(); rootNode.leafGroup = !this.groupCols?.length; rootNode.childrenAfterGroup = []; rootNode.childrenMapped = {}; rootNode.updateHasChildren(); const sibling = rootNode.sibling; if (sibling) { sibling.childrenAfterGroup = rootNode.childrenAfterGroup; sibling.childrenMapped = rootNode.childrenMapped; } const allLeafs = rootNode._leafs; for (let i = 0, len = allLeafs.length; i < len; ++i) { this.insertOneNode(rootNode, allLeafs[i]); } } insertOneNode(rootNode, childNode) { let parentGroup = rootNode; const { beans, pivotMode, groupCols, groupEmpty } = this; const valueSvc = beans.valueSvc; if (!groupCols) { return; } const len = groupCols.length; for (let i = 0; i < len; ++i) { const groupCol = groupCols[i]; const col = groupCol.col; let key = valueSvc.getKeyForNode(col, childNode); if (key == null || key === "") { if (!groupEmpty) { continue; } key = ""; } const existingGroup = parentGroup.childrenMapped?.[this.getChildrenMappedKey(key, col)]; if (existingGroup) { parentGroup = existingGroup; continue; } const nextLevel = parentGroup.level + 1; const isLeafLevel = nextLevel >= len - 1; const newGroup = this.createGroup(parentGroup, groupCol, key, nextLevel, isLeafLevel, childNode); this.addToParent(newGroup, parentGroup); this.setExpandedInitialValue(pivotMode, newGroup); parentGroup = newGroup; } if (!parentGroup.group) { _warn31(184, { parentGroupData: parentGroup.data, childNodeData: childNode.data }); } childNode.parent = parentGroup; childNode.level = parentGroup.level + 1; parentGroup.childrenAfterGroup.push(childNode); parentGroup.updateHasChildren(); invalidateAllLeafChildren(parentGroup); } createGroup(parent, groupCol, key, level, isLeafLevel, leafNode) { const col = groupCol.col; const id = (parent.level >= 0 ? parent.id + "-" : "row-group-") + (col.getColId() + "-" + key); const groupsById = this.nonLeafsById; let groupNode = groupsById.get(id); if (groupNode !== void 0) { return groupNode; } groupNode = new RowNode(this.beans); groupNode.group = true; groupNode.parent = parent; groupNode.field = groupCol.field ?? null; groupNode.rowGroupColumn = col; groupNode.key = key; groupNode.id = id; groupNode.level = level; groupNode.leafGroup = isLeafLevel; groupNode.rowGroupIndex = level; groupNode.childrenAfterGroup = []; groupNode.childrenMapped = {}; groupsById.set(id, groupNode); groupNode.groupValue = leafNode && this.beans.valueSvc.getValue(col, leafNode, "data"); groupNode.setAllChildrenCount(0); groupNode.updateHasChildren(); return groupNode; } getChildrenMappedKey(key, rowGroupColumn) { return rowGroupColumn ? rowGroupColumn.getId() + "-" + key : key; } setExpandedInitialValue(pivotMode, groupNode) { if (pivotMode && groupNode.leafGroup) { groupNode.expanded = false; return; } groupNode.expanded = _getRowDefaultExpanded(this.beans, groupNode, groupNode.level); } onShowRowGroupColsSetChanged() { const { rowModel, valueSvc } = this.beans; for (const groupNode of this.nonLeafsById.values()) { groupNode._groupData = void 0; const rowGroupColumn = groupNode.rowGroupColumn; const leafNode = rowGroupColumn && _csrmFirstLeaf2(groupNode); groupNode.groupValue = leafNode && valueSvc.getValue(rowGroupColumn, leafNode, "data"); } const allLeafs = rowModel.rootNode?._leafs; if (allLeafs) { for (let i = 0, len = allLeafs.length; i < len; ++i) { const leafNode = allLeafs[i]; leafNode.parent._groupData = void 0; } } } }; var batchedRemove = (parents) => { for (const parent of parents) { const childrenAfterGroup = parent?.childrenAfterGroup; if (!childrenAfterGroup) { continue; } const childrenAfterGroupLen = childrenAfterGroup.length; let writeIdx = 0; for (let readIdx = 0; readIdx < childrenAfterGroupLen; ++readIdx) { const item = childrenAfterGroup[readIdx]; if (item.parent === parent && !item.destroyed) { if (writeIdx !== readIdx) { childrenAfterGroup[writeIdx] = item; } ++writeIdx; } } if (childrenAfterGroupLen !== writeIdx) { childrenAfterGroup.length = writeIdx; parent.updateHasChildren(); invalidateAllLeafChildren(parent); } } }; var invalidateAllLeafChildren = (node) => { while (node._leafs !== void 0) { const parent = node.parent; if (!parent) { break; } node._leafs = void 0; node = parent; } }; // 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, GroupHierarchyModule ] }; var RowGroupingModule = { moduleName: "RowGrouping", version: VERSION, dynamicBeans: { groupStrategy: GroupStrategy }, rowModels: ["clientSide"], dependsOn: [SharedRowGroupingModule, AggregationModule, ClientSideRowModelHierarchyModule, GroupEditModule] }; 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, _PopupModule4] }; var GroupFilterModule = { moduleName: "GroupFilter", version: VERSION, userComponents: { agGroupColumnFilter: { classImp: GroupFilter, processParams: processGroupFilterParams }, agGroupColumnFloatingFilter: GroupFloatingFilterComp }, beans: [GroupFilterService], dynamicBeans: { agGroupColumnFilterHandler: GroupFilterHandler }, dependsOn: [EnterpriseCoreModule, _ColumnFilterModule3] }; // packages/ag-grid-enterprise/src/viewportRowModel/viewportRowModel.ts import { BeanStub as BeanStub41, RowNode as RowNode2, _addGridCommonParams as _addGridCommonParams19, _getRowHeightAsNumber, _getRowIdCallback, _warn as _warn32 } from "ag-grid-community"; var ViewportRowModel = class extends BeanStub41 { 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 = {}; /** Dummy root node */ this.rootNode = null; /** * 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; const rootNode = new RowNode2(beans); this.rootNode = rootNode; rootNode.level = -1; this.rowHeight = _getRowHeightAsNumber(beans); this.addManagedEventListeners({ viewportChanged: this.onViewportChanged.bind(this) }); this.addManagedPropertyListener("viewportDatasource", () => this.updateDatasource()); this.addManagedPropertyListener("rowHeight", () => { this.rowHeight = _getRowHeightAsNumber(beans); this.updateRowHeights(); }); } start() { this.updateDatasource(); } isLastRowIndexKnown() { return true; } destroy() { this.destroyDatasource(); super.destroy(); this.rootNode = null; } 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; for (const indexStr of Object.keys(rowNodesByIndex)) { const index = parseInt(indexStr, 10); if (index < this.firstRow || index > this.lastRow) { if (this.isRowFocused(index) || this.beans.editSvc?.isRowEditing(rowNodesByIndex[index])) { continue; } 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) { _warn32(226); } else { viewportDatasource.init( _addGridCommonParams19(this.gos, { 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; } /** Viewport row model does not support dynamic row heights by design and while it is possible to implement this feature, it leads to view-model desync due to data being not isotropic in time */ resetRowHeights() { } /** Viewport row model does not support dynamic row heights by design and while it is possible to implement this feature, it leads to view-model desync due to data being not isotropic in time */ onRowHeightChanged() { } 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; } getOverlayType() { return null; } 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; for (const indexStr of Object.keys(this.rowNodesByIndex)) { const index = parseInt(indexStr, 10); const rowNode = this.rowNodesByIndex[index]; callback(rowNode, callbackCount); callbackCount++; } } setRowData(rowData) { const getRowIdFunc = _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 RowNode2(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 import { CsvExportModule, HighlightChangesModule, _KeyboardNavigationModule as _KeyboardNavigationModule2 } from "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 import { BeanStub as BeanStub42, ChangedPath as ChangedPath2, _createCellId as _createCellId2, _exists as _exists21, _getActiveDomElement as _getActiveDomElement12, _getDocument as _getDocument4, _getRowBelow as _getRowBelow2, _getRowNode as _getRowNode3, _isClientSideRowModel as _isClientSideRowModel8, _isSameRow, _last as _last11, _removeFromArray as _removeFromArray6, _warn as _warn33, isColumnSelectionCol, isSpecialCol } from "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 BeanStub42 { 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 (_isClientSideRowModel8(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?.readText) { navigator.clipboard.readText().then(this.processClipboardData.bind(this)).catch((e) => { _warn33(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 _exists21(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, editSvc } = this.beans; const pasteOperation = (cellsToFlash, updatedRowNodes, focusedCell, changedPath) => { const rangeActive = rangeSvc?.isMoreThanOneCell(); const pasteIntoRange = rangeActive && !this.hasOnlyOneValueToPaste(parsedData); if (pasteIntoRange) { this.pasteIntoActiveRange(parsedData, cellsToFlash, updatedRowNodes, changedPath); } else { this.pasteStartingFromFocusedCell(parsedData, cellsToFlash, updatedRowNodes, focusedCell, changedPath); } 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 ChangedPath2(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 }); } getPreProcessRangeCallback(clipboardData) { return (cellRange) => { const { rangeSvc } = this.beans; if (!rangeSvc) { return; } const { rowDiff, colDiff } = this.getAdjustedRangeDimensionForPaste(cellRange, clipboardData); if (rowDiff !== 0) { rangeSvc.extendRangeRowCountBy(cellRange, rowDiff); } if (colDiff !== 0) { rangeSvc.extendRangeColumnCountBy(cellRange, colDiff); } }; } getAdjustedRangeDimensionForPaste(cellRange, clipboardData) { const rangeSvc = this.beans.rangeSvc; const clipboardRowCount = clipboardData.length; const rangeRowCount = rangeSvc.getRangeRowCount(cellRange); const isRowMultiple = rangeRowCount >= clipboardRowCount && rangeRowCount % clipboardRowCount === 0; const clipboardColCount = clipboardData[0].length; const rangeColCount = cellRange.columns.length; const isColMultiple = rangeColCount >= clipboardColCount && rangeColCount % clipboardColCount === 0; return { rowDiff: isRowMultiple ? 0 : clipboardRowCount - rangeRowCount, colDiff: isColMultiple ? 0 : clipboardColCount - rangeColCount }; } pasteIntoActiveRange(clipboardData, cellsToFlash, updatedRowNodes, changedPath) { let indexOffset = 0; let dataRowIndex = 0; const rowCallback = (currentRow, rowNode, range, rangeIndex) => { const atEndOfClipboardData = rangeIndex - indexOffset >= clipboardData.length; if (atEndOfClipboardData) { if (rangeIndex % clipboardData.length !== 0) { return; } indexOffset += dataRowIndex; dataRowIndex = 0; } const currentRowData = clipboardData[rangeIndex - indexOffset]; updatedRowNodes.push(rowNode); const processCellFromClipboardFunc = this.gos.getCallback("processCellFromClipboard"); const columns = range.columns; const selectionColIdx = columns.findIndex(isColumnSelectionCol); if (selectionColIdx !== -1) { columns.splice(selectionColIdx, 1); } 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 ); rowNode.setDataValue(column, newValue, SOURCE_PASTE); changedPath?.addParentNode(rowNode.parent, [column]); const { rowIndex, rowPinned } = currentRow; const cellId = _createCellId2({ rowIndex, column, rowPinned }); cellsToFlash[cellId] = true; } dataRowIndex++; }; this.iterateActiveRanges(rowCallback, false, this.getPreProcessRangeCallback(clipboardData)); } getDisplayedColumnsStartingAt(column) { let currentColumn = column; const columns = []; const { visibleCols } = this.beans; while (currentColumn && 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, range) => { updatedRowNodes.push(rowNode); range.columns.forEach( (column) => this.updateCellValue(rowNode, column, value, cellsToFlash, EXPORT_TYPE_CLIPBOARD, changedPath) ); }; this.iterateActiveRanges(rowCallback); } hasOnlyOneValueToPaste(parsedData) { return parsedData.length === 1 && parsedData[0].length === 1; } copyRangeDown() { const { rangeSvc, gos, formula, 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, range) => { const { columns } = range; if (!firstRowValues.length) { columns.forEach((column) => { const value = this.processCell( rowNode, column, valueSvc.getValue(column, rowNode, "batch"), 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 isFormula = column.isAllowFormula() && formula?.isFormula(firstRowValues[index]); if (isFormula) { firstRowValues[index] = formula?.updateFormulaByOffset({ value: firstRowValues[index], rowDelta: 1 }); } const firstRowValue = this.processCell( rowNode, column, firstRowValues[index], EXPORT_TYPE_DRAG_COPY, processCellFromClipboardFunc, true ); rowNode.setDataValue(column, firstRowValue, SOURCE_PASTE); if (changedPath) { changedPath.addParentNode(rowNode.parent, [column]); } const { rowIndex, rowPinned } = currentRow; const cellId = _createCellId2({ rowIndex, column, rowPinned }); cellsToFlash[cellId] = true; }); } }; this.iterateActiveRanges(rowCallback, true); }; this.doPasteOperation(pasteOperation); } removeLastLineIfBlank(parsedData) { const lastLine = _last11(parsedData); const lastLineIsBlank = lastLine && lastLine.length === 1 && lastLine[0] === ""; if (lastLineIsBlank) { if (parsedData.length === 1) { return; } _removeFromArray6(parsedData, lastLine); } } fireRowChanged(rowNodes) { if (this.gos.get("editType") !== "fullRow") { return; } for (const rowNode of rowNodes) { 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 = _getRowNode3(beans, rowPointer); rowPointer = _getRowBelow2(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; } } }; for (const clipboardRowData of clipboardGridData) { const rowNode = getNextGoodRowNode(); if (!rowNode) { continue; } 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?.isCellEditable(rowNode) || column?.isSuppressPaste(rowNode)) { return; } const processedValue = this.processCell( rowNode, column, value, type, this.gos.getCallback("processCellFromClipboard"), true ); rowNode.setDataValue(column, processedValue, SOURCE_PASTE); const { rowIndex, rowPinned } = rowNode; const cellId = _createCellId2({ 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 = _getRowNode3(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 deleteValue = this.beans.valueSvc.getDeleteValue(column, rowNode); rowNode.setDataValue(column, deleteValue, "clipboardSvc"); } iterateActiveRanges(rowCallback, onlyFirst, preProcessRange) { const rangeSvc = this.beans.rangeSvc; if (!rangeSvc || rangeSvc.isEmpty()) { return; } const currentCellRanges = rangeSvc.getCellRanges(); const cellRanges = onlyFirst ? [currentCellRanges[0]] : currentCellRanges; for (const cellRange of cellRanges) { this.iterateActiveRange({ cellRange, rowCallback, preProcessRange }); } } iterateActiveRange(params) { const { cellRange, preProcessRange, rowCallback } = params; const { beans } = this; const { rangeSvc } = beans; if (!rangeSvc) { return; } if (preProcessRange) { preProcessRange(cellRange); } let currentRow = rangeSvc.getRangeStartRow(cellRange); const lastRow = rangeSvc.getRangeEndRow(cellRange); let rangeIndex = 0; let isLastRow = false; while (!isLastRow && currentRow != null) { const rowNode = _getRowNode3(beans, currentRow); isLastRow = _isSameRow(currentRow, lastRow); rowCallback(currentRow, rowNode, cellRange, rangeIndex++); currentRow = _getRowBelow2(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 = {}; const isClientSideRowModel = _isClientSideRowModel8(this.gos, this.beans.rowModel); const flatCache = /* @__PURE__ */ new Set(); if (!isClientSideRowModel) { this.beans.rowModel.forEachNode((node) => { flatCache.add(node.rowIndex); }); } for (const range of ranges) { range.columns.forEach((col) => columnsSet.add(col)); const { rowPositions, cellsToFlash } = this.getRangeRowPositionsAndCellsToFlash(rangeSvc, range); for (const rowPosition of rowPositions) { const isInCache = flatCache.has(rowPosition.rowIndex); if (!isClientSideRowModel && !isInCache) { continue; } 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 = {}; for (const range of ranges) { 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); for (const column of range.columns) { const { rowIndex, rowPinned } = node; const cellId = _createCellId2({ rowIndex, column, rowPinned }); cellsToFlash[cellId] = true; } if (_isSameRow(node, lastRow)) { break; } node = _getRowBelow2(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 = _createCellId2({ 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 = _createCellId2(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, includeValueFormatted: true, from: "batch" }); 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, valueFrom: "batch", 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, formula } = this.beans; 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, "edit") ) }; return func(params); } if (canParse && column.getColDef().useValueParserForImport !== false) { return valueSvc.parseValue(column, rowNode ?? null, value, valueSvc.getValue(column, rowNode, "edit")); } if (canFormat && column.getColDef().useValueFormatterForExport !== false) { if (formula?.isFormula(value)) { return value; } 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) => { _warn33(40, { e, method: "writeText" }); this.copyDataToClipboardLegacy(data); }); return; } this.copyDataToClipboardLegacy(data); } copyDataToClipboardLegacy(data) { this.executeOnTempElement((element) => { const eDocument = _getDocument4(this.beans); const focusedElementBefore = _getActiveDomElement12(this.beans); element.value = data || " "; element.select(); element.focus({ preventScroll: true }); const result = eDocument.execCommand("copy"); if (!result) { _warn33(41); } if (focusedElementBefore?.focus != null) { focusedElementBefore.focus({ preventScroll: true }); } }); } executeOnTempElement(callbackNow, callbackAfter) { if (!this.gridCtrl) { return; } const eDoc = _getDocument4(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) { _warn33(42); } if (callbackAfter) { window.setTimeout(() => { callbackAfter(eTempInput); eTempInput.remove(); }, 100); } else { eTempInput.remove(); } } }; // 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, CsvExportModule, _KeyboardNavigationModule2, HighlightChangesModule] }; // packages/ag-grid-enterprise/src/rowNumbers/rowNumbersModule.ts import { CellStyleModule, _SharedDragAndDropModule as _SharedDragAndDropModule4 } from "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 import { Component as Component40, Direction, _getRowNode as _getRowNode4 } from "ag-grid-community"; var RowNumbersRowResizerElement = { tag: "div", cls: "ag-row-numbers-resizer" }; var AgRowNumbersRowResizer = class extends Component40 { 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 = _getRowNode4(this.beans, rowPosition); } onDragStart(mouseEvent) { if (!this.node) { return; } const { beans: { ctrlsSvc, eventSvc } } = this; const ctrl = ctrlsSvc.get("gridCtrl"); ctrl.setResizeCursor(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 import { AgColumn as AgColumn3, BeanStub as BeanStub43, KeyCode as KeyCode29, ROW_NUMBERS_COLUMN_ID, _addGridCommonParams as _addGridCommonParams20, _applyColumnState as _applyColumnState3, _areColIdsEqual as _areColIdsEqual3, _convertColumnEventSourceType as _convertColumnEventSourceType2, _createElement as _createElement13, _debounce as _debounce4, _destroyColumnTree as _destroyColumnTree3, _getColumnStateFromColDef as _getColumnStateFromColDef2, _getFirstRow, _getRowNode as _getRowNode5, _interpretAsRightClick, _isRowNumbers as _isRowNumbers2, _selectAllCells, _setAriaLabel as _setAriaLabel15, _updateColsMap as _updateColsMap3, isRowNumberCol } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rowNumbers/rowNumbersRowResizeFeature.ts import { _isRowNumbers, _removeFromParent as _removeFromParent7, _warn as _warn34 } from "ag-grid-community"; function _isRowNumbersResizerEnabled(beans) { const rowNumbers = _isRowNumbers(beans); return !(!rowNumbers || typeof rowNumbers !== "object" || !rowNumbers.enableRowResizer); } var RowNumbersRowResizeFeature = class { constructor(beans, cellCtrl) { this.beans = beans; this.cellCtrl = cellCtrl; } refreshRowResizer() { if (!_isRowNumbersResizerEnabled(this.beans) || !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) { _warn34(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) { eGui.appendChild(rowResizer.getGui()); return; } rowResizer = beans.registry.createDynamicBean("rowNumberRowResizer", false, cellCtrl); if (!rowResizer) { return; } this.rowResizer = beans.context.createBean(rowResizer); eGui.appendChild(rowResizer.getGui()); } removeRowResizerFromCellComp() { const { rowResizer, beans: { context } } = this; if (!rowResizer) { return; } _removeFromParent7(rowResizer.getGui()); this.rowResizer = context.destroyBean(rowResizer); } destroy() { this.removeRowResizerFromCellComp(); } }; // packages/ag-grid-enterprise/src/rowNumbers/rowNumbersService.ts var RowNumbersService = class extends BeanStub43 { constructor() { super(...arguments); this.beanName = "rowNumbersSvc"; this.isIntegratedWithSelection = false; this.lastColumnResized = 0; } postConstruct() { const refreshCells_debounced = _debounce4(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.updateColumns(e); }); this.refreshSelectionIntegration(); this.registerRangeSelectionExtension(); } shouldSkipColumn(column) { return _isRowNumbers2(this.beans) && isRowNumberCol(column); } isAllColumnsSelectionCell(cellPosition) { return _isRowNumbers2(this.beans) && isRowNumberCol(cellPosition.column); } isAllColumnsRange(range, allColumns) { if (!_isRowNumbers2(this.beans) || allColumns.length === 0) { return false; } return range.columns.length === allColumns.length && allColumns.every((column) => range.columns.includes(column)); } registerRangeSelectionExtension() { const rangeSvc = this.beans.rangeSvc; if (!rangeSvc) { return; } rangeSvc.registerRangeSelectionExtension(this); this.addDestroyFunc(() => rangeSvc.unregisterRangeSelectionExtension?.(this)); } addColumns(cols) { if (this.columns == null) { return; } cols.list = this.columns.list.concat(cols.list); cols.tree = this.columns.tree.concat(cols.tree); _updateColsMap3(cols); } createColumns(cols, updateOrders) { const destroyCollection = () => { _destroyColumnTree3(this.beans, this.columns?.tree); this.columns = null; }; const { beans } = this; if (!_isRowNumbers2(beans)) { destroyCollection(); return; } const newTreeDepth = cols.treeDepth; const oldTreeDepth = this.columns?.treeDepth ?? -1; const treeDepthSame = oldTreeDepth == newTreeDepth; const list = this.generateRowNumberCols(); const areSame = _areColIdsEqual3(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) => !isRowNumberCol(col)); return [...list, ...colsFiltered]; }; updateOrders(putRowNumbersColsFirstInList); } handleMouseDownOnCell(cellPosition, mouseEvent) { if (!this.isIntegratedWithSelection || mouseEvent.target.classList.contains("ag-row-numbers-resizer")) { if (this.beans.rangeSvc) { mouseEvent.preventDefault(); } mouseEvent.stopImmediatePropagation(); return false; } if (!mouseEvent.shiftKey && !_interpretAsRightClick(this.beans, mouseEvent)) { this.focusFirstRenderedCellAtRowPosition(cellPosition); } return true; } updateColumns(event) { const source = _convertColumnEventSourceType2(event.source); this.refreshSelectionIntegration(); for (const col of this.columns?.list ?? []) { const colDef = this.createRowNumbersColDef(); col.setColDef(colDef, null, source); _applyColumnState3(this.beans, { state: [_getColumnStateFromColDef2(colDef, col.getColId())] }, source); } } getColumn() { return this.columns?.list.find(isRowNumberCol) ?? null; } getColumns() { return this.columns?.list ?? null; } setupForHeader(comp) { const { column, eGridHeader } = comp.params; if (!isRowNumberCol(column)) { return; } _setAriaLabel15(eGridHeader, "Row Number"); this.addManagedElementListeners(eGridHeader, { click: this.onHeaderClick.bind(this), keydown: this.onHeaderKeyDown.bind(this), focus: this.onHeaderFocus.bind(this) }); } createRowNumbersRowResizerFeature(ctrl) { if (!_isRowNumbersResizerEnabled(this.beans)) { return void 0; } return new RowNumbersRowResizeFeature(this.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 = _isRowNumbers2(this.beans); 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", "tooltipComponentSelector", "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 !== KeyCode29.SPACE) { return; } this.handleFocusAllCellsFromHeader(); } onHeaderClick(_e) { if (Date.now() - this.lastColumnResized < 100 || !this.isIntegratedWithSelection || this.getColumn()?.resizing) { return; } this.handleFocusAllCellsFromHeader(); } handleFocusAllCellsFromHeader() { _selectAllCells(this.beans); this.focusFirstRenderedCellAtRowPosition(); } 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 = _createElement13({ tag: "div", cls: "ag-cell-value ag-cell" }); let value = String(this.beans.rowModel.getRowCount() + 1); if (typeof this.rowNumberOverrides.valueFormatter === "function") { const valueFormatterParams = _addGridCommonParams20(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.bind(this), contextMenuItems: this.isIntegratedWithSelection || !contextMenuSvc ? void 0 : () => [], // overrides ...this.rowNumberOverrides, // non-overridable properties colId: 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; const isFormulasActive = this.beans.formula?.active; const pinnedSibling = node?.pinnedSibling; if (node?.rowPinned && pinnedSibling) { const rowIndex = isFormulasActive ? pinnedSibling.formulaRowIndex : pinnedSibling.rowIndex; return `${rowIndex == null ? "-" : rowIndex + 1}`; } return String(((isFormulasActive ? node?.formulaRowIndex : 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({ rowIndex: node.rowIndex, rowPinned: 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, beans } = this; if (!_isRowNumbers2(beans)) { return []; } const colDef = this.createRowNumbersColDef(); const colId = colDef.colId; gos.validateColDef(colDef, colId, true); const col = new AgColumn3(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 or first cell of the grid (from header). focusFirstRenderedCellAtRowPosition(rowPosition) { const editSvc = this.beans.editSvc; if (editSvc?.isEditing() && editSvc.isRangeSelectionEnabledWhileEditing?.()) { return; } if (!rowPosition) { rowPosition = _getFirstRow(this.beans); if (!rowPosition) { return; } } 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 = _getRowNode5(beans, rowPosition); if (!rowNode) { return; } columns = colViewport.getColsWithinViewport(rowNode); } else { columns = pinnedCols; } const column = columns.find((col) => !isRowNumberCol(col)); if (!column) { return; } const { rowPinned, rowIndex } = rowPosition; setTimeout(() => { beans.focusSvc.setFocusedCell({ rowIndex, rowPinned, column, forceBrowserFocus: true, preventScrollOnBrowserFocus: true }); }); } destroy() { _destroyColumnTree3(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, CellStyleModule, _SharedDragAndDropModule4], css: [rowNumbersCSS] }; // packages/ag-grid-enterprise/src/filterToolPanel/filtersToolPanelModule.ts import { _ColumnFilterModule as _ColumnFilterModule4 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/filterToolPanel/filtersToolPanel.ts import { Component as Component45, RefPlaceholder as RefPlaceholder40 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/filterToolPanel/agFiltersToolPanelHeader.ts import { AgInputTextFieldSelector as AgInputTextFieldSelector8, Component as Component41, RefPlaceholder as RefPlaceholder37, _createIconNoSpan as _createIconNoSpan20, _debounce as _debounce5, _setDisplayed as _setDisplayed20 } from "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 Component41 { constructor() { super(...arguments); this.eExpand = RefPlaceholder37; this.eFilterTextField = RefPlaceholder37; } postConstruct() { this.setTemplate(AgFiltersToolPanelHeaderElement, [AgInputTextFieldSelector8]); 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 = _createIconNoSpan20("accordionOpen", beans)); eExpand.appendChild(this.eExpandUnchecked = _createIconNoSpan20("accordionClosed", beans)); eExpand.appendChild(this.eExpandIndeterminate = _createIconNoSpan20("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); _setDisplayed20(eFilterTextField.getGui(), showFilterSearch); _setDisplayed20(this.eExpand, showExpand && filterGroupsPresent); } onSearchTextChanged() { if (!this.onSearchTextChangedDebounced) { this.onSearchTextChangedDebounced = _debounce5( 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; _setDisplayed20(this.eExpandChecked, state === 0 /* EXPANDED */); _setDisplayed20(this.eExpandUnchecked, state === 1 /* COLLAPSED */); _setDisplayed20(this.eExpandIndeterminate, state === 2 /* INDETERMINATE */); } }; var AgFiltersToolPanelHeaderSelector = { selector: "AG-FILTERS-TOOL-PANEL-HEADER", component: AgFiltersToolPanelHeader }; // packages/ag-grid-enterprise/src/filterToolPanel/agFiltersToolPanelList.ts import { Component as Component44, _addGridCommonParams as _addGridCommonParams21, _clearElement as _clearElement16, _exists as _exists22, _getActiveDomElement as _getActiveDomElement13, _mergeDeep as _mergeDeep4, _setAriaLabel as _setAriaLabel18, _warn as _warn35, isProvidedColumnGroup as isProvidedColumnGroup6 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/filterToolPanel/toolPanelFilterComp.ts import { Component as Component42, FilterComp as FilterComp3, KeyCode as KeyCode30, RefPlaceholder as RefPlaceholder38, _clearElement as _clearElement14, _createElement as _createElement14, _createIconNoSpan as _createIconNoSpan21, _setAriaExpanded as _setAriaExpanded10, _setAriaLabel as _setAriaLabel16, _setAriaRole as _setAriaRole10, _setDisplayed as _setDisplayed21 } from "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" } ] }, { tag: "div", ref: "agFilterToolPanelBody", cls: "ag-filter-toolpanel-instance-body ag-filter" } ] }; var ToolPanelFilterComp = class extends Component42 { constructor(hideHeader, expandedCallback) { super(ToolPanelFilterElement); this.hideHeader = hideHeader; this.expandedCallback = expandedCallback; this.eFilterToolPanelHeader = RefPlaceholder38; this.eFilterName = RefPlaceholder38; this.agFilterToolPanelBody = RefPlaceholder38; this.eFilterIcon = RefPlaceholder38; this.eExpand = RefPlaceholder38; this.expanded = false; } postConstruct() { const { beans, eExpand, eFilterIcon } = this; const eExpandChecked = _createIconNoSpan21("accordionOpen", beans); this.eExpandChecked = eExpandChecked; const eExpandUnchecked = _createIconNoSpan21("accordionClosed", beans); this.eExpandUnchecked = eExpandUnchecked; eExpand.appendChild(eExpandChecked); eExpand.appendChild(eExpandUnchecked); const translate = this.getLocaleTextFunc(); _setAriaLabel16(eFilterIcon, translate("ariaFilterActive", "Filter Active")); _setAriaRole10(eFilterIcon, "img"); } 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); _setDisplayed21(eFilterIcon, this.isFilterActive()); _setDisplayed21(eExpandChecked, false); if (hideHeader) { _setDisplayed21(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 } = KeyCode30; if (key !== ENTER && key !== SPACE && key !== LEFT && key !== RIGHT) { return; } e.preventDefault(); if (key === ENTER || key === SPACE) { this.toggleExpanded(); } else if (key === KeyCode30.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 = _createIconNoSpan21(iconName, this.beans, column); eParent.appendChild(eIcon); } isFilterActive() { return !!this.beans.colFilter?.isFilterActive(this.column); } onFilterChanged() { _setDisplayed21(this.eFilterIcon, this.isFilterActive()); this.dispatchLocalEvent({ type: "filterChanged" }); } toggleExpanded() { if (this.expanded) { this.collapse(); } else { this.expand(); } } expand() { if (this.expanded) { return; } this.expanded = true; _setAriaExpanded10(this.eFilterToolPanelHeader, true); _setDisplayed21(this.eExpandChecked, true); _setDisplayed21(this.eExpandUnchecked, false); this.addFilterElement(); this.expandedCallback(); } addFilterElement(suppressFocus) { const filterPanelWrapper = _createElement14({ tag: "div", cls: "ag-filter-toolpanel-instance-filter" }); const comp = this.createManagedBean(new FilterComp3(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; _setAriaExpanded10(this.eFilterToolPanelHeader, false); this.removeFilterElement(); _setDisplayed21(this.eExpandChecked, false); _setDisplayed21(this.eExpandUnchecked, true); const filterComp = this.filterComp; filterComp?.afterGuiDetached(); this.destroyBean(filterComp); this.expandedCallback(); } removeFilterElement() { _clearElement14(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 import { Component as Component43, RefPlaceholder as RefPlaceholder39, _clearElement as _clearElement15, _createIconNoSpan as _createIconNoSpan22, _getShouldDisplayTooltip as _getShouldDisplayTooltip4, _setAriaLabel as _setAriaLabel17, _setAriaRole as _setAriaRole11, isProvidedColumnGroup as isProvidedColumnGroup5 } from "ag-grid-community"; var ToolPanelFilterGroupComp = class extends Component43 { constructor(columnGroup, childFilterComps, expandedCallback, depth, showingColumn) { super(); this.columnGroup = columnGroup; this.childFilterComps = childFilterComps; this.expandedCallback = expandedCallback; this.depth = depth; this.showingColumn = showingColumn; this.filterGroupComp = RefPlaceholder39; } 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`); for (const filterComp of childFilterComps) { 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: _getShouldDisplayTooltip4( gos, () => filterGroupComp.getGui().querySelector(".ag-group-title") ), getAdditionalParams: () => ({ colDef: column?.getColDef(), column }) }) ); 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() { for (const filterComp of this.childFilterComps) { filterComp.onPanelHidden(); } } isColumnGroup() { return isProvidedColumnGroup5(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 = _createIconNoSpan22(iconName, this.beans); if (eIcon) { eIcon.classList.add("ag-filter-toolpanel-group-instance-header-icon"); const translate = this.getLocaleTextFunc(); _setAriaLabel17(eIcon, translate("ariaFilterActive", "Filter Active")); _setAriaRole11(eIcon, "img"); } this.filterGroupComp.addTitleBarWidget(eIcon); } forEachToolPanelFilterChild(action) { for (const filterComp of this.childFilterComps) { 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 (isProvidedColumnGroup5(this.columnGroup)) { return this.columnGroup.getLeafColumns(); } return [this.columnGroup]; } addFilterChangedListeners() { for (const column of this.getColumns()) { this.addManagedListeners(column, { filterChanged: () => this.refreshFilterClass() }); } if (!isProvidedColumnGroup5(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 = isProvidedColumnGroup5(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); _clearElement15(this.getGui()); } destroy() { this.destroyFilters(); super.destroy(); } }; // packages/ag-grid-enterprise/src/filterToolPanel/agFiltersToolPanelList.ts var AgFiltersToolPanelList = class extends Component44 { 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 = _addGridCommonParams21(this.gos, { suppressExpandAll: false, suppressFilterSearch: false, suppressSyncLayoutWithGrid: false }); _mergeDeep4(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; if (shouldSyncColumnLayoutWithGrid) { this.syncFilterLayout(); } else { 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 = _getActiveDomElement13(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) { for (const comp of filterGroupComps) { this.appendChild(comp); } this.setFirstAndLastVisible(0, len - 1); } const searchFilterText = this.searchFilterText; if (_exists22(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 (isProvidedColumnGroup6(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; _setAriaLabel18(this.getAriaElement(), `${filterListName} ${totalVisibleItems} ${localeFilters}`); } recursivelyAddFilterGroupComps(columnGroup, depth, expansionState) { if (!this.filtersExistInChildren(columnGroup.getChildren())) { return; } const colGroupDef = columnGroup.getColGroupDef(); if (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 (isProvidedColumnGroup6(child)) { return this.filtersExistInChildren(child.getChildren()); } return this.shouldDisplayFilter(child); }); } shouldDisplayFilter(column) { const suppressFiltersToolPanel = column.getColDef()?.suppressFiltersToolPanel; return column.isFilterAllowed() && !suppressFiltersToolPanel; } getExpansionState() { const expansionState = /* @__PURE__ */ new Map(); if (this.isInitialState) { const { expandedColIds, expandedGroupIds } = this.params.initialState; for (const id of expandedColIds) { expansionState.set(id, true); } for (const id of expandedGroupIds) { expansionState.set(id, true); } return expansionState; } const recursiveGetExpansionState = (filterGroupComp) => { expansionState.set(filterGroupComp.getFilterGroupId(), filterGroupComp.isExpanded()); for (const child of filterGroupComp.getChildren()) { if (child instanceof ToolPanelFilterGroupComp) { recursiveGetExpansionState(child); } else { expansionState.set(child.getColumn().getId(), child.isExpanded()); } } }; this.filterGroupComps.forEach(recursiveGetExpansionState); return expansionState; } 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); } for (const child of filterGroup.getChildren()) { 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) { _warn35(166, { unrecognisedGroupIds }); } } } expandFilters(expand, colIds) { const updatedColIds = []; const updateGroupExpandState = (filterComp) => { if (filterComp instanceof ToolPanelFilterGroupComp) { let anyChildrenChanged = false; for (const child of filterComp.getChildren()) { 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) { if (expand) { filterComp.expand(); } else { 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) { _warn35(167, { unrecognisedColIds }); } } } onGroupExpanded() { this.fireExpandedEvent(); } onFilterExpanded() { this.dispatchLocalEvent({ type: "filterExpanded" }); } fireExpandedEvent() { let expandedCount = 0; let notExpandedCount = 0; const updateExpandCounts = (filterGroup) => { if (!filterGroup.isColumnGroup()) { return; } if (filterGroup.isExpanded()) { expandedCount++; } else { notExpandedCount++; } for (const child of filterGroup.getChildren()) { 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 = _exists22(searchText) ? searchText.toLowerCase() : null; this.searchFilters(this.searchFilterText); } searchFilters(searchFilter) { const passesFilter = (groupName) => { return !_exists22(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() { for (const filterGroupComp of this.filterGroupComps) { filterGroupComp.onPanelHidden(); } } getExpandedFiltersAndGroups() { const expandedGroupIds = []; const expandedColIds = /* @__PURE__ */ new Set(); const getExpandedFiltersAndGroups = (filterComp) => { if (filterComp instanceof ToolPanelFilterGroupComp) { for (const child of filterComp.getChildren()) { 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); _clearElement16(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);>:where(.ag-filter-icon),>:where(.ag-filter-toolpanel-expand),>:where(.ag-filter-toolpanel-search-input),>:where(.ag-header-cell-text){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 Component45 { constructor() { super(FiltersToolPanelElement, [AgFiltersToolPanelHeaderSelector, AgFiltersToolPanelListSelector]); this.filtersToolPanelHeaderPanel = RefPlaceholder40; this.filtersToolPanelListPanel = RefPlaceholder40; this.initialised = false; this.listenerDestroyFuncs = []; this.registerCSS(filtersToolPanelCSS); } init(params) { if (this.initialised) { for (const func of this.listenerDestroyFuncs) { 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 import { BeanStub as BeanStub44, FilterComp as FilterComp4 } from "ag-grid-community"; var FilterPanelService = class extends BeanStub44 { constructor() { super(...arguments); this.beanName = "filterPanelSvc"; this.states = /* @__PURE__ */ new Map(); this.orderedStates = []; this.initialStateApplied = false; this.columnsLoaded = false; this.isActive = false; } postConstruct() { if (!this.gos.get("enableFilterHandlers")) { return; } const updateFilterStates = this.updateFilterStates.bind(this); const updateApplyButton = () => this.dispatchStatesUpdates(void 0, true); const onFilterDestroyed = this.onFilterDestroyed.bind(this); this.addManagedEventListeners({ newColumnsLoaded: () => { this.columnsLoaded = true; if (!this.initialStateApplied) { this.applyState(); } updateFilterStates(); }, dataTypesInferred: updateFilterStates, filterChanged: updateFilterStates, filterDestroyed: onFilterDestroyed, filterHandlerDestroyed: onFilterDestroyed, filterOpened: updateApplyButton, filterClosed: updateApplyButton }); const refreshForColumn = ({ column }) => { this.states.get(column.getColId())?.refresh?.(); updateApplyButton(); }; this.addManagedListeners(this.beans.colFilter, { filterStateChanged: refreshForColumn, filterModelAsStringChanged: refreshForColumn }); } updateParams(params, state) { this.params = params; let dispatchedStateUpdates = false; if (state) { this.currState = state; if (this.columnsLoaded) { const newIds = new Set(state.filters?.map((f) => f.colId)); for (const id of this.getIds()) { if (!newIds.has(id)) { this.remove(id); } } this.clear(); this.applyState(); this.updateFilterStates(); dispatchedStateUpdates = true; } } if (!dispatchedStateUpdates) { this.dispatchStatesUpdates(); } this.beans.colFilter?.setGlobalButtons(!!params.buttons?.length); } getIds() { return Array.from(this.states.keys()); } getAvailable() { const beans = this.beans; const availableFilters = []; for (const column of beans.colModel.getColDefCols() ?? []) { 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); } 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.getColDefCol(id); if (column && !column.colDef.suppressFiltersToolPanel) { const handler = colFilter.getHandler(column, true); if (handler) { return this.createFilterState(column, handler, expanded); } } return void 0; } updateFilterStates() { if (!this.params) { return; } 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 FilterComp4(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 }) { const { colFilter, filterManager } = this.beans; if (!colFilter?.isAlive() || !filterManager?.isFilterAllowed(column)) { 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 }); } applyState() { if (this.params && this.columnsLoaded) { this.initialStateApplied = true; for (const { colId, expanded } of this.currState?.filters ?? []) { this.createFilter(colId, expanded); } } } destroy() { this.clear(); this.params = void 0; this.currState = void 0; super.destroy(); } clear() { const { states, orderedStates } = this; states.forEach((state) => state.destroy?.()); states.clear(); orderedStates.length = 0; } }; function getDisplayName(beans, column) { return beans.colNames.getDisplayNameForColumn(column, "filterToolPanel") ?? column.getColId(); } // packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/selectableFilterService.ts import { BeanStub as BeanStub45, _addGridCommonParams as _addGridCommonParams22, _getDefaultSimpleFilter as _getDefaultSimpleFilter2, _getFilterParamsForDataType as _getFilterParamsForDataType2, _isSetFilterByDefault, _warn as _warn36 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterPanelUtils.ts import { _removeFromParent as _removeFromParent8, _translate as _translate2 } from "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 _translate2(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 { _removeFromParent8(ePrevItem); } } while (newIndex < eNewItems.length) { eContainer.appendChild(eNewItems[newIndex++]); } } // packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/selectableFilterService.ts var SelectableFilterService = class extends BeanStub45 { constructor() { super(...arguments); this.beanName = "selectableFilter"; this.selectedFilters = /* @__PURE__ */ new Map(); this.valueGetters = /* @__PURE__ */ new Map(); } postConstruct() { const { gos, selectedFilters } = this; const initialState = gos.get("initialState")?.filter?.selectableFilters ?? {}; for (const colId of Object.keys(initialState)) { selectedFilters.set(colId, initialState[colId]); } } 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, overrideIndex) { 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( _addGridCommonParams22(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 = _getFilterParamsForDataType2( 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 { _warn36(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 = overrideIndex ?? // provided override this.selectedFilters.get(column.getColId()) ?? // UI selected value defaultFilterIndex ?? // col def value (!filters && _isSetFilterByDefault(gos) ? 1 : 0); if (index >= filterDefs.length) { index = 0; } const activeFilterDef = filterDefs[index]; return { filterDefs, activeFilterDef }; } setActive(colId, filterDefs, activeFilterDef, silent) { 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); } if (!silent) { this.onChange(); } } clearActive(colId) { const { selectedFilters, valueGetters } = this; selectedFilters.delete(colId); valueGetters.delete(colId); this.onChange(); } getState() { return Object.fromEntries(this.selectedFilters); } setState(state) { this.clearAll(); const colModel = this.beans.colModel; for (const colId of Object.keys(state)) { const column = colModel.getColDefCol(colId); if (column) { const defs = this.getDefs(column, column.colDef, state[colId]); if (defs) { this.setActive(colId, defs.filterDefs, defs.activeFilterDef, true); } } } } destroy() { this.clearAll(); super.destroy(); } clearAll() { const { selectedFilters, valueGetters } = this; selectedFilters.clear(); valueGetters.clear(); } onChange() { this.dispatchLocalEvent({ type: "selectedFilterChanged" }); } getDefaultFilters(column) { const beans = this.beans; const { gos, dataTypeSvc } = beans; const isMultiFilterEnabled = gos.isModuleRegistered("MultiFilter"); const cellDataType = dataTypeSvc?.getBaseDataType(column); const simpleFilter = _getDefaultSimpleFilter2(cellDataType, false); return [ { filter: simpleFilter }, { filter: "agSetColumnFilter" }, ...isMultiFilterEnabled ? [ { filter: "agMultiColumnFilter" } ] : [] ]; } }; // packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/wrapperToolPanel.ts import { Component as Component51, _warn as _warn37 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterPanel.ts import { Component as Component50, FilterButtonComp as FilterButtonComp2, RefPlaceholder as RefPlaceholder43, _focusInto as _focusInto8, _getActiveDomElement as _getActiveDomElement14, _isNothingFocused as _isNothingFocused4, _removeFromParent as _removeFromParent11, _translateForFilter } from "ag-grid-community"; // packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/addFilterComp.ts import { Component as Component46, _clearElement as _clearElement17, _createElement as _createElement15, _createIconNoSpan as _createIconNoSpan23 } from "ag-grid-community"; var AddFilterElement = { tag: "div", cls: "ag-filter-card ag-filter-card-add" }; var AddFilterComp = class extends Component46 { 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() { _clearElement17(this.getGui()); this.destroySelect(); const eButton = _createElement15({ tag: "button", cls: "ag-button ag-standard-button ag-filter-add-button", children: [ { tag: "span", children: [() => _createIconNoSpan23("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() { _clearElement17(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 import { Component as Component49, RefPlaceholder as RefPlaceholder42, _clearElement as _clearElement18, _createIcon as _createIcon3, _removeFromParent as _removeFromParent10, _setAriaControls, _setAriaExpanded as _setAriaExpanded11, _setAriaLabel as _setAriaLabel19, _setDisplayed as _setDisplayed22 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterDetailComp.ts import { AgSelectSelector, Component as Component47, RefPlaceholder as RefPlaceholder41, _removeFromParent as _removeFromParent9 } from "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 Component47 { constructor() { super(...arguments); this.eFilterType = RefPlaceholder41; } postConstruct() { const eFilterTypeParams = { onValueChange: (filterDef) => this.dispatchLocalEvent({ type: "filterTypeChanged", filterDef }) }; this.setTemplate(FilterDetailElement, [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) { _removeFromParent9(oldDetail); afterGuiDetached(); } this.appendChild(newDetail); afterGuiAttached({ container: "newFiltersToolPanel", suppressFocus: true }); } } }; // packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/filterSummaryComp.ts import { Component as Component48 } from "ag-grid-community"; var FilterSummaryElement = { tag: "div", cls: "ag-filter-card-summary", attrs: { "aria-hidden": "true" } }; var FilterSummaryComp = class extends Component48 { 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 Component49 { constructor(id) { super(FilterCardElement); this.id = id; this.eTitle = RefPlaceholder42; this.eExpand = RefPlaceholder42; this.eDelete = RefPlaceholder42; this.eExpandIcon = RefPlaceholder42; this.eDeleteIcon = RefPlaceholder42; this.eEditing = RefPlaceholder42; } postConstruct() { const { beans, eDelete, eExpand, eDeleteIcon, eEditing, id } = this; const filterPanelService = beans.filterPanelSvc; _setAriaLabel19(eDelete, translateForFilterPanel(this, "ariaLabelFilterCardDelete")); eDeleteIcon.appendChild(_createIcon3("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(_createIcon3("filterCardEditing", beans, null)); } refresh(newState) { const { eExpand, eEditing, state: oldState, beans } = this; this.state = newState; const { name, expanded, isEditing } = newState; this.eTitle.textContent = name; _setDisplayed22(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")}`; } _setAriaLabel19(eExpand, ariaLabel); const removeComp = (comp) => { if (!comp) { return; } _removeFromParent10(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; _setAriaControls(eExpand, detailId); } else { this.detailComp = removeComp(this.detailComp); this.summaryComp = createOrRefreshComp(this.summaryComp, FilterSummaryComp); _setAriaControls(eExpand, null); } } toggleExpand(state) { const expanded = !!state.expanded; const { eExpandIcon, eExpand, beans } = this; _clearElement18(eExpandIcon); eExpandIcon.appendChild(_createIcon3(expanded ? "filterCardCollapse" : "filterCardExpand", beans, null)); _setAriaExpanded11(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 Component50 { constructor() { super(FilterPanelElement); this.eContainer = RefPlaceholder43; 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 = !_isNothingFocused4(beans); const activeElement = somethingIsFocused ? _getActiveDomElement14(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); for (const comp of compsToDestroy) { this.destroyBean(comp); } const activeId = params?.activeId; const activeItemToFocus = activeId && newFilters.get(activeId)?.getGui(); if (activeItemToFocus) { _focusInto8(activeItemToFocus); } else if (containerHasFocus && _isNothingFocused4(beans)) { _focusInto8(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: _translateForFilter(this, `${type}Filter`) })); if (!buttonComp) { buttonComp = this.createBean(new FilterButtonComp2({ className: "ag-filter-panel-buttons" })); this.getGui().appendChild(buttonComp.getGui()); const listeners = {}; for (const action of ["apply", "clear", "reset", "cancel"]) { listeners[action] = () => filterPanelSvc.doAction(action); } buttonComp.addManagedListeners(buttonComp, listeners); } buttonComp.updateButtons(buttons); buttonComp.updateValidity(canApply !== false); } else if (buttonComp) { _removeFromParent11(buttonComp.getGui()); buttonComp = this.destroyBean(buttonComp); } this.buttonComp = buttonComp; } destroy() { this.beans.filterPanelSvc?.clear?.(); 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{display:flex;flex:1;flex-direction:column;gap:var(--ag-widget-container-vertical-padding);overflow:auto;padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding) 0}.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;gap:var(--ag-spacing);padding-top:var(--ag-widget-vertical-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-buttons:where(:last-child),.ag-filter-panel-container: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{padding-bottom:var(--ag-widget-container-vertical-padding)}` ); // packages/ag-grid-enterprise/src/filterToolPanel/newFilterToolPanel/wrapperToolPanel.ts var WrapperToolPanel = class extends Component51 { constructor() { super(); this.registerCSS(newFiltersToolPanelCSS); } init(params) { if (!this.gos.get("enableFilterHandlers")) { _warn37(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, params.initialState); 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, _ColumnFilterModule4] }; 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", // loading async values richSelectLoading: "loading", // 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, _ColumnFilterModule4] }; // packages/ag-grid-enterprise/src/masterDetail/masterDetailModule.ts import { EventApiModule } from "ag-grid-community"; // packages/ag-grid-enterprise/src/masterDetail/detailCellRenderer.ts import { Component as Component52, RefPlaceholder as RefPlaceholder44, _getGridRegisteredModules, _missing as _missing5, _warn as _warn39, createGrid } from "ag-grid-community"; // packages/ag-grid-enterprise/src/masterDetail/detailCellRendererCtrl.ts import { BeanStub as BeanStub46, _addGridCommonParams as _addGridCommonParams23, _focusInto as _focusInto9, _isSameRow as _isSameRow2, _missing as _missing4, _warn as _warn38 } from "ag-grid-community"; var DetailCellRendererCtrl = class extends BeanStub46 { 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 = _isSameRow2(row, eventRow); if (!isSameRow) { return; } _focusInto9(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) { _warn38(170, { providedStrategy }); } this.refreshStrategy = "rows"; } createDetailGrid() { const { params, gos } = this; if (_missing4(params.detailGridOptions)) { _warn38(171); return; } const masterTheme = gos.get("theme"); const detailTheme = params.detailGridOptions.theme; if (detailTheme && detailTheme !== masterTheme) { _warn38(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, expansionSvc } } = 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 adjustDetailsOnExpandOrCollapseAll({ source }) { if (source === "expandAll") { return api.expandAll(); } if (source === "collapseAll") { return api.collapseAll(); } } 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); const sharedApiModuleName = "CsrmSsrmSharedApi"; const asAgModuleName = `${sharedApiModuleName}Module`; if (api.isModuleRegistered(asAgModuleName)) { masterGridApi.addEventListener("expandOrCollapseAll", adjustDetailsOnExpandOrCollapseAll); expansionSvc?.setDetailsExpansionState(api); } }); this.addManagedListeners(masterNode, { masterChanged: (event) => { if (!event.node.master) { this.onDestroy(gridInfo); } } }); this.addDestroyFunc(() => this.onDestroy(gridInfo)); } onDestroy(gridInfo) { const { params } = this; const rowNode = params.node; const masterGridApi = params.api; if (rowNode.detailGridInfo !== gridInfo) { return; } if (!masterGridApi.isDestroyed()) { masterGridApi.removeDetailGridInfo(rowNode.id); } 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) { _warn38(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: _addGridCommonParams23(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 Component52 { constructor() { super(...arguments); this.eDetailGrid = RefPlaceholder44; } 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 (_missing5(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 { _warn39(168); setDefaultTemplate(); } if (this.eDetailGrid == null) { _warn39(169); } } setDetailGrid(gridOptions) { if (!this.eDetailGrid) { return; } const parentFrameworkComponentWrapper = this.context.getBean("frameworkCompWrapper"); const frameworkCompWrapper = new DetailFrameworkComponentWrapper(parentFrameworkComponentWrapper); const { frameworkOverrides } = this.beans; const api = createGrid(this.eDetailGrid, gridOptions, { frameworkOverrides, providedBeanInstances: { frameworkCompWrapper }, modules: _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 import { BeanStub as BeanStub47, RowNode as RowNode3, _exists as _exists23, _getClientSideRowModel, _isClientSideRowModel as _isClientSideRowModel9, _isServerSideRowModel as _isServerSideRowModel3, _observeResize as _observeResize2 } from "ag-grid-community"; var MasterDetailService = class extends BeanStub47 { constructor() { super(...arguments); this.beanName = "masterDetailSvc"; this.store = {}; } isEnabled() { return this.gos.get("masterDetail"); } postConstruct() { const gos = this.gos; if (_isClientSideRowModel9(gos)) { this.enabled = this.isEnabled(); } if (_isServerSideRowModel3(gos)) { this.addEventListeners(); } } addEventListeners() { const rowNodeDataChanged = (event) => { this.setMaster(event.node, false, true); }; let removeListeners; const addOrRemoveListeners = () => { if (removeListeners) { for (const removeListener of removeListeners) { removeListener(); } removeListeners = void 0; } if (this.isEnabled()) { removeListeners = this.addManagedListeners(this.beans.eventSvc, { rowNodeDataChanged }); } }; addOrRemoveListeners(); this.gos.addPropertyEventListener("masterDetail", addOrRemoveListeners); } refreshModel(params) { if (params.changedProps) { const enabled = this.isEnabled(); if (this.enabled !== enabled) { this.setMasters(null); return; } } if (params.rowDataUpdated) { this.setMasters(params.changedRowNodes); } } setMaster(row, created, updated) { const oldMaster = row.master; const enabled = this.isEnabled(); let newMaster = enabled; const gos = this.gos; const isRowMaster = gos.get("isRowMaster"); const treeData = gos.get("treeData"); if (enabled) { if (created || updated) { if (isRowMaster) { const data = row.data; newMaster = !!data && !!isRowMaster(data); } } else { newMaster = oldMaster; } } const beans = this.beans; if (!treeData) { if (newMaster && created) { const level = beans.rowGroupColsSvc?.columns.length ?? 0; row.expanded = _getRowDefaultExpanded(beans, row, level, false); } else if (!newMaster && oldMaster) { row.expanded = false; } } if (newMaster !== oldMaster) { row.master = newMaster; row.dispatchRowEvent("masterChanged"); } } setMasters(changedRowNodes) { this.enabled = this.isEnabled(); if (changedRowNodes) { for (const node of changedRowNodes.updates) { this.setMaster(node, false, true); } for (const node of changedRowNodes.adds) { this.setMaster(node, true, false); } } else { const allLeafChildren = _getClientSideRowModel(this.beans)?.rootNode?._leafs; if (allLeafChildren) { for (let i = 0, len = allLeafChildren.length; i < len; ++i) { this.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 RowNode3(this.beans); detailNode.detail = true; detailNode.selectable = false; detailNode.parent = masterNode; if (_exists23(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 (_isClientSideRowModel9(gos, rowModel) || _isServerSideRowModel3(gos, rowModel)) { rowModel.onRowHeightChanged(); } }; window.setTimeout(updateRowHeightFunc, 0); } }; const resizeObserverDestroyFunc = _observeResize2(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, EventApiModule] }; // packages/ag-grid-enterprise/src/rangeSelection/rangeSelectionModule.ts import { _DragModule, _KeyboardNavigationModule as _KeyboardNavigationModule3 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rangeSelection/agFillHandle.ts import { _addGridCommonParams as _addGridCommonParams24, _getCellByPosition as _getCellByPosition2, _getFillHandle, _getLastRow, _getNormalisedMousePosition, _getRowAbove, _getRowBelow as _getRowBelow3, _getRowNode as _getRowNode6, _isRowBefore as _isRowBefore3, _isSameRow as _isSameRow3, _last as _last13, _stopPropagationForAgGrid as _stopPropagationForAgGrid9, _toStringOrNull as _toStringOrNull6, _warn as _warn40, isRowNumberCol as isRowNumberCol2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rangeSelection/abstractSelectionHandle.ts import { Component as Component53, _areCellsEqual, _getCellPositionForEvent, _getPageBody as _getPageBody2, _isRowBefore as _isRowBefore2, _isVisible as _isVisible7, _last as _last12, _setDisplayed as _setDisplayed23 } from "ag-grid-community"; var AbstractSelectionHandle = class extends Component53 { constructor() { super(...arguments); this.changedCalculatedValues = false; this.dragging = false; this.shouldDestroyOnEndDragging = false; } postConstruct() { this.beans.dragSvc.addDragSource({ dragStartPixels: 0, eElement: this.getGui(), onDragging: (e) => { let startingMove = false; if (!this.dragging) { startingMove = true; this.dragging = true; const pageBody = _getPageBody2(this.beans); pageBody.classList?.add(this.getDraggingCssClass()); } this.updateValuesOnMove(e); if (startingMove) { this.changedCalculatedValues = false; return; } this.beans.rangeSvc.autoScrollService.check(e); if (this.changedCalculatedValues) { this.onDrag(e); this.changedCalculatedValues = false; } }, onDragStop: (e) => { this.dragging = false; this.onDragEnd(e); this.clearDragProperties(); }, onDragCancel: () => { this.dragging = false; this.onDragCancel(); this.clearDragProperties(); } }); this.addManagedEventListeners({ cellSelectionChanged: this.updateLocalRangeIfNeeded.bind(this) }); this.addManagedElementListeners(this.getGui(), { pointerdown: stopEventPropagation, mousedown: stopEventPropagation }); } getLastCellHovered() { return this.lastCellHovered; } getDraggingCssClass() { return `ag-dragging-${this.type === 0 /* FILL */ ? "fill" : "range"}-handle`; } updateValuesOnMove(e) { const cell = _getCellPositionForEvent(this.gos, e); if (!cell || this.shouldSkipCell(cell) || this.lastCellHovered && _areCellsEqual(cell, this.lastCellHovered)) { return; } this.lastCellHovered = cell; this.changedCalculatedValues = true; } clearDragProperties() { this.clearValues(); this.beans.rangeSvc.autoScrollService.ensureCleared(); const pageBody = _getPageBody2(this.beans); pageBody.classList?.remove(this.getDraggingCssClass()); if (this.shouldDestroyOnEndDragging) { this.destroy(); } } getType() { return this.type; } refresh(cellCtrl, cellRange) { const oldCellComp = this.cellCtrl; const eGui = this.getGui(); const cellRangeToUse = cellRange ?? _last12(this.beans.rangeSvc.getCellRanges()); const start = cellRangeToUse.startRow; const end = cellRangeToUse.endRow; if (start && end) { const isBefore = _isRowBefore2(end, start); if (isBefore) { this.rangeStartRow = end; this.rangeEndRow = start; } else { this.rangeStartRow = start; this.rangeEndRow = end; } } if (oldCellComp !== cellCtrl || !_isVisible7(eGui)) { this.cellCtrl = cellCtrl; const eParentOfValue = cellCtrl.comp.getParentOfValue(); if (eParentOfValue) { eParentOfValue.appendChild(eGui); } } this.cellRange = cellRangeToUse; } clearValues() { this.lastCellHovered = void 0; } destroy() { if (!this.shouldDestroyOnEndDragging && this.dragging) { _setDisplayed23(this.getGui(), false); this.shouldDestroyOnEndDragging = true; return; } this.shouldDestroyOnEndDragging = false; super.destroy(); this.getGui()?.remove(); } updateLocalRangeIfNeeded(event) { if (!this.cellRange) { return; } const { id, type } = this.cellRange; if (!id || id !== event.id) { return; } const newRange = this.beans.rangeSvc?.getCellRanges().find((range) => range.id === id && range.type === type); if (newRange && newRange !== this.cellRange) { this.cellRange = newRange; } } }; var stopEventPropagation = (e) => { e.stopPropagation(); }; // 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) { _stopPropagationForAgGrid9(e); const { cellRange: initialRange, rangeStartRow, beans } = this; const { rangeSvc, visibleCols } = beans; const lastRow = _getLastRow(beans); if (!lastRow) { return; } const fillHandleDirection = this.getFillHandleDirection(); this.dragAxis = fillHandleDirection === "xy" ? "y" : fillHandleDirection; const finalRange = rangeSvc?.createCellRangeFromCellRangeParams({ rowStartIndex: rangeStartRow.rowIndex, rowStartPinned: rangeStartRow.rowPinned, columnStart: initialRange.columns[0], rowEndIndex: this.dragAxis === "x" ? initialRange.endRow?.rowIndex ?? null : lastRow.rowIndex, rowEndPinned: this.dragAxis === "x" ? initialRange.endRow?.rowPinned : lastRow.rowPinned, columnEnd: this.dragAxis === "x" ? _last13(visibleCols.allCols) : _last13(initialRange.columns) }); 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 = _getNormalisedMousePosition(this.beans, e); } const { x, y } = this.initialXY; const { x: newX, y: newY } = _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 isRowNumberCol2(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 = _getFillHandle(this.gos)?.direction; if (!direction) { return "xy"; } if (direction !== "x" && direction !== "y" && direction !== "xy") { _warn40(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 && !_getFillHandle(gos)?.suppressClearOnFillReduction) { const columns = isVertical ? initialRange.columns : initialRange.columns.filter((col) => finalRange.columns.indexOf(col) < 0); const startRow = isVertical ? _getRowBelow3(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 = _getRowNode6(beans, currentRow); if (!rowNode) { break; } if (isVertical && column) { fillValues( values, column, rowNode, () => !_isSameRow3(currentRow, this.isUp ? initialRangeStartRow : initialRangeEndRow) ); } else if (columns) { withinInitialRange = true; resetValues(); for (const col of columns) { fillValues( values, col, rowNode, () => col !== (this.isLeft ? initialRange.columns[0] : _last13(initialRange.columns)) ); } } finished = _isSameRow3(currentRow, this.isUp ? finalRangeStartRow : finalRangeEndRow); currentRow = this.isUp ? _getRowAbove(this.beans, currentRow) : _getRowBelow3(beans, currentRow); } }; const fillValues = (currentValues, col, rowNode, updateInitialSet) => { let currentValue; let skipValue = false; if (withinInitialRange) { currentValue = valueSvc.getValue(col, rowNode, "edit"); initialValues.push(currentValue); initialNonAggregatedValues.push(valueSvc.getValue(col, rowNode, "edit", true)); initialFormattedValues.push( valueSvc.getValueForDisplay({ column: col, node: rowNode, from: "edit" }).valueFormatted ); 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, "edit"); if (!fromUserFunction) { if (sourceCol) { const sourceColDef = sourceCol.getColDef(); if (sourceColDef.useValueFormatterForExport !== false && sourceColDef.valueFormatter) { const formattedValue = valueSvc.getValueForDisplay({ column: sourceCol, node: sourceRowNode, includeValueFormatted: true, from: "edit" }).valueFormatted; 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 : _toStringOrNull6(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], restoreSourceInBatch: true }); } processValues(params) { const { formula, valueSvc } = this.beans; const { event, values, initialValues, initialNonAggregatedValues, initialFormattedValues, col, rowNode, idx } = params; const userFillOperation = _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 = _addGridCommonParams24(this.gos, { event, values: values.map(({ value }) => value), initialValues, initialNonAggregatedValues, initialFormattedValues, currentIndex: idx, currentCellValue: valueSvc.getValue(col, rowNode, "edit"), direction, column: col, rowNode }); const userResult = userFillOperation(params2); if (userResult !== false) { return { value: userResult, fromUserFunction: true }; } } const isNumeric = (v) => typeof v === "number" && Number.isFinite(v) || typeof v === "string" && /^[+-]?\d+(?:\.\d+)?$/.test(v.trim()); const allNumbers = values.every(({ value }) => isNumeric(value)); if (event.altKey || !allNumbers) { const valueForFunctions = String(_last13(values)?.value ?? ""); if (allNumbers && initialValues.length === 1) { const multiplier = this.isUp || this.isLeft ? -1 : 1; return { value: parseFloat(valueForFunctions) + 1 * multiplier, fromUserFunction: false }; } const { value: cyclicValue, column: sourceCol, rowNode: sourceRowNode } = values[idx % values.length]; let processedValue; const fromFormula = sourceCol.isAllowFormula() && formula?.isFormula(valueForFunctions); if (fromFormula) { const rowDelta = direction === "up" ? -1 : direction === "down" ? 1 : 0; const columnDelta = direction === "left" ? -1 : direction === "right" ? 1 : 0; processedValue = formula.updateFormulaByOffset({ value: valueForFunctions, rowDelta, columnDelta }); } else { processedValue = cyclicValue; } return { value: processedValue, fromUserFunction: false, sourceCol: fromFormula ? void 0 : sourceCol, sourceRowNode }; } return { value: _last13(findLineByLeastSquares(values.map(({ value }) => Number(value)))), fromUserFunction: false }; } clearValues() { this.clearMarkedPath(); this.clearCellValues(); this.lastCellMarked = void 0; super.clearValues(); } clearMarkedPath() { for (const cell of this.markedCells) { if (!cell.isAlive()) { continue; } 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 (_isSameRow3(currentPosition, initialPosition)) { return; } const isBefore = _isRowBefore3(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 = _isSameRow3(row, initialPosition); if (isMovingUp) { this.isUp = true; } if (!isInitialRow) { const cell = _getCellByPosition2(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", _isSameRow3(row, endPosition) ); } } } if (_isSameRow3(row, endPosition)) { break; } } while ( // tslint:disable-next-line row = isMovingUp ? _getRowAbove(this.beans, row) : _getRowBelow3(beans, row) ); } reduceVertical(initialPosition, endPosition) { let row = initialPosition; const beans = this.beans; do { const cellRange = this.cellRange; const colLen = cellRange.columns.length; const isLastRow = _isSameRow3(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 = _getCellByPosition2(beans, celPos); if (cell) { this.markedCells.push(cell); cell.comp.toggleCss("ag-selection-fill-bottom", _isSameRow3(row, endPosition)); } } if (isLastRow) { break; } } while (row = _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; for (const column of colsToMark) { let row = rangeStartRow; let isLastRow = false; do { isLastRow = _isSameRow3(row, rangeEndRow); const cell = _getCellByPosition2(beans, { rowIndex: row.rowIndex, rowPinned: row.rowPinned, column }); if (cell) { this.markedCells.push(cell); const cellComp = cell.comp; cellComp.toggleCss("ag-selection-fill-top", _isSameRow3(row, rangeStartRow)); cellComp.toggleCss("ag-selection-fill-bottom", _isSameRow3(row, rangeEndRow)); if (isMovingLeft) { this.isLeft = true; cellComp.toggleCss("ag-selection-fill-left", column === colsToMark[0]); } else { cellComp.toggleCss("ag-selection-fill-right", column === _last13(colsToMark)); } } row = _getRowBelow3(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; for (const column of colsToMark) { let row = rangeStartRow; let isLastRow = false; do { isLastRow = _isSameRow3(row, rangeEndRow); const cell = _getCellByPosition2(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 = _getRowBelow3(beans, row); } while (!isLastRow); } } refresh(cellCtrl, cellRange) { const cellRangeToUse = cellRange ?? this.beans.rangeSvc.getCellRanges()[0]; const isColumnRange = !cellRangeToUse.startRow || !cellRangeToUse.endRow; if (isColumnRange) { this.destroy(); return; } super.refresh(cellCtrl, cellRangeToUse); } }; // packages/ag-grid-enterprise/src/rangeSelection/agRangeHandle.ts import { CellRangeType, _isSameRow as _isSameRow4, _last as _last14 } from "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 targetRange = this.cellRange ?? _last14(rangeSvc.getCellRanges()); if (!targetRange) { return; } if (!this.rangeFixed) { this.fixRangeStartEnd(targetRange); this.rangeFixed = true; } this.endPosition = { rowIndex: lastCellHovered.rowIndex, rowPinned: lastCellHovered.rowPinned, column: lastCellHovered.column }; if (rangeSvc.getCellRanges().length === 2 && rangeSvc.getCellRanges()[0].type === CellRangeType.DIMENSION && targetRange.type === CellRangeType.VALUE) { const rowChanged = !_isSameRow4(this.endPosition, rangeSvc.getRangeEndRow(targetRange)); if (rowChanged) { rangeSvc.updateRangeRowBoundary({ cellRange: rangeSvc.getCellRanges()[0], boundary: "end", cellPosition: { ...this.endPosition, column: rangeSvc.getCellRanges()[0].columns[0] }, silent: true }); } } rangeSvc.extendRangeToCell(targetRange, this.endPosition); } shouldSkipCell(_) { return false; } onDragEnd(_) { const cellRange = this.cellRange ?? _last14(this.beans.rangeSvc.getCellRanges()); if (!cellRange) { return; } 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.ag-formula-range,.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.ag-formula-range,.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.ag-formula-range,.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.ag-formula-range,.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 import { AutoScrollService as AutoScrollService2, BeanStub as BeanStub51, KeyCode as KeyCode31, _areCellsEqual as _areCellsEqual2, _areEqual as _areEqual3, _exists as _exists24, _getAbsoluteRowIndex, _getCellCtrlForEventTarget, _getEnableColumnSelection, _getFirstRow as _getFirstRow2, _getLastRow as _getLastRow2, _getRowAbove as _getRowAbove2, _getRowBelow as _getRowBelow4, _getRowCtrlForEventTarget, _getRowNode as _getRowNode7, _getSuppressMultiRanges, _interpretAsRightClick as _interpretAsRightClick2, _isCellSelectionEnabled as _isCellSelectionEnabled2, _isDomLayout, _isRowBefore as _isRowBefore4, _isSameRow as _isSameRow6, _isUsingNewCellSelectionAPI, _last as _last16, _makeNull as _makeNull8, _missing as _missing7, _removeAllFromArray as _removeAllFromArray2, _removeFromArray as _removeFromArray7, _warn as _warn41 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/rangeSelection/cellRangeFeature.ts import { CellRangeType as CellRangeType2, _isSameRow as _isSameRow5, _last as _last15, _missing as _missing6, _setAriaSelected as _setAriaSelected2 } from "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.rangeColorClass = null; this.handleColorClass = null; this.rangeSvc = beans.rangeSvc; } setComp(cellComp) { this.cellComp = cellComp; this.eGui = this.cellCtrl.eGui; this.onCellSelectionChanged(); } unsetComp() { this.beans.context.destroyBean(this.selectionHandle); } 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); _setAriaSelected2(eGui, rangeCount > 0 ? true : void 0); cellComp.toggleCss(CSS_CELL_RANGE_SINGLE_CELL, this.isSingleCell()); this.updateRangeBorders(); this.refreshRangeStyleAndHandle(); } 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) => [CellRangeType2.DIMENSION, CellRangeType2.VALUE].includes(range.type)); } updateRangeBordersIfRangeCount() { if (this.rangeCount > 0) { this.updateRangeBorders(); this.refreshRangeStyleAndHandle(); } } 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 && _isSameRow5(startRow, cellPosition)) { top = true; } if (!bottom && _isSameRow5(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 }; } refreshRangeStyleAndHandle() { const { context } = this.beans; if (context.isDestroyed()) { return; } this.styleCellForRangeType(); const rangeForHandle = this.getRangeForHandle(); if (this.selectionHandle && !rangeForHandle) { this.selectionHandle = context.destroyBean(this.selectionHandle); } if (rangeForHandle) { this.addSelectionHandle(rangeForHandle); } this.refreshHandleColor(rangeForHandle); this.cellComp.toggleCss(CSS_CELL_RANGE_HANDLE, !!this.selectionHandle); } styleCellForRangeType() { if (this.hasChartRange) { const { rangeSvc } = this; const dimensionRange = rangeSvc.getCellRanges()[0]; const hasCategoryRange = dimensionRange.type === CellRangeType2.DIMENSION; const isCategoryCell = hasCategoryRange && rangeSvc.isCellInSpecificRange(this.cellCtrl.cellPosition, dimensionRange); this.cellComp.toggleCss(CSS_CELL_RANGE_CHART_CATEGORY, isCategoryCell); } else { this.cellComp.toggleCss(CSS_CELL_RANGE_CHART_CATEGORY, false); this.applyRangeColor(this.getRangeColorClass()); } } applyRangeColor(nextClass) { if (this.rangeColorClass && this.rangeColorClass !== nextClass) { this.cellComp.toggleCss(this.rangeColorClass, false); this.cellComp.toggleCss("ag-formula-range", false); } if (nextClass) { this.cellComp.toggleCss(nextClass, true); this.cellComp.toggleCss("ag-formula-range", nextClass.startsWith("ag-formula-range")); } this.rangeColorClass = nextClass ?? null; } getRangeColorClass() { const { rangeSvc, rangeCount } = this; if (!rangeSvc || !rangeCount) { return null; } const ranges = rangeSvc.getCellRanges(); for (let i = ranges.length - 1; i >= 0; i--) { const range = ranges[i]; const colorClass = range.colorClass; if (!colorClass) { continue; } if (rangeSvc.isCellInSpecificRange(this.cellCtrl.cellPosition, range)) { return colorClass; } } return null; } refreshHandleColor(rangeForHandle) { const handleGui = this.selectionHandle?.getGui?.(); const nextClass = rangeForHandle?.colorClass ?? null; if (!handleGui) { this.handleColorClass = null; return; } if (this.handleColorClass && this.handleColorClass !== nextClass) { handleGui.classList.remove(this.handleColorClass); } if (nextClass) { handleGui.classList.add(nextClass); } else if (this.handleColorClass) { handleGui.classList.remove(this.handleColorClass); } this.handleColorClass = nextClass ?? null; } getRangeForHandle() { const { gos, editSvc } = this.beans; const rangeSvc = this.rangeSvc; const allRanges = rangeSvc.getCellRanges(); const rangesLen = allRanges.length; if (this.rangeCount < 1 || rangesLen < 1) { return null; } const isRangeSelectionEnabledWhileEditing = editSvc?.isRangeSelectionEnabledWhileEditing(); const rangesToRefreshHandle = isRangeSelectionEnabledWhileEditing ? allRanges : [_last15(allRanges)]; for (const cellRange of rangesToRefreshHandle) { 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 = !isCellEditing && (isRangeSelectionEnabledWhileEditing || rangesLen === 1 && (isFillHandleAvailable || isRangeHandleAvailable)); if (this.hasChartRange) { handleIsAvailable = cellRange.type === CellRangeType2.VALUE; } if (handleIsAvailable && cellRange.endRow != null && rangeSvc.isContiguousRange(cellRange) && rangeSvc.isBottomRightCell(cellRange, cellPosition)) { return cellRange; } } return null; } addSelectionHandle(cellRange) { const { beans } = this; const isRangeSelectionEnabledWhileEditing = beans.editSvc?.isRangeSelectionEnabledWhileEditing(); const cellRangeType = cellRange.type; const selectionHandleFill = !isRangeSelectionEnabledWhileEditing && _isFillHandleEnabled(beans.gos) && _missing6(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, cellRange); } destroy() { this.unsetComp(); } }; // packages/ag-grid-enterprise/src/rangeSelection/dragListenerFeature.ts import { BeanStub as BeanStub48, _isCellSelectionEnabled } from "ag-grid-community"; var DragListenerFeature = class extends BeanStub48 { 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 (_isCellSelectionEnabled(gos)) { enableFeature(); } else { disableFeature(); } }); this.addDestroyFunc(disableFeature); if (_isCellSelectionEnabled(gos)) { enableFeature(); } } }; // packages/ag-grid-enterprise/src/rangeSelection/headerGroupCellMouseListenerFeature.ts import { BeanStub as BeanStub49 } from "ag-grid-community"; var HeaderGroupCellMouseListenerFeature = class extends BeanStub49 { constructor(column, eGui) { super(); this.column = column; this.eGui = eGui; } postConstruct() { this.addManagedElementListeners(this.eGui, { click: (e) => e && this.onClick(e) }); } onClick(event) { this.beans.rangeSvc?.handleColumnSelection(this.column, event); } }; // packages/ag-grid-enterprise/src/rangeSelection/rangeHeaderHighlightFeature.ts import { BeanStub as BeanStub50 } from "ag-grid-community"; var RangeHeaderHighlightFeature = class extends BeanStub50 { 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 BeanStub51 { constructor() { super(...arguments); this.beanName = "rangeSvc"; this.rangeSelectionExtensions = []; this.cellRanges = []; this.bodyScrollListener = this.onBodyScroll.bind(this); this.dragging = false; /** When dragging ends, the current range will be used to intersect all other ranges */ this.intersectionRange = false; this.columnRangeSelectionCtx = {}; } 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; } 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 AutoScrollService2({ 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: () => !_isDomLayout(this.gos, "normal"), shouldSkipHorizontalScroll: () => !gridBodyCtrl.scrollFeature.isHorizontalScrollShowing() }); }); } registerRangeSelectionExtension(extension) { if (this.rangeSelectionExtensions.includes(extension)) { return; } this.rangeSelectionExtensions.push(extension); } unregisterRangeSelectionExtension(extension) { _removeFromArray7(this.rangeSelectionExtensions, extension); } shouldSuppressRangeSelection(eventTarget) { return this.rangeSelectionExtensions.some((extension) => extension.shouldSuppressRangeSelection?.(eventTarget)); } shouldSkipColumn(column) { return this.rangeSelectionExtensions.some((extension) => extension.shouldSkipColumn?.(column)); } isAllColumnsSelectionCell(cellPosition) { return this.rangeSelectionExtensions.some((extension) => extension.isAllColumnsSelectionCell?.(cellPosition)); } isAllColumnsRange(range, allColumns) { return this.rangeSelectionExtensions.some((extension) => extension.isAllColumnsRange?.(range, allColumns)); } updateSelectionModeForCell(cellPosition) { this.setSelectionMode(this.isAllColumnsSelectionCell(cellPosition)); } // Drag And Drop Target Methods onDragStart(mouseEvent) { const gos = this.gos; const target = mouseEvent.target; if (!_isCellSelectionEnabled2(gos) || _getRowCtrlForEventTarget(gos, target)?.isSuppressMouseEvent(mouseEvent)) { return; } if (this.shouldSuppressRangeSelection(target)) { return; } const { shiftKey } = mouseEvent; const isMultiRange = this.isMultiRange(mouseEvent); const extendRange = shiftKey && !!this.cellRanges?.length; if (!isMultiRange && (!extendRange || _exists24(_last16(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 = isMultiRange && this.getCellRangeCount(this.lastCellHovered) > 1; if (!extendRange) { this.setNewestRangeStartCell(this.lastCellHovered); } if (this.cellRanges.length > 0) { this.draggingRange = _last16(this.cellRanges); } else { const mouseRowPosition = { rowIndex: this.lastCellHovered.rowIndex, rowPinned: this.lastCellHovered.rowPinned }; const columns = this.getColumnsFromModel([this.lastCellHovered.column]); if (!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 and column visibility events onColumnsChanged() { this.refreshLastRangeStart(); const allColumns = this.visibleCols.allCols; for (const cellRange of this.cellRanges) { const beforeCols = cellRange.columns; cellRange.columns = cellRange.columns.filter( (col) => col.isVisible() && allColumns.indexOf(col) !== -1 ); const colsInRangeChanged = !_areEqual3(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 = _last16(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 _last16(allPositions) - allPositions[0] + 1 === rangeColumns.length; } getRangeStartRow(cellRange) { if (cellRange.startRow && cellRange.endRow) { return _isRowBefore4(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 _isRowBefore4(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 }; } getRangeRowCount(cellRange) { const beans = this.beans; const start = this.getRangeStartRow(cellRange); const end = this.getRangeEndRow(cellRange); const startIndex = _getAbsoluteRowIndex(beans, start); const endIndex = _getAbsoluteRowIndex(beans, end); return endIndex - startIndex + 1; } handleCellMouseDown(event, cell) { const { beans } = this; const target = event.target; if (this.shouldSuppressRangeSelection(target)) { return; } const isAllColumnsCell = this.isAllColumnsSelectionCell(cell); if (isAllColumnsCell) { event.preventDefault(); } if (event.shiftKey) { return this.extendLatestRangeToCell(cell); } if (isAllColumnsCell && _interpretAsRightClick2(beans, event)) { return; } const isMultiRange = this.isMultiRange(event); this.updateSelectionModeForCell(cell); const columns = this.calculateColumnsBetween(cell.column, cell.column); if (!columns) { return; } const containingRange = isAllColumnsCell ? this.findContainingRange({ columns, startRow: cell, endRow: cell }) : void 0; const isMultiRangeRemoval = isAllColumnsCell && !!containingRange && isMultiRange && (event.ctrlKey || event.metaKey); if (isMultiRangeRemoval && containingRange) { this.removeRowFromAllColumnsRange(cell, containingRange); } else { this.setRangeToCell(cell, isMultiRange); } } isMultiRange(event) { const { ctrlKey, metaKey } = event; const { editingWithRanges, allowMulti } = this.getMultiRangeContext(); const isMultiKey = ctrlKey || metaKey; return editingWithRanges || (allowMulti ? isMultiKey : false); } getMultiRangeContext() { const { gos, editSvc } = this.beans; const editingWithRanges = !!editSvc?.isEditing() && !!editSvc?.isRangeSelectionEnabledWhileEditing(); const suppressMultiRanges = _getSuppressMultiRanges(gos) && !editingWithRanges; return { editingWithRanges, suppressMultiRanges, allowMulti: !suppressMultiRanges }; } removeRowFromAllColumnsRange(cell, containingRange) { const { beans, cellRanges } = this; const firstRow = _getFirstRow2(beans); const lastRow = _getLastRow2(beans); const startRow = this.getRangeStartRow(containingRange); const endRow = this.getRangeEndRow(containingRange); if (!startRow && _isSameRow6(firstRow, cell)) { replaceEdgeRow(containingRange, _getRowBelow4(beans, firstRow), "top"); } else if (!endRow && _isSameRow6(lastRow, cell)) { replaceEdgeRow(containingRange, _getRowAbove2(beans, lastRow), "bottom"); } else if (_isSameRow6(startRow, endRow)) { _removeFromArray7(cellRanges, containingRange); } else if (_isSameRow6(startRow, cell)) { replaceEdgeRow(containingRange, _getRowBelow4(beans, cell), "top"); } else if (_isSameRow6(endRow, cell)) { replaceEdgeRow(containingRange, _getRowAbove2(beans, cell), "bottom"); } else { const rowAbove = _getRowAbove2(beans, cell); const rowBelow = _getRowBelow4(beans, cell); containingRange.startRow = startRow; containingRange.endRow = rowAbove ?? void 0; cellRanges.push({ ...containingRange, startRow: rowBelow ?? void 0, endRow }); } this.dispatchChangedEvent(true, true); } setRangeToCell(cell, appendRange = false) { const { gos } = this; if (!_isCellSelectionEnabled2(gos)) { return; } this.updateSelectionModeForCell(cell); const columns = this.calculateColumnsBetween(cell.column, cell.column); if (!columns) { return; } const { suppressMultiRanges } = this.getMultiRangeContext(); if (suppressMultiRanges || !appendRange || _missing7(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); } getRangeLastColumn(cellRange) { const firstCol = cellRange.columns[0]; const lastCol = _last16(cellRange.columns); return this.newestRangeStartCell?.column === firstCol ? lastCol : firstCol; } extendRangeRowCountBy(cellRange, targetCount) { const { beans } = this; const { startRow, endRow } = cellRange; if (!startRow || !endRow) { return; } let stepsMoved = 0; let currentRow; const isBottomUp = _isRowBefore4(endRow, startRow); if (isBottomUp) { currentRow = startRow; } else { currentRow = endRow; } const stepFn = targetCount > 0 ? _getRowBelow4 : _getRowAbove2; const stepCount = Math.abs(targetCount); while (stepsMoved < stepCount) { const nextRow = stepFn(beans, currentRow); if (!nextRow) { break; } currentRow = nextRow; stepsMoved++; } if (stepsMoved !== stepCount) { return; } const cellPosition = { ...currentRow, column: this.getRangeLastColumn(cellRange) }; this.updateRangeRowBoundary({ cellRange, boundary: isBottomUp ? "start" : "end", cellPosition }); } extendRangeColumnCountBy(cellRange, delta) { const { columns, startColumn } = cellRange; if (delta === 0) { return; } const allColumns = this.getColumnsFromModel(); if (!allColumns) { return; } const lastColumn = _last16(columns); const endColumn = startColumn === columns[0] ? lastColumn : columns[0]; if (!lastColumn || !endColumn) { return; } let startIdx = allColumns.indexOf(startColumn); const endIdx = allColumns.indexOf(endColumn); const isRtlRange = endIdx < startIdx; if (isRtlRange) { startIdx = endIdx; } const currentLength = columns.length; const targetLength = currentLength + delta; if (targetLength <= 0) { return; } const newColumns = []; for (let i = startIdx; i < startIdx + targetLength; i++) { const col = allColumns[i]; if (!col) { break; } newColumns.push(col); } if (newColumns.length === targetLength) { if (isRtlRange) { const newColumnToFocus = _last16(newColumns); cellRange.startColumn = newColumnToFocus; this.focusCellOnNewColumn(cellRange, newColumnToFocus); } cellRange.columns = newColumns; this.dispatchChangedEvent(true, true, cellRange.id); } } extendLatestRangeToCell(cellPosition) { if (this.isEmpty() || !this.newestRangeStartCell) { return; } const cellRange = _last16(this.cellRanges); this.updateSelectionModeForCell(cellPosition); this.updateRangeRowBoundary({ cellRange, boundary: "end", cellPosition }); } extendRangeToCell(cellRange, cellPosition) { if (!cellRange) { return; } this.updateSelectionModeForCell(cellPosition); this.updateRangeRowBoundary({ cellRange, boundary: "end", cellPosition }); } updateRangeRowBoundary(params) { const { cellRange, boundary, cellPosition, silent = false } = params; const endColumn = cellPosition.column; const colsToAdd = this.calculateColumnsBetween(cellRange.startColumn, endColumn); if (!colsToAdd || isLastCellOfRange(cellRange, cellPosition)) { return; } if (boundary === "start") { this.focusCellOnNewRow(cellRange, cellPosition); } cellRange.columns = colsToAdd; cellRange[boundary === "start" ? "startRow" : "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[_last16(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 = _last16(this.cellRanges); const startCell = this.newestRangeStartCell; const endCellIndex = lastRange.endRow.rowIndex; const endCellFloating = lastRange.endRow.rowPinned; const endCellColumn = this.getRangeLastColumn(lastRange); 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 (!_isCellSelectionEnabled2(this.gos)) { return; } this.removeAllCellRanges(true); this.addCellRange(params); } setCellRanges(cellRanges) { if (_areEqual3(this.cellRanges, cellRanges)) { return; } if (!this.verifyCellRanges(this.gos)) { return; } this.setSelectionMode(false); this.removeAllCellRanges(true); const allDataColumns = this.getColumnsFromModel(this.visibleCols.allCols) ?? []; let hasAllColumnsRange = false; 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] }); } if (!hasAllColumnsRange && allDataColumns.length > 0 && this.isAllColumnsRange(cellRange, allDataColumns)) { hasAllColumnsRange = true; } this.cellRanges.push(cellRange); } this.setSelectionMode(hasAllColumnsRange); this.dispatchChangedEvent(false, true); } clearCellRangeCellValues(params) { const { beans, eventSvc } = this; const { cellEventSource = "rangeSvc", dispatchWrapperEvents, wrapperEventSource = "deleteKey", restoreSourceInBatch } = params; let { cellRanges } = params; if (dispatchWrapperEvents) { eventSvc.dispatchEvent({ type: "cellSelectionDeleteStart", source: wrapperEventSource }); eventSvc.dispatchEvent({ type: "rangeDeleteStart", source: wrapperEventSource }); } if (!cellRanges) { cellRanges = this.cellRanges; } const { valueSvc, editSvc } = beans; const batch = !!editSvc?.isBatchEditing(); this.forEachEditableCellInRanges(cellRanges, (rowNode, column) => { if (restoreSourceInBatch && batch) { editSvc?.batchResetToSourceValue({ rowNode, column }); return; } const deleteValue = valueSvc.getDeleteValue(column, rowNode); rowNode.setDataValue(column, deleteValue, 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 = createRowPosition(rowStartIndex, rowStartPinned); const endRow = createRowPosition(rowEndIndex, rowEndPinned); return { startRow, endRow, columns, startColumn: this.getColumnFromModel(columnStart) ?? (startsOnTheRight ? _last16(columns) : columns[0]) }; } addCellRange(params) { const gos = this.gos; if (!_isCellSelectionEnabled2(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); return newRange; } } 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; } for (const range of this.cellRanges) { 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?.includes(cell.column); const rowInRange = this.isRowInRange(cell, range); return columnInRange && rowInRange; } isColumnInAnyRange(column) { const { beans } = this; const firstRow = _getFirstRow2(beans); const lastRow = _getLastRow2(beans); if (!firstRow || !lastRow) { return false; } const columns = column.isColumn ? [column] : column.getDisplayedLeafColumns(); return this.findContainingRange({ columns, startRow: firstRow, endRow: lastRow }, true) != null; } findContainingRange({ columns, startRow, endRow }, matchOnly = false) { const ranges = this.cellRanges; for (let i = ranges.length - 1; i >= 0; i--) { const range = ranges[i]; const hasCols = columns.every((c) => range.columns.includes(c)); let condition = false; if (matchOnly) { condition = _isSameRow6(range.startRow, startRow) && _isSameRow6(range.endRow, endRow); } else { const isStartBeforeOrEqual = startRow && this.isRowInRange(startRow, range); const isEndAfterOrEqual = endRow && this.isRowInRange(endRow, range); condition = !!isStartBeforeOrEqual && !!isEndAfterOrEqual; } if (hasCols && condition) { return range; } } } 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 = _isRowBefore4(startRow, endRow) ? endRow : startRow; const isRightColumn = allColumns.indexOf(cell.column) === _last16(allPositions); const isLastRow = cell.rowIndex === lastRow.rowIndex && _makeNull8(cell.rowPinned) === _makeNull8(lastRow.rowPinned); return isRightColumn && isLastRow; } // returns the number of ranges this cell is in getCellRangeCount(cell) { return this.cellRanges.filter((cellRange) => this.isCellInSpecificRange(cell, cellRange)).length; } isRowInRange(thisRow, cellRange) { const firstRow = this.getRangeStartRow(cellRange); const lastRow = this.getRangeEndRow(cellRange); const equalsFirstRow = _isSameRow6(thisRow, firstRow); const equalsLastRow = _isSameRow6(thisRow, lastRow); if (equalsFirstRow || equalsLastRow) { return true; } const afterFirstRow = !_isRowBefore4(thisRow, firstRow); const beforeLastRow = _isRowBefore4(thisRow, lastRow); return afterFirstRow && beforeLastRow; } intersectLastRange(fromMouseClick) { const { editingWithRanges, suppressMultiRanges } = this.getMultiRangeContext(); if (editingWithRanges || suppressMultiRanges || fromMouseClick && this.dragging || this.isEmpty()) { return; } const lastRange = _last16(this.cellRanges); const intersectionStartRow = this.getRangeStartRow(lastRange); const intersectionEndRow = this.getRangeEndRow(lastRange); const newRanges = []; for (const range of this.cellRanges.slice(0, -1)) { 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); continue; } if (_isRowBefore4(intersectionEndRow, startRow) || _isRowBefore4(endRow, intersectionStartRow)) { newRanges.push(range); continue; } const rangeCountBefore = newRanges.length; if (_isRowBefore4(startRow, intersectionStartRow)) { const top = { columns: [...cols], startColumn: lastRange.startColumn, startRow: { ...startRow }, endRow: _getRowAbove2(this.beans, intersectionStartRow) }; newRanges.push(top); } if (intersectCols.length > 0) { const middle = { columns: intersectCols, startColumn: intersectCols.includes(lastRange.startColumn) ? lastRange.startColumn : intersectCols[0], startRow: rowMax([{ ...intersectionStartRow }, { ...startRow }]), endRow: rowMin([{ ...intersectionEndRow }, { ...endRow }]) }; newRanges.push(middle); } if (_isRowBefore4(intersectionEndRow, endRow)) { newRanges.push({ columns: [...cols], startColumn: lastRange.startColumn, startRow: _getRowBelow4(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 === _last16(columns) && startColumn === right; if (shouldMoveRightCol) { moveColInCellRange(right, false); } } 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?.length) { startsOnTheRight = processedColumns[0] !== this.getColumnFromModel(columnA); } } return processedColumns ? { columns: processedColumns, startsOnTheRight } : void 0; } verifyCellRanges(gos) { const { suppressMultiRanges } = this.getMultiRangeContext(); const invalid = _isUsingNewCellSelectionAPI(gos) && suppressMultiRanges && this.cellRanges.length > 1; if (invalid) { _warn41(93); } return !invalid; } forEachRowInRange(cellRange, callback) { const topRow = this.getRangeStartRow(cellRange); const bottomRow = this.getRangeEndRow(cellRange); let currentRow = topRow; while (currentRow) { callback(currentRow); if (_isSameRow6(currentRow, bottomRow)) { break; } currentRow = _getRowBelow4(this.beans, currentRow); } } forEachEditableCellInRanges(cellRanges, callback) { const { beans } = this; for (const cellRange of cellRanges) { this.forEachRowInRange(cellRange, (rowPosition) => { const rowNode = _getRowNode7(beans, rowPosition); if (!rowNode) { return; } for (let i = 0; i < cellRange.columns.length; i++) { const column = this.getColumnFromModel(cellRange.columns[i]); if (!column?.isCellEditable(rowNode)) { continue; } callback(rowNode, column); } }); } } // as the user is dragging outside of the panel, the div starts to scroll, which in turn // means we are selecting more (or less) cells, but the mouse isn't moving, so we recalculate // the selection by mimicking a new mouse event onBodyScroll() { if (this.dragging && this.lastMouseEvent) { this.onDragging(this.lastMouseEvent); } } updateValuesOnMove(eventTarget) { const cellCtrl = _getCellCtrlForEventTarget(this.gos, eventTarget); const cell = cellCtrl?.cellPosition; this.cellHasChanged = false; if (!cell || this.lastCellHovered && _areCellsEqual2(cell, this.lastCellHovered)) { return; } const editSvc = this.beans.editSvc; const editing = editSvc?.isEditing(cellCtrl, { withOpenEditor: true }); if (editing && !editSvc?.isRangeSelectionEnabledWhileEditing()) { this.dragSvc.cancelDrag(eventTarget); return; } if (this.lastCellHovered) { this.cellHasChanged = true; } this.lastCellHovered = cell; } 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 { visibleCols, selectionMode } = this; if (!cols || selectionMode === 1 /* ALL_COLUMNS */) { cols = visibleCols.allCols; } const columns = []; for (const col of cols) { const column = this.getColumnFromModel(col); if (!column || this.shouldSkipColumn(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) { _warn41(178, { colId: fromColumn.getId() }); return; } const toIndex = isSameColumn ? fromIndex : allColumns.indexOf(toColumn); if (toIndex < 0) { _warn41(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; return this.getColumnsFromModel(allColumns.slice(firstIndex, lastIndex + 1)); } focusCellOnNewColumn(currentRange, column) { const { focusSvc } = this.beans; const focusedCell = focusSvc.getFocusedCell(); if (!focusedCell) { return; } if (this.isCellInSpecificRange(focusedCell, currentRange)) { focusSvc.setFocusedCell({ ...focusedCell, column, forceBrowserFocus: true, preventScrollOnBrowserFocus: true }); } } focusCellOnNewRow(currentRange, row) { const { focusSvc } = this.beans; const focusedCell = focusSvc.getFocusedCell(); if (!focusedCell) { return; } if (this.isCellInSpecificRange(focusedCell, currentRange)) { focusSvc.setFocusedCell({ ...row, column: focusedCell.column, forceBrowserFocus: true, preventScrollOnBrowserFocus: true }); } } createDragListenerFeature(eContainer) { return new DragListenerFeature(eContainer); } createCellRangeFeature(ctrl) { return new CellRangeFeature(this.beans, ctrl); } createHeaderGroupCellMouseListenerFeature(column, eGui) { return new HeaderGroupCellMouseListenerFeature(column, eGui); } /** * Handle a user clicking column header to (de)select one or more column of cells * CTRL-clicking for toggling column selection + CTRL-SHIFT-clicking supported for selecting ranges of columns */ handleColumnSelection(clickedColumn, event) { const { gos, beans, columnRangeSelectionCtx: ctx, cellRanges } = this; if (!_getEnableColumnSelection(gos)) { return; } const { suppressMultiRanges, editingWithRanges } = this.getMultiRangeContext(); const hasRanges = cellRanges.length > 0; const isMeta = event.ctrlKey || event.metaKey; const allowToggle = !editingWithRanges || isMeta; const firstRow = _getFirstRow2(beans); const lastRow = _getLastRow2(beans); if (!firstRow || !lastRow) { return; } if (event.key === KeyCode31.ENTER) { event.preventDefault(); } if (event.shiftKey) { const root = ctx.root; if (!root) { return; } const column = clickedColumn.isColumn ? clickedColumn : _last16(clickedColumn.getLeafColumns()); const range = this.findContainingRange({ columns: [root], startRow: firstRow, endRow: lastRow }, true); if (!range) { _removeFromArray7(cellRanges, ctx.lastCellRange); this.selectColumns(this.calculateColumnsBetween(root, column), firstRow, lastRow); return; } this.updateRangeRowBoundary({ cellRange: range, boundary: "end", cellPosition: { column, ...lastRow } }); return; } if (hasRanges && (suppressMultiRanges || !isMeta && !editingWithRanges)) { this.removeAllCellRanges(true); } const toggleColumns = (columns, root) => { const foundRange = this.findContainingRange({ columns, startRow: firstRow, endRow: lastRow }, true); if (foundRange && allowToggle) { this.deselectColumnsFromRange(foundRange, columns); } else { const addedRange = this.selectColumns(columns, firstRow, lastRow); if (addedRange) { ctx.lastCellRange = addedRange; } } ctx.root = root; }; if (clickedColumn.isColumn) { toggleColumns([clickedColumn], clickedColumn); } else { const leafCols = clickedColumn.getDisplayedLeafColumns(); toggleColumns(leafCols, leafCols[0]); } } deselectColumnsFromRange(range, columns) { _removeAllFromArray2(range.columns, columns); if (columns.includes(range.startColumn)) { range.startColumn = range.columns[0]; } if (range.columns.length === 0) { _removeFromArray7(this.cellRanges, range); } this.dispatchChangedEvent(true, true); } selectColumns(columns, startRow, endRow) { return this.addCellRange({ columns, columnStart: columns[0], columnEnd: _last16(columns), rowStartIndex: startRow.rowIndex, rowStartPinned: startRow.rowPinned, rowEndIndex: endRow.rowIndex, rowEndPinned: endRow.rowPinned }); } }; function createRowPosition(rowIndex, rowPinned) { return rowIndex != null ? { rowIndex, rowPinned } : void 0; } function rowMax(rows) { let max; for (const row of rows) { if (max === void 0 || _isRowBefore4(max, row)) { max = row; } } return max; } function rowMin(rows) { let min; for (const row of rows) { if (min === void 0 || _isRowBefore4(row, min)) { min = row; } } return min; } function isLastCellOfRange(cellRange, cell) { const { startRow, endRow } = cellRange; const lastRow = _isRowBefore4(startRow, endRow) ? endRow : startRow; const isLastRow = cell.rowIndex === lastRow.rowIndex && cell.rowPinned === lastRow.rowPinned; const rangeFirstIndexColumn = cellRange.columns[0]; const rangeLastIndexColumn = _last16(cellRange.columns); const lastRangeColumn = cellRange.startColumn === rangeFirstIndexColumn ? rangeLastIndexColumn : rangeFirstIndexColumn; const isLastColumn = cell.column === lastRangeColumn; return isLastColumn && isLastRow; } function replaceEdgeRow(range, row, topOrBottom) { let key; if (topOrBottom === "top") { key = !range.startRow || !range.endRow || _isRowBefore4(range.startRow, range.endRow) ? "startRow" : "endRow"; } else { key = !range.startRow || !range.endRow || _isRowBefore4(range.startRow, range.endRow) ? "endRow" : "startRow"; } range[key] = row ?? void 0; } // 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, _KeyboardNavigationModule3, _DragModule], css: [rangeSelectionCSS] }; var RangeSelectionModule = { moduleName: "RangeSelection", version: VERSION, dependsOn: [CellSelectionModule] }; // packages/ag-grid-enterprise/src/serverSideRowModel/serverSideRowModelModule.ts import { _CsrmSsrmSharedApiModule, _RowModelSharedApiModule, _SharedRowSelectionModule, _SortModule, _SsrmInfiniteSharedApiModule, onRowHeightChanged, resetRowHeights } from "ag-grid-community"; // packages/ag-grid-enterprise/src/cellRenderers/loadingCellRenderer.ts import { Component as Component54, RefPlaceholder as RefPlaceholder45, _createIconNoSpan as _createIconNoSpan24 } from "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 Component54 { constructor() { super(LoadingCellRendererElement); this.eLoadingIcon = RefPlaceholder45; this.eLoadingText = RefPlaceholder45; } init(params) { if (params.node.failedLoad) { this.setupFailed(); } else { this.setupLoading(); } } setupFailed() { this.eLoadingText.textContent = this.getLocaleTextFunc()("loadingError", "ERR"); } setupLoading() { const eLoadingIcon = _createIconNoSpan24("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 import { _ColumnGroupModule } from "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 import { BeanStub as BeanStub52 } from "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 BeanStub52 { 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"); for (const valueColumn of valueCols) { 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; if (insertAfter) { children.push(totalColDef); } else { 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); if (insertAtEnd) { pivotColumnGroupDefs.push(valueGroup); } else { 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 import { BeanStub as BeanStub53, _areEqual as _areEqual4, _createColumnTree, _createColumnTreeWithIds, _destroyColumnTree as _destroyColumnTree4, _exists as _exists25, _getColumnsFromTree } from "ag-grid-community"; var PivotResultColsService = class extends BeanStub53 { constructor() { super(...arguments); this.beanName = "pivotResultCols"; } wireBeans(beans) { this.colModel = beans.colModel; this.visibleCols = beans.visibleCols; } destroy() { _destroyColumnTree4(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; for (const column of this.pivotResultCols.list) { const thisPivotKeys = column.getColDef().pivotKeys; const pivotValueColumn = column.getColDef().pivotValueColumn; const pivotKeyMatches = _areEqual4(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" ? _createColumnTree : _createColumnTreeWithIds; const balancedTreeResult = createColTreeFunc( this.beans, colDefs, false, this.pivotResultCols?.tree || this.previousPivotResultCols || void 0, source ); _destroyColumnTree4(this.beans, this.pivotResultCols?.tree, balancedTreeResult.columnTree); const tree = balancedTreeResult.columnTree; const treeDepth = balancedTreeResult.treeDepth; const list = _getColumnsFromTree(tree); const map = {}; this.pivotResultCols = { tree, treeDepth, list, map }; for (const col of this.pivotResultCols.list) { this.pivotResultCols.map[col.getId()] = col; } const hasPreviousCols = !!this.previousPivotResultCols; this.previousPivotResultCols = null; this.colModel.refreshCols(!hasPreviousCols, source); } else { this.previousPivotResultCols = this.pivotResultCols ? this.pivotResultCols.tree : null; this.pivotResultCols = null; this.colModel.refreshCols(false, source); } 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 = _exists25(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 import { BeanStub as BeanStub54, _jsonEquals, _missing as _missing8 } from "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 BeanStub54 { constructor() { super(...arguments); this.beanName = "pivotStage"; this.step = "pivot"; this.refreshProps = [ "removePivotHeaderRowWhenSingleValueColumn", "pivotRowTotals", "pivotColumnGroupTotals", "suppressExpandablePivotGroups" ]; 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(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 uniqueValuesChanged = !_jsonEquals(mapToObject(this.uniqueValues), mapToObject(newValues)); if (uniqueValuesChanged) { this.uniqueValues = newValues; return true; } 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]; const doesGeneratedColMaxExist = this.maxUniqueValues !== -1; children.forEach((child) => { let key = this.valueSvc.getKeyForNode(pivotColumn, child); if (_missing8(key)) { key = ""; } if (!uniqueValues.get(key)) { this.currentUniqueCount += 1; uniqueValues.set(key, /* @__PURE__ */ new Map()); const hasExceededColMax = this.currentUniqueCount > this.maxUniqueValues; if (doesGeneratedColMaxExist && hasExceededColMax) { throw new 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, _ColumnGroupModule] }; var PivotModule = { moduleName: "Pivot", version: VERSION, rowModels: ["clientSide"], beans: [PivotStage], dependsOn: [SharedPivotModule, RowGroupingModule, ClientSideRowModelHierarchyModule] }; // packages/ag-grid-enterprise/src/treeData/treeGroupStrategy.ts import { BeanStub as BeanStub55, RowNode as RowNode4, _EmptyArray, _removeFromArray as _removeFromArray8, _warn as _warn42 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/treeData/fieldAccess.ts var fieldGetter = (path) => { const segments = path.split("."); if (segments.includes("__proto__")) { return () => { }; } const len = segments.length; if (len < 2) { return (data) => data?.[path]; } return (data) => { let i = 0; do { data = data?.[segments[i++]]; if (i === len) { return data; } } while (typeof data === "object"); }; }; // packages/ag-grid-enterprise/src/treeData/treeGroupStrategy.ts 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.fromCodePoint(31, 41150, 8291); var PATH_KEY_SEPARATOR_LEN = 3; var TreeGroupStrategy = class extends BeanStub55 { constructor() { super(...arguments); this.nestedDataGetter = null; this.parentIdGetter = null; this.nonLeafsById = null; this.nodesToUnselect = null; this.fullReload = false; } postConstruct() { this.onPropChange(null); } onPropChange(changedProps) { const gos = this.gos; if (!changedProps || changedProps.has("treeDataParentIdField")) { const parentIdField = gos.get("treeDataParentIdField"); const getter = parentIdField ? fieldGetter(parentIdField) : null; this.fullReload || (this.fullReload = this.parentIdGetter !== getter); this.parentIdGetter = getter; if (getter) { this.nestedDataGetter = null; } } if (!changedProps || changedProps.has("treeDataChildrenField")) { const childrenField = this.parentIdGetter ? "" : gos.get("treeDataChildrenField"); const getter = childrenField ? fieldGetter(childrenField) : null; this.fullReload || (this.fullReload = this.nestedDataGetter !== getter); this.nestedDataGetter = getter; } } destroy() { this.nodesToUnselect = null; this.reset(); super.destroy(); } reset() { this.clearNonLeafs(); this.deselectHiddenNodes(false); this.fullReload = true; } clearNonLeafs() { const fillers = this.nonLeafsById; if (fillers) { for (const node of fillers.values()) { node._destroy(false); } fillers.clear(); this.nonLeafsById = null; } } getNonLeaf(id) { return this.nonLeafsById?.get(id); } loadGroupData(node) { const key = node.key; if (key == null) { node._groupData = null; return null; } const groupData = {}; node._groupData = groupData; const groupDisplayCols = this.beans.showRowGroupCols?.columns; if (groupDisplayCols) { for (let i = 0, len = groupDisplayCols.length; i < len; ++i) { groupData[groupDisplayCols[i].getColId()] = key; } } return groupData; } execute(rootNode, params) { if (this.fullReload) { this.reset(); } const { changedRowNodes, changedPath } = params; const activeChangedPath = changedPath?.active ? changedPath : void 0; const fullReload = this.fullReload || !changedRowNodes && !activeChangedPath; const hasUpdates = !!changedRowNodes && this.flagUpdatedNodes(changedRowNodes); if (fullReload || hasUpdates) { this.fullReload = false; if (this.parentIdGetter) { this.loadSelfRef(rootNode, fullReload); } else if (this.nestedDataGetter) { this.loadNested(rootNode, changedRowNodes, fullReload); } else { this.loadDataPath(rootNode, fullReload); } } const parentsChanged = this.initRowsParents(rootNode); this.destroyFillerRows(!!params.animate); 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.length > 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 allLeafs = rootNode._leafs; const allLeafsLen = allLeafs.length; let parentsChanged = false; for (let i = 0; i < allLeafsLen; ++i) { if (this.initRowParent(allLeafs[i])) { parentsChanged = true; } } return parentsChanged; } initRowParent(current) { let parentsChanged = false; while (true) { const oldParent = current.parent; const parent = current.treeParent; if (parent === null) { if (oldParent) { parentsChanged = true; this.hideRow(current); } break; } let parentFlags = parent.treeNodeFlags + 1; const parentChanged = oldParent !== parent; if (parentChanged) { parentsChanged = true; parentFlags |= FLAG_CHANGED; current.parent = parent; } if (parentChanged && oldParent) { if (oldParent.destroyed && maybeExpandFromRemovedParent(parent, oldParent)) { parentFlags |= FLAG_EXPANDED_INITIALIZED; } oldParent.treeNodeFlags |= FLAG_CHANGED; } if (parent.sourceRowIndex >= 0 || parent.treeNodeFlags & FLAG_MARKED_FILLER || parent.treeParent === null) { parent.treeNodeFlags = parentFlags; break; } parent.treeNodeFlags = parentFlags | FLAG_MARKED_FILLER | current.treeNodeFlags & FLAG_CHANGED; current = parent; } return parentsChanged; } destroyFillerRows(animate) { const nonLeafsById = this.nonLeafsById; if (nonLeafsById) { for (const node of nonLeafsById.values()) { if (node.treeParent === null || (node.treeNodeFlags & MASK_CHILDREN_LEN) === 0) { nonLeafsById.delete(node.id); node._destroy(animate); this.hideRow(node); } } if (nonLeafsById.size === 0) { this.nonLeafsById = null; } } } initRowsChildrenSize(rootNode) { this.initRowChildrenSize(rootNode); const allLeafs = rootNode._leafs; const allLeafsLen = allLeafs.length; for (let i = 0; i < allLeafsLen; ++i) { this.initRowChildrenSize(allLeafs[i]); } const nonLeafsById = this.nonLeafsById; if (nonLeafsById !== null) { for (const filler of nonLeafsById.values()) { this.initRowChildrenSize(filler); } } } initRowChildrenSize(row) { let { childrenAfterGroup, _leafs: rowLeafs, treeNodeFlags } = row; const oldLen = childrenAfterGroup?.length; const len = treeNodeFlags & MASK_CHILDREN_LEN; row.treeNodeFlags = treeNodeFlags & ~MASK_CHILDREN_LEN | ((oldLen || 0) === len ? 0 : FLAG_CHILDREN_CHANGED); if (len === 0 && row.level >= 0) { if (childrenAfterGroup !== _EmptyArray) { row.childrenAfterGroup = _EmptyArray; const sibling = row.sibling; if (sibling) { sibling.childrenAfterGroup = _EmptyArray; } } } else if (oldLen !== len || childrenAfterGroup === rowLeafs) { if (!childrenAfterGroup || childrenAfterGroup === _EmptyArray || childrenAfterGroup === rowLeafs) { row.childrenAfterGroup = childrenAfterGroup = new Array(len); const sibling = row.sibling; if (sibling) { sibling.childrenAfterGroup = childrenAfterGroup; } } else { childrenAfterGroup.length = len; } } } preprocessRows(rootNode) { const allLeafs = rootNode._leafs; const allLeafsLen = allLeafs.length; let preprocessedCount = 0; let treeChanged = false; for (let i = 0; i < allLeafsLen; ++i) { let current = allLeafs[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 (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; 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; } if (flags & FLAG_CHILDREN_CHANGED) { row._leafs = void 0; } return flags + 1; } /** 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); for (const child of row.childrenAfterGroup) { mark(child); } return true; }; mark(rootNode); const rootChildrenAfterGroup = rootNode.childrenAfterGroup; rootChildrenAfterGroup.length = 0; const allLeafs = rootNode._leafs; for (let i = 0, allLeafsLen = allLeafs.length; i < allLeafsLen; ++i) { const row = allLeafs[i]; const parent = row.treeParent; if (parent && mark(row)) { parent.treeNodeFlags |= FLAG_CHILDREN_CHANGED | FLAG_CHANGED; row.parent = rootNode; _removeFromArray8(parent.childrenAfterGroup, row); rootChildrenAfterGroup.push(row); _warn42(270, { id: row.id, parentId: parent?.id ?? "" }); } else if (parent === rootNode) { rootChildrenAfterGroup.push(row); } } } /** Load the tree structure for nested groups, aka children property */ loadNested(rootNode, changedRowNodes, fullReload) { if (!fullReload && changedRowNodes) { for (const row of changedRowNodes.adds) { row.key = row.id; } return; } const allLeafs = rootNode._leafs; for (let i = 0, allLeafsLen = allLeafs.length; i < allLeafsLen; ++i) { const row = allLeafs[i]; const id = row.id; if (row.key !== id) { updateNodeKey(row, id); } } } /** Load the tree structure for self-referencing data, aka parentId field */ loadSelfRef(rootNode, reload) { const allLeafs = rootNode._leafs; const allLeafsLen = allLeafs.length; const gos = this.gos; if (!gos.get("getRowId")) { for (let i = 0; i < allLeafsLen; i++) { allLeafs[i].treeParent = null; } return; } const rowModel = this.beans.rowModel; const parentIdGetter = this.parentIdGetter; for (let i = 0; i < allLeafsLen; i++) { const row = allLeafs[i]; if (reload || row.treeNodeFlags & FLAG_CHANGED || row.treeParent?.destroyed) { let newParent; const parentId = parentIdGetter?.(row.data); if (parentId !== null && parentId !== void 0) { newParent = rowModel.getRowNode(parentId); if (!newParent) { _warn42(271, { id: row.id, parentId }); } } row.treeParent = newParent ?? rootNode; const id = row.id; if (row.key !== id) { updateNodeKey(row, id); } } else { row.treeParent ?? (row.treeParent = rootNode); } } } loadFlattened(rootNode) { const allLeafs = rootNode._leafs; for (let i = 0, allLeafsLen = allLeafs.length; i < allLeafsLen; ++i) { const row = allLeafs[i]; row.treeParent = rootNode; const id = row.id; if (row.key !== id) { updateNodeKey(row, id); } } } /** Load the tree structure for data paths, aka getDataPath callback */ loadDataPath(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 allLeafs = rootNode._leafs; for (let i = 0, allLeafsLen = allLeafs.length; i < allLeafsLen; ++i) { const node = allLeafs[i]; if (!fullReload && node.treeParent !== null && (node.treeNodeFlags & FLAG_CHANGED) === 0) { continue; } const path = getDataPath(node.data); const pathLen = path?.length; if (!pathLen) { _warn42(185, { data: node.data }); continue; } const key = path[pathLen - 1]; if (node.key !== key) { updateNodeKey(node, key); } 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 allLeafs = rootNode._leafs; for (let i = 0, allLeafsLen = allLeafs.length; i < allLeafsLen; ++i) { const node = allLeafs[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 segments = new Array(48); const allLeafs = rootNode._leafs; for (let i = 0, allLeafsLen = allLeafs.length; i < allLeafsLen; ++i) { const node = allLeafs[i]; const pathKey = paths.get(node); if (pathKey === void 0) { continue; } const segmentsLen = this.splitPathKey(segments, pathKey); 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; } } if (startLevel < segmentsLen) { treeParent = this.buildMissingFillers( nodesByPath, pathKey, segments, segmentsLen, startLevel, treeParent ); } node.treeParent = treeParent; } } /** Collect separators positions, fast string split without allocations */ splitPathKey(segments, pathKey) { let segmentsLen = 0; let scanPos = 0; const pathKeyLen = pathKey.length; while (scanPos < pathKeyLen) { const sepPos = pathKey.indexOf(PATH_KEY_SEPARATOR, scanPos); if (sepPos === -1) { break; } segments[segmentsLen++] = sepPos; scanPos = sepPos + PATH_KEY_SEPARATOR_LEN; } return segmentsLen; } /** Walk forward from startLevel to segmentsLen creating missing filler nodes and return the final parent. */ buildMissingFillers(nodesByPath, pathKey, segments, segmentsLen, level, treeParent) { let fillerLevel = 0; let fillerId = "row-group"; if (treeParent.sourceRowIndex < 0 && treeParent.treeParent) { fillerLevel = level; fillerId = treeParent.id; } do { const start = level === 0 ? 0 : segments[level - 1] + PATH_KEY_SEPARATOR_LEN; const end = segments[level]; const subPath = pathKey.slice(0, end); let current = nodesByPath.get(subPath); if (current === void 0) { const fillerKey = start === 0 ? subPath : pathKey.slice(start, end); fillerId = this.makeFillerIdBase(pathKey, segments, level, fillerId, fillerLevel) + fillerKey; current = this.getOrCreateFiller(fillerKey, fillerId); nodesByPath.set(subPath, current); fillerLevel = level + 1; } else if (current.sourceRowIndex < 0) { fillerId = current.id; fillerLevel = level + 1; } current.treeParent = treeParent; treeParent = current; ++level; } while (level < segmentsLen); return 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]; _warn42(186, { rowId: first.id, rowData: first.data, duplicateRowsData }); } } getOrCreateFiller(key, id) { const nonLeafsById = this.nonLeafsById ?? (this.nonLeafsById = /* @__PURE__ */ new Map()); let node = nonLeafsById.get(id); if (node === void 0) { node = new RowNode4(this.beans); node.id = id; node.key = key; node.group = true; node.leafGroup = false; node.rowGroupIndex = null; nonLeafsById.set(id, node); } return node; } /** * Build the base filler ID up to the given 'level' and include the final level separator prefix. * Caller should append only the 'fillerKey' after this base. * Result format: * - With no prefix and level === 0: _ROW_ID_PREFIX_ROW_GROUP + '0-' * - With no prefix and level > 0: _ROW_ID_PREFIX_ROW_GROUP + '0-key0-1-key1-...-(level-1)-key(level-1)-level-' * - With prefix present: prefixId + '-level-' */ makeFillerIdBase(pathKey, segments, level, prefix, prefixLevel) { while (prefixLevel < level) { const start = prefixLevel > 0 ? segments[prefixLevel - 1] + PATH_KEY_SEPARATOR_LEN : 0; const end = segments[prefixLevel]; prefix += "-" + prefixLevel + "-" + pathKey.slice(start, end); ++prefixLevel; } return prefix + "-" + level + "-"; } 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.treeParent = null; row.treeNodeFlags = 0; row.childrenAfterGroup = _EmptyArray; row._leafs = void 0; row._groupData = null; const sibling = row.sibling; if (sibling) { sibling.childrenAfterGroup = _EmptyArray; } row.updateHasChildren(); if (row.rowIndex !== null) { row.clearRowTopAndRowIndex(); } } onShowRowGroupColsSetChanged() { const allLeafs = this.beans.rowModel.rootNode._leafs; if (!allLeafs) { return; } for (let i = 0, len = allLeafs.length; i < len; ++i) { allLeafs[i]._groupData = void 0; } const fillers = this.nonLeafsById; if (fillers) { for (const rowNode of fillers.values()) { rowNode._groupData = void 0; } } } }; var compareSourceRowIndex = (a, b) => a.sourceRowIndex - b.sourceRowIndex; var maybeExpandFromRemovedParent = (parent, oldParent) => { if ((oldParent.treeNodeFlags & FLAG_EXPANDED_INITIALIZED) !== 0 && (parent.treeNodeFlags & FLAG_EXPANDED_INITIALIZED) === 0 && parent.treeParent !== null && parent.sourceRowIndex < 0) { parent.expanded = oldParent.expanded; return true; } return false; }; var updateNodeKey = (node, key) => { const hadData = node._groupData !== void 0; node.key = key; node.groupValue = key; const sibling = node.sibling; if (sibling) { sibling.key = key; } if (hadData) { node._groupData = void 0; node.setData(node.data); } }; // 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, dynamicBeans: { treeGroupStrategy: TreeGroupStrategy }, rowModels: ["clientSide"], dependsOn: [SharedTreeDataModule, AggregationModule, ClientSideRowModelHierarchyModule, GroupEditModule] }; // packages/ag-grid-enterprise/src/serverSideRowModel/blocks/blockUtils.ts import { BeanStub as BeanStub56, RowNode as RowNode5, _doOnce, _exists as _exists26, _getGroupTotalRowCallback as _getGroupTotalRowCallback3, _getRowHeightAsNumber as _getRowHeightAsNumber2, _getRowHeightForNode as _getRowHeightForNode2, _warn as _warn43 } from "ag-grid-community"; var GROUP_MISSING_KEY_ID = "ag-Grid-MissingKey"; var BlockUtils = class extends BeanStub56 { 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 RowNode5(this.beans); const rowHeight = params.rowHeight != null ? params.rowHeight : _getRowHeightAsNumber2(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; } const sibling = rowNode.sibling; if (sibling && !rowNode.footer) { this.destroyRowNode(sibling, false); } rowNode._destroy(true); 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, "data"); if (rowNode.key === null || rowNode.key === void 0) { _doOnce(() => { _warn43(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 = _getGroupTotalRowCallback3(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 = _getGroupTotalRowCallback3(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 (_exists26(data)) { rowNode.setRowHeight(_getRowHeightForNode2(this.beans, rowNode, false, cachedRowHeight).height); rowNode.sibling?.setRowHeight( _getRowHeightForNode2(this.beans, rowNode.sibling, false, cachedRowHeight).height ); } } setChildCountIntoRowNode(rowNode) { const getChildCount = this.gos.get("getChildCount"); if (getChildCount) { rowNode.setAllChildrenCount(getChildCount(rowNode.data)); } } setGroupDataIntoRowNode(rowNode) { const key = rowNode.key; rowNode.groupValue = key; if (rowNode.sibling) { rowNode.sibling.groupValue = key; } const groupDisplayCols = this.showRowGroupCols?.columns; if (!groupDisplayCols) { return; } const usingTreeData = this.gos.get("treeData"); for (const col of groupDisplayCols) { let groupData = rowNode._groupData; if (!groupData) { groupData = {}; rowNode._groupData = groupData; } if (usingTreeData) { groupData[col.getColId()] = key; } else if (col.isRowGroupDisplayed(rowNode.rowGroupColumn.getId())) { const groupValue = this.valueSvc.getValue(rowNode.rowGroupColumn, rowNode, "data"); 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 (!_exists26(node.rowTop) || !_exists26(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) { const expanded = !!this.expansionSvc?.isNodeExpanded(rowNode); const oldExpanded = rowNode.expanded; if (!!oldExpanded !== expanded) { rowNode.setExpanded(expanded); } else if (oldExpanded === void 0) { rowNode.expanded = expanded; } } }; // packages/ag-grid-enterprise/src/serverSideRowModel/listeners/expandListener.ts import { BeanStub as BeanStub57, _isServerSideRowModel as _isServerSideRowModel4 } from "ag-grid-community"; var ExpandListener = class extends BeanStub57 { constructor() { super(...arguments); this.beanName = "ssrmExpandListener"; } postConstruct() { if (!_isServerSideRowModel4(this.gos)) { return; } this.addManagedEventListeners({ rowExpansionStateChanged: this.onRowExpandStateChanged.bind(this) }); } onRowExpandStateChanged() { const beans = this.beans; const expansionSvx = beans.expansionSvc; beans.rowModel.forEachNode((rowNode) => { expansionSvx.updateExpandedState(rowNode); }); this.eventSvc.dispatchEvent({ type: "storeUpdated" }); } }; // packages/ag-grid-enterprise/src/serverSideRowModel/listeners/filterListener.ts import { BeanStub as BeanStub58, _isServerSideRowModel as _isServerSideRowModel5, _jsonEquals as _jsonEquals2 } from "ag-grid-community"; var FilterListener = class extends BeanStub58 { constructor() { super(...arguments); this.beanName = "ssrmFilterListener"; } wireBeans(beans) { this.serverSideRowModel = beans.rowModel; this.filterManager = beans.filterManager; this.listenerUtils = beans.ssrmListenerUtils; } postConstruct() { if (!_isServerSideRowModel5(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); for (const column of oldColumns) { newColumns.add(column); } changedColumns = Array.from(newColumns); } else { newModel = this.filterManager?.getFilterModel() ?? {}; if (advancedFilterEnabledChanged) { const oldColumns = this.getAdvancedFilterColumns(oldModel); for (const column of Object.keys(newModel)) { 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 = {}; for (const key of Object.keys(oldModel)) { allColKeysMap[key] = true; } for (const key of Object.keys(newModel)) { allColKeysMap[key] = true; } const res = []; for (const key of Object.keys(allColKeysMap)) { const filterChanged = !_jsonEquals2(oldModel[key], newModel[key]); 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") { for (const condition of filterModel.conditions) { processAdvancedFilterModel(condition); } } else { columns.add(filterModel.colId); } }; processAdvancedFilterModel(model); return columns; } }; // packages/ag-grid-enterprise/src/serverSideRowModel/listeners/listenerUtils.ts import { BeanStub as BeanStub59 } from "ag-grid-community"; var ListenerUtils = class extends BeanStub59 { 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 import { BeanStub as BeanStub60, _isServerSideRowModel as _isServerSideRowModel6 } from "ag-grid-community"; var SortListener = class extends BeanStub60 { constructor() { super(...arguments); this.beanName = "ssrmSortSvc"; } wireBeans(beans) { this.sortSvc = beans.sortSvc; this.serverSideRowModel = beans.rowModel; this.listenerUtils = beans.ssrmListenerUtils; } postConstruct() { if (!_isServerSideRowModel6(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 = []; for (const sortModel of [newSortModel, oldSortModel]) { 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 import { BeanStub as BeanStub61, _warn as _warn44 } from "ag-grid-community"; var NodeManager = class extends BeanStub61 { constructor() { super(...arguments); this.beanName = "ssrmNodeManager"; this.rowNodes = /* @__PURE__ */ new Map(); } addRowNode(rowNode) { const id = rowNode.id; if (this.rowNodes.has(id)) { _warn44(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 import { BeanStub as BeanStub62, RowNode as RowNode6, _debounce as _debounce6, _getRowHeightAsNumber as _getRowHeightAsNumber3, _getRowHeightForNode as _getRowHeightForNode3, _isGetRowHeightFunction, _isRowSelection as _isRowSelection2, _jsonEquals as _jsonEquals3, _warn as _warn45 } from "ag-grid-community"; var ServerSideRowModel = class extends BeanStub62 { constructor() { super(...arguments); this.beanName = "rowModel"; this.started = false; this.managingPivotResultColumns = false; this.onRowHeightChanged_debounced = _debounce6(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 (_isRowSelection2(this.gos) && !this.gos.exists("getRowId")) { _warn45(188, { feature: "selection" }); } } 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 = {}; for (const col of params.oldCols) { 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 = !_jsonEquals3(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?.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 = _getRowHeightForNode3(this.beans, this.rootNode); this.rootNode.setRowHeight(rootNodeHeight.height, rootNodeHeight.estimated); if (this.rootNode.sibling) { const rootNodeSibling = _getRowHeightForNode3(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 = _getRowHeightForNode3(this.beans, rowNode); rowNode.setRowHeight(rowHeightForNode.height, rowHeightForNode.estimated); const detailNode = rowNode.detailNode; if (detailNode) { const detailRowHeight = _getRowHeightForNode3(this.beans, detailNode); detailNode.setRowHeight(detailRowHeight.height, detailRowHeight.estimated); } if (rowNode.sibling) { const siblingRowHeight = _getRowHeightForNode3(this.beans, rowNode.sibling); detailNode?.setRowHeight(siblingRowHeight.height, siblingRowHeight.estimated); } atLeastOne = true; }); return atLeastOne; } resetRootStore() { this.destroyRootStore(); this.rootNode = new RowNode6(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 = _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() { 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); } 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 = _getRowHeightAsNumber3(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; } getOverlayType() { const rootStore = this.getRootStore(); if (rootStore?.getDisplayIndexEnd() === 0) { return this.filterManager?.isAnyFilterPresent() ? "noMatchingRows" : "noRows"; } return null; } 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 import { _getServerSideRowModel, _warn as _warn46 } from "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) { _warn46(189, { startRow }); return; } _getServerSideRowModel(beans)?.applyRowData(params.successParams, startRow, route); } function applyServerSideTransactionAsync(beans, transaction, callback) { return beans.ssrmTxnManager?.applyTransactionAsync(transaction, callback); } function retryServerSideLoads(beans) { _getServerSideRowModel(beans)?.retryLoads(); } function flushServerSideAsyncTransactions(beans) { return beans.ssrmTxnManager?.flushAsyncTransactions(); } function refreshServerSide(beans, params) { _getServerSideRowModel(beans)?.refreshStore(params); } function getServerSideGroupLevelState(beans) { return _getServerSideRowModel(beans)?.getStoreState() ?? []; } // packages/ag-grid-enterprise/src/serverSideRowModel/services/serverSideExpansionService.ts import { RowNode as RowNode7, _exists as _exists27, _getRowHeightForNode as _getRowHeightForNode4 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/serverSideRowModel/services/expansion/strategies/defaultStrategy.ts import { BeanStub as BeanStub63 } from "ag-grid-community"; var ExpandStrategy = class extends BeanStub63 { constructor() { super(...arguments); this.name = "expand"; this.expanded = /* @__PURE__ */ new Set(); this.collapsed = /* @__PURE__ */ new Set(); this.initialState = /* @__PURE__ */ new Map(); } /** * Set the expanded and collapsed rows. * @param expandedRows the rows to expand * @param touchedRows the rows that have been touched */ setExpandedState({ expandedRowGroupIds, collapsedRowGroupIds }) { this.expanded = new Set(expandedRowGroupIds); this.collapsed = new Set(collapsedRowGroupIds); for (const node of this.expanded) { this.initialState.set(node, false); } for (const node of this.collapsed) { this.initialState.set(node, true); } } /** * Get the serializable expanded state * @returns an object containing the expanded and collapsed rows */ getExpandedState() { return { expandedRowGroupIds: Array.from(this.expanded), collapsedRowGroupIds: Array.from(this.collapsed) }; } /** * Set the expanded state for a row. * @param row the row to expand/collapse * @param expanded true to expand the row, false to collapse it */ setRowExpanded(row, expanded) { const id = row.id; const stateIsDefault = this.initialState.get(id) === expanded; if (expanded) { this.collapsed.delete(id); if (!stateIsDefault) { this.expanded.add(id); } return; } this.expanded.delete(id); if (!stateIsDefault) { this.collapsed.add(id); } } /** * Check if a row is expanded. * @param rowId the row id to check * @returns true if the row is expanded */ isRowExpanded(node) { const rowId = node.id; if (this.expanded.has(rowId)) { return true; } if (this.collapsed.has(rowId)) { return false; } const initialVal = this.initialState.get(rowId); if (initialVal != null) { return initialVal; } const initial = this.getInitialRowState(node); this.initialState.set(rowId, initial); return initial; } /** * This is different from just checking expandedState.isExpanded(rowNode.id), * as this correctly prioritizes user interaction over the user-defined initial state. * Plus sanity checks that the rowNode is actually expandable. */ getInitialRowState(rowNode) { if (!rowNode.isExpandable()) { return false; } const userFunc = this.gos.getCallback("isServerSideGroupOpenByDefault"); if (!userFunc) { return false; } const params = { data: rowNode.data, rowNode }; return userFunc(params); } /** * if the row is expanded or has been collapsed intentionally, do not apply initial state. * @param rowId the row id to check * @returns true if the row has been toggled */ isRowInitialised(rowId) { return this.initialState.has(rowId); } /** * Expand or collapse all loaded rows. * @param expanded true to expand all rows, false to collapse all rows */ expandAll(expanded) { this.beans.rowModel.forEachNode((node) => { this.setRowExpanded(node, expanded); }); } }; // packages/ag-grid-enterprise/src/serverSideRowModel/services/expansion/strategies/expandAllStrategy.ts import { BeanStub as BeanStub64 } from "ag-grid-community"; var ExpandAllStrategy = class extends BeanStub64 { constructor() { super(...arguments); this.name = "expandAll"; this.allExpanded = void 0; this.flipped = /* @__PURE__ */ new Set(); } setExpandedState(state) { this.allExpanded = state.expandAll; this.flipped = new Set(state.invertedRowGroupIds); } getExpandedState() { return { expandAll: this.allExpanded, invertedRowGroupIds: Array.from(this.flipped) }; } setRowExpanded(row, expanded) { const id = row.id; if (expanded === this.allExpanded) { this.flipped.delete(id); return; } this.flipped.add(id); } isRowExpanded(node) { const rowId = node.id; return this.allExpanded !== this.flipped.has(rowId); } isRowInitialised() { return true; } expandAll(expanded) { this.allExpanded = expanded; this.flipped.clear(); } }; // packages/ag-grid-enterprise/src/serverSideRowModel/services/serverSideExpansionService.ts var ServerSideExpansionService = class extends BaseExpansionService { constructor() { super(...arguments); this.beanName = "expansionSvc"; } wireBeans(beans) { this.serverSideRowModel = beans.rowModel; this.storeFactory = beans.ssrmStoreFactory; } postConstruct() { const setDefaultExpand = () => { this.strategy = this.createManagedBean(new ExpandStrategy()); }; this.addManagedEventListeners({ // when row grouping / pivot changes, the old expand all state is no longer valid as rows changed columnRowGroupChanged: setDefaultExpand, columnPivotChanged: setDefaultExpand, columnPivotModeChanged: setDefaultExpand }); this.addManagedPropertyListener("ssrmExpandAllAffectsAllRows", (p) => { if (!p.currentValue) { this.strategy = this.createManagedBean(new ExpandStrategy()); this.updateAllNodes(); this.dispatchStateUpdatedEvent(); } }); setDefaultExpand(); } setExpansionState(state) { const isExpandAllState = "expandAll" in state; const isExpandAllStrategy = this.isExpandAllStrategy(this.strategy); if (isExpandAllState !== isExpandAllStrategy) { this.strategy = isExpandAllState ? this.createManagedBean(new ExpandAllStrategy()) : this.createManagedBean(new ExpandStrategy()); } this.strategy.setExpandedState(state); this.dispatchStateUpdatedEvent(); this.updateAllNodes(); } getExpansionState() { return this.strategy.getExpandedState(); } /** * Updates all nodes to the correct expanded/collapsed state. */ updateAllNodes() { this.serverSideRowModel.forEachNode((node) => { super.setExpanded(node, this.isNodeExpanded(node)); }); } isNodeExpanded(node) { return this.strategy.isRowExpanded(node); } setExpanded(node, expanded, e, _) { this.strategy.setRowExpanded(node, expanded); super.setExpanded(node, expanded, e); this.dispatchStateUpdatedEvent(); this.updateExpandedState(node); } expandAll(expanded) { const ssrmExpandAllAffectsAllRows = this.beans.gos.get("ssrmExpandAllAffectsAllRows"); const shouldUseExpandAllStrategy = !this.isExpandAllStrategy(this.strategy) && ssrmExpandAllAffectsAllRows; this.strategy = shouldUseExpandAllStrategy ? new ExpandAllStrategy() : this.strategy; this.strategy.expandAll(expanded); this.updateAllNodes(); this.dispatchStateUpdatedEvent(); this.beans.eventSvc.dispatchEvent({ type: "expandOrCollapseAll", source: expanded ? "expandAll" : "collapseAll" }); } isExpandAllStrategy(strategy) { return strategy.name === "expandAll"; } onGroupExpandedOrCollapsed() { } setDetailsExpansionState(detailGridApi) { const { gos: masterGos } = this.beans; if (!masterGos.get("ssrmExpandAllAffectsAllRows")) { return; } const masterExpansionState = this.getExpansionState(); const isInitial = masterExpansionState.expandAll === void 0; if (isInitial) { return; } const allExpanded = masterExpansionState.expandAll && masterExpansionState.invertedRowGroupIds.length === 0; const allCollapsed = !masterExpansionState.expandAll && masterExpansionState.invertedRowGroupIds.length === 0; if (allCollapsed === allExpanded) { return; } return allExpanded ? detailGridApi.expandAll() : detailGridApi.collapseAll(); } dispatchExpandedEvent(event) { this.eventSvc.dispatchEvent(event); this.beans.rowRenderer.refreshCells({ rowNodes: [event.node] }); } updateExpandedState(rowNode) { const oldChildStore = rowNode.childStore; if (rowNode.expanded) { if (rowNode.master && !rowNode.detailNode) { rowNode.detailNode = this.createDetailNode(rowNode); } if (!oldChildStore && rowNode.hasChildren()) { const storeParams = this.serverSideRowModel.getParams(); rowNode.childStore = this.createBean(this.storeFactory.createStore(storeParams, rowNode)); } } else if (oldChildStore && this.gos.get("purgeClosedRowNodes")) { rowNode.childStore = this.destroyBean(oldChildStore); } } createDetailNode(masterNode) { const detailNode = new RowNode7(this.beans); detailNode.detail = true; detailNode.selectable = false; detailNode.parent = masterNode; if (_exists27(masterNode.id)) { detailNode.id = "detail_" + masterNode.id; } detailNode.data = masterNode.data; detailNode.level = masterNode.level + 1; const defaultDetailRowHeight = 200; const rowHeight = _getRowHeightForNode4(this.beans, detailNode).height; detailNode.rowHeight = rowHeight ? rowHeight : defaultDetailRowHeight; return detailNode; } }; // packages/ag-grid-enterprise/src/serverSideRowModel/services/serverSideSelectionService.ts import { BaseSelectionService, _error as _error8, _getGroupSelectsDescendants, _getRowSelectionMode, _isMultiRowSelection as _isMultiRowSelection3, _isRowSelection as _isRowSelection3, _isUsingNewRowSelectionAPI as _isUsingNewRowSelectionAPI2, _warn as _warn49 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/serverSideRowModel/services/selection/strategies/defaultStrategy.ts import { BeanStub as BeanStub65, _error as _error6, _isMultiRowSelection, _isUsingNewRowSelectionAPI, _warn as _warn47 } from "ag-grid-community"; var DefaultStrategy = class extends BeanStub65 { 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") { _error6(116); return; } if (!("selectAll" in state)) { _error6(116); return; } if (typeof state.selectAll !== "boolean") { _error6(117); return; } if (!("toggledNodes" in state) || !Array.isArray(state.toggledNodes)) { return _warn47(197); } const newState = { selectAll: state.selectAll, toggledNodes: /* @__PURE__ */ new Set() }; state.toggledNodes.forEach((key) => { if (typeof key === "string") { newState.toggledNodes.add(key); } else { _warn47(196, { key }); } }); const isSelectingMultipleRows = newState.selectAll || newState.toggledNodes.size > 1; if (_isUsingNewRowSelectionAPI(this.gos) && !_isMultiRowSelection(this.gos) && isSelectingMultipleRows) { _warn47(130); return; } this.selectedState = newState; } deleteSelectionStateFromParent(parentPath, removedNodeIds) { if (this.selectedState.toggledNodes.size === 0) { return false; } let anyNodesToggled = false; for (const id of removedNodeIds) { 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 (!_isMultiRowSelection(this.gos) || onlyThisNode) { if (nodes.length > 1) { _error6(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); } }; for (const node of nodes) { 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) { _warn47(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 import { BeanStub as BeanStub66, _error as _error7, _isMultiRowSelection as _isMultiRowSelection2, _warn as _warn48 } from "ag-grid-community"; var GroupSelectsChildrenStrategy = class extends BeanStub66 { 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) { _error7(111); return; } const recursivelyDeserializeState = (normalisedState, parentSelected) => { if (typeof normalisedState !== "object") { _error7(243); throw new Error(); } if ("selectAllChildren" in normalisedState && typeof normalisedState.selectAllChildren !== "boolean") { _error7(244); throw new Error(); } if ("toggledNodes" in normalisedState) { if (!Array.isArray(normalisedState.toggledNodes)) { _error7(245); throw new Error(); } const allHaveIds = normalisedState.toggledNodes.every( (innerState) => typeof innerState === "object" && "nodeId" in innerState && typeof innerState.nodeId === "string" ); if (!allHaveIds) { _error7(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) { _error7(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; for (const id of removedNodeIds) { 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 (!_isMultiRowSelection2(this.gos) || onlyThisNode) { if (nodes.length > 1) { _error7(130); return 0; } this.deselectAllRowNodes(); } for (const rowNode of nodes) { 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?.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) { _warn48(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 BaseSelectionService { constructor() { super(...arguments); this.beanName = "selectionSvc"; } postConstruct() { super.postConstruct(); this.addManagedPropertyListeners(["groupSelectsChildren", "rowSelection"], () => { const groupSelectsChildren2 = _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 = _getRowSelectionMode(this.gos); if (rowSelection !== this.selectionMode) { this.selectionMode = rowSelection; this.deselectAllRowNodes({ source: "api" }); } }); this.selectionMode = _getRowSelectionMode(this.gos); const groupSelectsChildren = _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 (!_isRowSelection3(this.gos)) { if (state) { _warn49(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 (!_isRowSelection3(this.gos) && params.newValue) { _warn49(132); return 0; } const { nodes, ...otherParams } = params; if (nodes.length > 1 && this.selectionMode !== "multiRow") { _warn49(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 (!_isRowSelection3(this.gos)) { _warn49(132); return; } validateSelectionParameters(params); if (_isUsingNewRowSelectionAPI2(this.gos) && !_isMultiRowSelection3(this.gos)) { return _warn49(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 _warn49(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 (!_isRowSelection3(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 _error8(194, { method: "updateSelectableAfterGrouping" }); } refreshMasterNodeState() { } setDetailSelectionState() { return; } }; function validateSelectionParameters({ selectAll }) { if (selectAll === "filtered" || selectAll === "currentPage") { _warn49(195, { justCurrentPage: selectAll === "currentPage" }); } } // packages/ag-grid-enterprise/src/serverSideRowModel/services/ssrmRowChildrenService.ts import { BeanStub as BeanStub67 } from "ag-grid-community"; var SsrmRowChildrenService = class extends BeanStub67 { 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 import { BeanStub as BeanStub68, _addGridCommonParams as _addGridCommonParams25, _getMaxConcurrentDatasourceRequests } from "ag-grid-community"; var LazyBlockLoadingService = class extends BeanStub68 { 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 = _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 = _addGridCommonParams25(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 import { BeanStub as BeanStub71, _warn as _warn52 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/serverSideRowModel/stores/lazy/lazyStore.ts import { BeanStub as BeanStub70, ServerSideTransactionResultStatus, _getGroupTotalRowCallback as _getGroupTotalRowCallback4, _getRowHeightAsNumber as _getRowHeightAsNumber5, _getRowIdCallback as _getRowIdCallback3, _warn as _warn51 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/serverSideRowModel/stores/lazy/lazyCache.ts import { BeanStub as BeanStub69, _getRowHeightAsNumber as _getRowHeightAsNumber4, _getRowIdCallback as _getRowIdCallback2, _warn as _warn50 } from "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) { for (const index of this.indexes) { const map = this.maps.get(index); map.set(item[index], item); } } delete(item) { for (const index of this.indexes) { 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 BeanStub69 { 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(); const { blockUtils, gos, store } = this; this.defaultNodeIdPrefix = blockUtils.createNodeIdPrefix(store.getParentNode()); this.getRowIdFunc = _getRowIdCallback2(gos); this.isMasterDetail = 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?.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 = _getRowHeightAsNumber4(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; if (node.firstChild !== isFirstChild) { node.firstChild = isFirstChild; node.dispatchRowEvent("firstChildChanged"); } 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; } }); 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; } }); 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.blockUtils.checkOpenByDefault(newNode); 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 isExpandedGroup = node.isExpandable() && node.expanded; const isUnbalancedNode = this.gos.get("groupAllowUnbalanced") && node.key === ""; const isEditing = !!this.beans.editSvc?.isRowEditing(node); return isExpandedGroup || this.isNodeFocused(node) || isUnbalancedNode || isEditing; } 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(", "); _warn50(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?.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); const rowNodeSorter = this.rowNodeSorter; if (!isAnySort || !rowNodeSorter) { return; } const allNodes = new Array(this.nodeMap.getSize()); const nodesMap = this.nodeMap; nodesMap.forEach((lazyNode) => allNodes[lazyNode.index] = lazyNode.node); nodesMap.clear(); const sortedNodes = rowNodeSorter.doFullSortInPlace(allNodes, sortOptions); for (let i = 0, len = sortedNodes.length; i < len; ++i) { const node = sortedNodes[i]; nodesMap.set({ id: node.id, node, index: i }); } } /** * 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, newRowCount) { 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 }); } const isNewRowCountValid = newRowCount != null && newRowCount >= 0; if (isNewRowCountValid) { this.numberOfRows = newRowCount; this.isLastRowKnown = true; } else { this.numberOfRows -= 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 BeanStub70 { 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 = _getRowIdCallback3(this.gos); if (!idFunc) { _warn51(206); return { status: 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: 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, transaction.rowCount); } 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: ServerSideTransactionResultStatus.Applied, update: updatedNodes, add: insertedNodes, remove: removedNodes }; } updateSelectionAfterTransaction(updatedNodes, removedNodes) { if (!this.selectionSvc) { return; } const nodesToDeselect = []; for (const node of updatedNodes ?? []) { if (node.isSelected() && !node.selectable) { nodesToDeselect.push(node); } } for (const node of removedNodes ?? []) { 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 && _getGroupTotalRowCallback4(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 && _getGroupTotalRowCallback4(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 = _getRowHeightAsNumber5(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 = _getRowHeightAsNumber5(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 BeanStub71 { 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?.maxBlocksInCache != null ? userStoreParams.maxBlocksInCache : this.gos.get("maxBlocksInCache"); const maxBlocksActive = maxBlocksInCache != null && maxBlocksInCache >= 0; if (!maxBlocksActive) { return; } if (ssrmParams.dynamicRowHeight) { _warn52(203); return; } if (this.rowAutoHeight?.active) { _warn52(204); return void 0; } return maxBlocksInCache; } getBlockSize(userStoreParams) { const blockSize = 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 import { BeanStub as BeanStub72, _isServerSideRowModel as _isServerSideRowModel7 } from "ag-grid-community"; var StoreUtils = class extends BeanStub72 { 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") && _isServerSideRowModel7(this.gos); } isServerSideOnlyRefreshFilteredGroups() { return this.gos.get("serverSideOnlyRefreshFilteredGroups") && _isServerSideRowModel7(this.gos); } }; // packages/ag-grid-enterprise/src/serverSideRowModel/transactionManager.ts import { BeanStub as BeanStub73, ServerSideTransactionResultStatus as ServerSideTransactionResultStatus2, _isServerSideRowModel as _isServerSideRowModel8 } from "ag-grid-community"; var TransactionManager = class extends BeanStub73 { constructor() { super(...arguments); this.beanName = "ssrmTxnManager"; this.asyncTransactions = []; } wireBeans(beans) { this.valueCache = beans.valueCache; this.serverSideRowModel = beans.rowModel; this.selectionSvc = beans.selectionSvc; } postConstruct() { if (!_isServerSideRowModel8(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; for (const txWrapper of this.asyncTransactions) { let result; const hasStarted = this.serverSideRowModel.executeOnStore(txWrapper.transaction.route, (cache) => { result = cache.applyTransaction(txWrapper.transaction); }); if (!hasStarted) { result = { status: ServerSideTransactionResultStatus2.StoreNotStarted }; } else if (result == void 0) { result = { status: ServerSideTransactionResultStatus2.StoreNotFound }; } resultsForEvent.push(result); const retryTransaction = result.status == ServerSideTransactionResultStatus2.StoreLoading; if (retryTransaction) { transactionsToRetry.push(txWrapper); continue; } if (txWrapper.callback) { resultFuncs.push(() => txWrapper.callback(result)); } if (result.status === ServerSideTransactionResultStatus2.Applied) { atLeastOneTransactionApplied = true; } } if (resultFuncs.length > 0) { window.setTimeout(() => { for (const func of resultFuncs) { 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: ServerSideTransactionResultStatus2.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: ServerSideTransactionResultStatus2.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, _SortModule, _SharedRowSelectionModule, SharedPivotModule, SharedTreeDataModule, LoadingCellRendererModule ] }; var ServerSideRowModelApiModule = { moduleName: "ServerSideRowModelApi", version: VERSION, apiFunctions: { getServerSideSelectionState, setServerSideSelectionState, applyServerSideTransaction, applyServerSideTransactionAsync, applyServerSideRowData, retryServerSideLoads, flushServerSideAsyncTransactions, refreshServerSide, getServerSideGroupLevelState, resetRowHeights, onRowHeightChanged }, dependsOn: [EnterpriseCoreModule, _RowModelSharedApiModule, _CsrmSsrmSharedApiModule, _SsrmInfiniteSharedApiModule] }; // packages/ag-grid-enterprise/src/formula/editor/formulaCellEditor.ts import { AgAbstractCellEditor as AgAbstractCellEditor2, KeyCode as KeyCode33, RefPlaceholder as RefPlaceholder46, _isBrowserSafari as _isBrowserSafari2, _placeCaretAtEnd as _placeCaretAtEnd2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/widgets/agFormulaInputField.ts import { AgContentEditableField, _createElement as _createElement16, _getDocument as _getDocument6, _getWindow, _placeCaretAtEnd } from "ag-grid-community"; // packages/ag-grid-enterprise/src/formula/refUtils.ts var CELL_OR_RANGE_REGEX = /\$?[A-Za-z]+\$?[0-9]+(?::\$?[A-Za-z]+\$?[0-9]+)?/g; var FULL_CELL_OR_RANGE_REGEX = /^(\$?)([A-Za-z]+)(\$?)([0-9]+)(?::(\$?)([A-Za-z]+)(\$?)([0-9]+))?$/; var WORD_CHAR_REGEX = /[A-Za-z0-9]/; var isFormulaIdentChar = (char) => { return !!char && WORD_CHAR_REGEX.test(char); }; var isFormulaIdentStart = (char) => { return !!char && /[A-Za-z]/.test(char); }; var isWordChar = (char) => { return isFormulaIdentChar(char ?? void 0); }; var isStandaloneRefToken = (text, matchIndex, ref) => { const prevChar = matchIndex > 0 ? text[matchIndex - 1] : null; if (isWordChar(prevChar)) { return false; } if (ref.endsWith(":")) { return true; } const nextIndex = matchIndex + ref.length; const nextChar = nextIndex < text.length ? text[nextIndex] : null; return !isWordChar(nextChar); }; var parseA1Ref = (ref, options = {}) => { const allowTrailingColon = options.allowTrailingColon ?? false; const normalizedRef = allowTrailingColon && ref.endsWith(":") ? ref.slice(0, -1) : ref; const match = FULL_CELL_OR_RANGE_REGEX.exec(normalizedRef); if (!match) { return null; } const [, absCol1, col1, absRow1, row1, absCol2, col2, absRow2, row2] = match; const hasEnd = !!(col2 && row2); return { startCol: col1, startRow: row1, startColAbsolute: absCol1 === "$", startRowAbsolute: absRow1 === "$", ...hasEnd ? { endCol: col2, endRow: row2, endColAbsolute: absCol2 === "$", endRowAbsolute: absRow2 === "$" } : null }; }; var getRefTokenMatches = (text) => { const matches = []; let match; let index = 0; CELL_OR_RANGE_REGEX.lastIndex = 0; while ((match = CELL_OR_RANGE_REGEX.exec(text)) != null) { let ref = match[0]; const start = match.index ?? 0; const endIndex = start + ref.length; if (endIndex < text.length && text[endIndex] === ":") { ref += ":"; } if (!isStandaloneRefToken(text, start, ref)) { continue; } matches.push({ ref, start, end: start + ref.length, index }); index += 1; } return matches; }; // packages/ag-grid-enterprise/src/widgets/agFormulaInputField.css-GENERATED.ts var agFormulaInputFieldCSS = ( /*css*/ `.ag-formula-token{line-height:var(--ag-line-height,1.6)}.ag-formula-token-color-1{color:var(--ag-formula-token-1-color)}.ag-formula-token-color-2{color:var(--ag-formula-token-2-color)}.ag-formula-token-color-3{color:var(--ag-formula-token-3-color)}.ag-formula-token-color-4{color:var(--ag-formula-token-4-color)}.ag-formula-token-color-5{color:var(--ag-formula-token-5-color)}.ag-formula-token-color-6{color:var(--ag-formula-token-6-color)}.ag-formula-token-color-7{color:var(--ag-formula-token-7-color)}.ag-formula-range-color-1{--ag-range-selection-border-color:var(--ag-formula-token-1-color);--ag-range-selection-background-color:var(--ag-formula-token-1-background-color)}.ag-formula-range-color-2{--ag-range-selection-border-color:var(--ag-formula-token-2-color);--ag-range-selection-background-color:var(--ag-formula-token-2-background-color)}.ag-formula-range-color-3{--ag-range-selection-border-color:var(--ag-formula-token-3-color);--ag-range-selection-background-color:var(--ag-formula-token-3-background-color)}.ag-formula-range-color-4{--ag-range-selection-border-color:var(--ag-formula-token-4-color);--ag-range-selection-background-color:var(--ag-formula-token-4-background-color)}.ag-formula-range-color-5{--ag-range-selection-border-color:var(--ag-formula-token-5-color);--ag-range-selection-background-color:var(--ag-formula-token-5-background-color)}.ag-formula-range-color-6{--ag-range-selection-border-color:var(--ag-formula-token-6-color);--ag-range-selection-background-color:var(--ag-formula-token-6-background-color)}.ag-formula-range-color-7{--ag-range-selection-border-color:var(--ag-formula-token-7-color);--ag-range-selection-background-color:var(--ag-formula-token-7-background-color)}.ag-fill-handle.ag-formula-range-color-1,.ag-range-handle.ag-formula-range-color-1{background-color:var(--ag-formula-token-1-color)}.ag-fill-handle.ag-formula-range-color-2,.ag-range-handle.ag-formula-range-color-2{background-color:var(--ag-formula-token-2-color)}.ag-fill-handle.ag-formula-range-color-3,.ag-range-handle.ag-formula-range-color-3{background-color:var(--ag-formula-token-3-color)}.ag-fill-handle.ag-formula-range-color-4,.ag-range-handle.ag-formula-range-color-4{background-color:var(--ag-formula-token-4-color)}.ag-fill-handle.ag-formula-range-color-5,.ag-range-handle.ag-formula-range-color-5{background-color:var(--ag-formula-token-5-color)}.ag-fill-handle.ag-formula-range-color-6,.ag-range-handle.ag-formula-range-color-6{background-color:var(--ag-formula-token-6-color)}` ); // packages/ag-grid-enterprise/src/widgets/formulaInputAutocompleteFeature.ts import { BeanStub as BeanStub74, KeyCode as KeyCode32, _getDocument as _getDocument5 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/widgets/formulaInputTokenUtils.ts var TOKEN_INSERT_AFTER_CHARS = /* @__PURE__ */ new Set(["=", "+", "-", "*", "/", "^", ",", "(", ";", "<", ">", "&"]); var getPreviousNonSpaceChar = (value, offset) => { for (let i = offset - 1; i >= 0; i--) { const char = value[i]; if (char != null && char.trim() !== "") { return char; } } return null; }; // packages/ag-grid-enterprise/src/widgets/formulaRangeUtils.ts import { isSpecialCol as isSpecialCol2 } from "ag-grid-community"; var FORMULA_TOKEN_COLOR_CLASS = "ag-formula-token-color"; var FORMULA_RANGE_COLOR_CLASS = "ag-formula-range-color"; var getColorClassesForRef = (_ref, colorIndexOverride) => { const index = colorIndexOverride ?? 0; return { tokenClass: `${FORMULA_TOKEN_COLOR_CLASS}-${index + 1}`, rangeClass: `${FORMULA_RANGE_COLOR_CLASS}-${index + 1}`, colorIndex: index }; }; var getRangeColorIndexFromClass = (colorClass) => { if (!colorClass) { return null; } const match = /ag-formula-range-color-(\d+)/.exec(colorClass); if (!match) { return null; } const parsed = parseInt(match[1], 10); return Number.isFinite(parsed) ? parsed - 1 : null; }; var tagRangeWithFormulaColor = (range, ref, colorIndex) => { if (!range) { return; } const { rangeClass } = getColorClassesForRef(ref, colorIndex); range.colorClass = rangeClass; }; var getCellRangeParams = (beans, ref) => { const parsed = parseA1Ref(ref, { allowTrailingColon: true }); if (!parsed) { return null; } const { formula } = beans; const { startCol, startRow, endCol, endRow } = parsed; const startColRef = startCol; const endColRef = endCol ?? startCol; const startColMatch = formula?.getColByRef(startColRef); const endColMatch = formula?.getColByRef(endColRef); if (!startColMatch || !endColMatch) { return null; } const rowStartIndex = parseInt(startRow, 10) - 1; const rowEndIndex = endRow ? parseInt(endRow, 10) - 1 : rowStartIndex; if (rowStartIndex < 0 || rowEndIndex < 0) { return null; } const rowModel = beans.rowModel; if (!rowModel?.getFormulaRow(rowStartIndex) || !rowModel.getFormulaRow(rowEndIndex)) { return null; } return { rowStartIndex, rowEndIndex, columnStart: startColMatch, columnEnd: endColMatch }; }; var getLatestRangeRef = (beans) => { const ranges = beans.rangeSvc?.getCellRanges(); const latest = ranges?.length ? ranges[ranges.length - 1] : null; if (!latest) { return null; } return rangeToRef(beans, latest); }; var rangeToRef = (beans, range) => { const { rangeSvc, formula } = beans; if (!rangeSvc || !formula) { return null; } const startRow = rangeSvc.getRangeStartRow(range); const endRow = rangeSvc.getRangeEndRow(range); if (!startRow || !endRow || startRow.rowPinned || endRow.rowPinned) { return null; } const rowStartIndex = Math.min(startRow.rowIndex, endRow.rowIndex) + 1; const rowEndIndex = Math.max(startRow.rowIndex, endRow.rowIndex) + 1; const columns = range.columns?.filter((col) => !isSpecialCol2(col) && !!formula.getColRef(col)); if (!columns?.length) { return null; } const sorted = [...columns]; const startCol = sorted[0]; const endCol = sorted[sorted.length - 1]; const colStartRef = formula.getColRef(startCol); const colEndRef = formula.getColRef(endCol); if (!colStartRef || !colEndRef) { return null; } const sameCol = colStartRef === colEndRef; const sameRow = rowStartIndex === rowEndIndex; if (sameCol && sameRow) { return `${colStartRef}${rowStartIndex}`; } return `${colStartRef}${rowStartIndex}:${colEndRef}${rowEndIndex}`; }; var getRefTokenMatchesForFormula = (beans, text) => { const matches = getRefTokenMatches(text); const { formula } = beans; if (!formula) { return matches; } const valid = []; let index = 0; for (const match of matches) { if (!getCellRangeParams(beans, match.ref)) { continue; } valid.push({ ...match, index }); index += 1; } return valid; }; var getRefTokensFromText = (beans, text) => { const matches = getRefTokenMatchesForFormula(beans, text); return matches.map(({ ref, index }) => ({ ref, index })); }; // packages/ag-grid-enterprise/src/widgets/formulaInputAutocompleteFeature.ts var FormulaInputAutocompleteFeature = class extends BeanStub74 { constructor(field) { super(); this.field = field; this.functionAutocompleteList = null; this.functionAutocompleteToken = null; this.functionAutocompleteEntries = null; this.functionAutocompleteSearch = null; } postConstruct() { this.addManagedElementListeners(this.field.getContentElement(), { keydown: this.onContentKeyDown.bind(this), mouseup: this.updateFunctionAutocomplete.bind(this), focusin: this.updateFunctionAutocomplete.bind(this), focusout: this.closeFunctionAutocomplete.bind(this) }); this.addDestroyFunc(() => this.closeFunctionAutocomplete()); } onPlainValueUpdated() { this.closeFunctionAutocomplete(); } onFormulaValueUpdated() { this.updateFunctionAutocomplete(); } onContentKeyDown(event) { if (this.functionAutocompleteList) { switch (event.key) { case KeyCode32.ENTER: case KeyCode32.TAB: event.preventDefault(); event.stopPropagation(); this.confirmFunctionAutocomplete(); return; case KeyCode32.ESCAPE: event.preventDefault(); event.stopPropagation(); this.closeFunctionAutocomplete(); return; case KeyCode32.UP: case KeyCode32.DOWN: this.functionAutocompleteList.onNavigationKeyDown(event, event.key); return; } } switch (event.key) { case KeyCode32.LEFT: case KeyCode32.RIGHT: case KeyCode32.PAGE_HOME: case KeyCode32.PAGE_END: this.scheduleFunctionAutocompleteUpdate(); break; } } scheduleFunctionAutocompleteUpdate() { setTimeout(() => { if (!this.isAlive()) { return; } this.updateFunctionAutocomplete(); }); } updateFunctionAutocomplete() { if (!this.isContentFocused()) { this.closeFunctionAutocomplete(); return; } const { field, beans } = this; const value = field.getCurrentValue(); const hasFormulaPrefix = value.trimStart().startsWith("="); if (!hasFormulaPrefix) { this.closeFunctionAutocomplete(); return; } const caretOffsets = field.getCaretOffsetsForAutocomplete(value); if (!caretOffsets) { this.closeFunctionAutocomplete(); return; } if (isCaretInsideRefToken(beans, value, caretOffsets.valueOffset)) { this.closeFunctionAutocomplete(); return; } const token = getFunctionTokenAtOffset(value, caretOffsets.valueOffset, beans.formula ?? null); if (!token) { this.closeFunctionAutocomplete(); return; } const { prefix } = token; if (!prefix.length) { this.closeFunctionAutocomplete(); return; } const entries = this.getFunctionAutocompleteEntries(); if (!entries.length) { this.closeFunctionAutocomplete(); return; } const searchLower = prefix.toLocaleLowerCase(); const hasMatch = entries.some(({ key }) => key.toLocaleLowerCase().startsWith(searchLower)); if (!hasMatch) { this.closeFunctionAutocomplete(); return; } this.functionAutocompleteToken = token; this.openFunctionAutocomplete(entries); if (this.functionAutocompleteList && this.functionAutocompleteSearch !== prefix) { this.functionAutocompleteList.setSearch(prefix); this.functionAutocompleteSearch = prefix; } } getFunctionAutocompleteEntries() { const formula = this.beans.formula; const names = formula?.active ? formula.getFunctionNames?.() ?? [] : []; if (!this.functionAutocompleteEntries || this.functionAutocompleteEntries.length !== names.length) { this.functionAutocompleteEntries = names.map((name) => ({ key: name })); } return this.functionAutocompleteEntries; } openFunctionAutocomplete(entries) { if (this.functionAutocompleteList || !entries.length) { return; } const popupSvc = this.beans.popupSvc; if (!popupSvc) { return; } let positionParams = null; const repositionList = () => { if (this.functionAutocompleteList && positionParams) { popupSvc.positionPopupByComponent(positionParams); } }; this.functionAutocompleteList = this.createManagedBean( new AgAutocompleteList({ autocompleteEntries: entries, onConfirmed: () => this.confirmFunctionAutocomplete(), useStartsWithSearch: true, autoSizeList: true, maxVisibleItems: 10, onListHeightChanged: repositionList }) ); const ePopupGui = this.functionAutocompleteList.getGui(); positionParams = { ePopup: ePopupGui, type: "autocomplete", eventSource: this.field.getGui(), position: "under", alignSide: this.gos.get("enableRtl") ? "right" : "left", keepWithinBounds: true }; const addPopupRes = popupSvc.addPopup({ eChild: ePopupGui, anchorToElement: this.field.getGui(), positionCallback: repositionList, ariaLabel: "Formula functions" }); this.functionAutocompleteHidePopup = addPopupRes.hideFunc; this.functionAutocompleteList.afterGuiAttached(); } closeFunctionAutocomplete() { this.functionAutocompleteToken = null; this.functionAutocompleteSearch = null; if (!this.functionAutocompleteList) { return; } this.functionAutocompleteHidePopup?.(); this.functionAutocompleteHidePopup = void 0; this.destroyBean(this.functionAutocompleteList); this.functionAutocompleteList = null; } confirmFunctionAutocomplete() { const token = this.functionAutocompleteToken; const selected = this.functionAutocompleteList?.getSelectedValue(); if (!token || !selected) { this.closeFunctionAutocomplete(); return; } const { field } = this; const value = field.getCurrentValue(); const functionName = selected.key; const baseValue = value.slice(0, token.start) + functionName + value.slice(token.end); const insertPos = token.start + functionName.length; const nextValue = baseValue[insertPos] === "(" ? baseValue : baseValue.slice(0, insertPos) + "(" + baseValue.slice(insertPos); field.getContentElement().focus({ preventScroll: true }); field.applyFormulaValueChange({ currentValue: value, nextValue, caret: insertPos + 1 }); this.closeFunctionAutocomplete(); } isContentFocused() { return _getDocument5(this.beans).activeElement === this.field.getContentElement(); } }; var getFunctionTokenAtOffset = (value, caretOffset, formula) => { if (caretOffset < 0 || caretOffset > value.length || isInsideStringLiteral(value, caretOffset)) { return null; } let start = caretOffset; while (start > 0 && isFormulaIdentChar(value[start - 1])) { start--; } let end = caretOffset; while (end < value.length && isFormulaIdentChar(value[end])) { end++; } if (start === end) { return null; } let tokenEnd = end; if (caretOffset !== end) { const suffix = value.slice(caretOffset, end); const parsed = parseA1Ref(suffix); const isRefSuffix = !!parsed && (!formula || !!formula.getColByRef(parsed.startCol)); if (isRefSuffix) { tokenEnd = caretOffset; } } const token = value.slice(start, tokenEnd); if (!token || !isFormulaIdentStart(token[0])) { return null; } if (value[start - 1] === "$") { return null; } const previousChar = getPreviousNonSpaceChar(value, start); if (previousChar != null && !TOKEN_INSERT_AFTER_CHARS.has(previousChar)) { return null; } return { start, end: tokenEnd, prefix: value.slice(start, caretOffset) }; }; var isCaretInsideRefToken = (beans, value, caretOffset) => { for (const match of getRefTokenMatchesForFormula(beans, value)) { if (caretOffset >= match.start && caretOffset <= match.end) { return true; } } return false; }; var isInsideStringLiteral = (value, offset) => { let inString = false; for (let i = 0; i < offset && i < value.length; i++) { if (value[i] !== '"') { continue; } if (value[i + 1] === '"') { i++; continue; } inString = !inString; } return inString; }; // packages/ag-grid-enterprise/src/widgets/formulaInputRangeSyncFeature.ts import { BeanStub as BeanStub75, _last as _last17, isSpecialCol as isSpecialCol3 } from "ag-grid-community"; var FormulaInputRangeSyncFeature = class extends BeanStub75 { constructor(field) { super(); this.field = field; // local mirror of editSvc range selection state while formula editing is active. this.rangeSelectionEnabled = false; // refs found in the formula that should have matching grid ranges (counts handle duplicates). this.trackedRangeRefs = /* @__PURE__ */ new Map(); // ranges we are actively tracking and their current ref string. this.trackedRanges = /* @__PURE__ */ new Map(); // prevents our own range changes from re-entering the selection handler. this.suppressRangeEvents = false; // skips the synthetic refresh event we dispatch after re-tagging ranges. this.ignoreNextRangeEvent = false; // avoids a value update loop when we re-render on enabling range selection. this.skipNextValueUpdate = false; // suppress selection handling while keyboard navigation updates the focus range. this.suppressSelectionChangeHandling = false; // keep a stable callback so the input manager can deactivate the previous editor. this.handleEditorDeactivated = () => { this.rangeSelectionEnabled = false; this.suppressRangeEvents = false; this.ignoreNextRangeEvent = false; this.skipNextValueUpdate = false; this.clearTrackedRanges(true); }; } postConstruct() { this.addManagedEventListeners({ cellSelectionChanged: this.onCellSelectionChanged.bind(this) }); this.addDestroyFunc(() => this.disableRangeSelectionWhileEditing()); this.addDestroyFunc(() => this.unregisterActiveEditor()); } onValueUpdated(value, hasFormulaPrefix) { if (this.skipNextValueUpdate) { this.skipNextValueUpdate = false; return; } if (!this.isActiveEditor()) { return; } if (hasFormulaPrefix) { const newlyEnabled = this.enableRangeSelectionWhileEditing(); if (newlyEnabled) { this.skipNextValueUpdate = true; this.field.setValue(value, true); } this.syncRangesFromFormula(value); return; } this.disableRangeSelectionWhileEditing(); } setEditingCellRef(column, rowIndex, editingCellRef) { this.editingColumn = column; this.editingRowIndex = rowIndex ?? void 0; this.editingCellRef = editingCellRef; } setEditorActive(active) { if (active) { this.registerActiveEditor(); return; } this.unregisterActiveEditor(); } withSelectionChangeHandlingSuppressed(action) { const previous = this.suppressSelectionChangeHandling; this.suppressSelectionChangeHandling = true; try { action(); } finally { this.suppressSelectionChangeHandling = previous; } } deactivateForFocusLoss() { if (!this.isActiveEditor()) { return; } this.handleEditorDeactivated(); this.beans.editSvc?.disableRangeSelectionWhileEditing?.(); this.unregisterActiveEditor(); } registerActiveEditor() { const fieldId = this.field.getCompId(); const { formulaInputManager } = this.beans; if (!formulaInputManager) { return; } const becameActive = formulaInputManager.registerActiveEditor(fieldId, this.handleEditorDeactivated); if (!becameActive) { return; } this.rangeSelectionEnabled = false; this.suppressRangeEvents = false; this.ignoreNextRangeEvent = false; this.skipNextValueUpdate = false; this.clearTrackedRanges(false); const value = this.field.getCurrentValue(); const hasFormulaPrefix = value.trimStart().startsWith("="); this.onValueUpdated(value, hasFormulaPrefix); } unregisterActiveEditor() { const fieldId = this.field.getCompId(); const { formulaInputManager } = this.beans; if (!formulaInputManager) { return; } formulaInputManager.unregisterActiveEditor(fieldId, this.handleEditorDeactivated); } isActiveEditor() { const fieldId = this.field.getCompId(); const { formulaInputManager } = this.beans; return !!formulaInputManager && formulaInputManager.isActiveEditor(fieldId); } getTrackedRefCount(ref) { return this.trackedRangeRefs.get(ref) ?? 0; } hasTrackedRef(ref) { return this.getTrackedRefCount(ref) > 0; } addTrackedRef(ref) { this.trackedRangeRefs.set(ref, this.getTrackedRefCount(ref) + 1); } removeTrackedRef(ref) { const next = this.getTrackedRefCount(ref) - 1; if (next <= 0) { this.trackedRangeRefs.delete(ref); return; } this.trackedRangeRefs.set(ref, next); } enableRangeSelectionWhileEditing() { if (this.rangeSelectionEnabled) { return false; } this.rangeSelectionEnabled = true; this.beans.editSvc?.enableRangeSelectionWhileEditing?.(); return true; } disableRangeSelectionWhileEditing() { if (!this.rangeSelectionEnabled && !this.trackedRangeRefs.size) { return; } this.rangeSelectionEnabled = false; this.beans.editSvc?.disableRangeSelectionWhileEditing?.(); this.clearTrackedRanges(this.isActiveEditor()); } clearTrackedRanges(clearGridRanges = true) { if (clearGridRanges) { const refs = Array.from(this.trackedRangeRefs.keys()); refs.forEach((ref) => this.removeRangeForRef(ref)); } this.trackedRangeRefs.clear(); this.trackedRanges.clear(); } getLiveRanges() { return this.beans.rangeSvc?.getCellRanges() ?? []; } withSuppressedRangeEvents(action) { this.suppressRangeEvents = true; action(); this.suppressRangeEvents = false; } setCellRangesSilently(ranges) { const rangeSvc = this.beans.rangeSvc; if (!rangeSvc) { return; } this.withSuppressedRangeEvents(() => rangeSvc.setCellRanges(ranges)); } getColorIndexForTokenOrRef(ref, tokenIndex) { return this.field.getColorIndexForToken(tokenIndex ?? null) ?? this.field.getColorIndexForRef(ref); } normaliseRefForComparison(ref) { if (!ref) { return null; } const trimmed = ref.endsWith(":") ? ref.slice(0, -1) : ref; return trimmed.replace(/\$/g, "").toUpperCase(); } tagRangeColor(range, ref, colorIndex) { const { rangeClass } = getColorClassesForRef(ref, colorIndex); if (range.colorClass === rangeClass) { return false; } tagRangeWithFormulaColor(range, ref, colorIndex); return true; } trackRange(range, ref, tokenIndex) { const existing = this.trackedRanges.get(range); const nextTokenIndex = tokenIndex !== void 0 ? tokenIndex : existing?.tokenIndex ?? null; if (!existing) { this.addTrackedRef(ref); } else if (existing.ref !== ref) { this.removeTrackedRef(existing.ref); this.addTrackedRef(ref); } this.trackedRanges.set(range, { ref, tokenIndex: nextTokenIndex }); } getUntrackedFormulaRangesByRef() { const rangesByRef = /* @__PURE__ */ new Map(); const ranges = this.getLiveRanges(); for (const range of ranges) { if (this.trackedRanges.has(range)) { continue; } if (getRangeColorIndexFromClass(range.colorClass) == null) { continue; } const ref = rangeToRef(this.beans, range); if (!ref || ref === this.editingCellRef) { continue; } const existing = rangesByRef.get(ref); if (existing) { existing.push(range); } else { rangesByRef.set(ref, [range]); } } return rangesByRef; } syncRangesFromFormula(value) { const text = value ?? this.field.getCurrentValue() ?? ""; if (!this.rangeSelectionEnabled) { this.clearTrackedRanges(); return; } const refTokens = getRefTokensFromText(this.beans, text); const desiredByRef = /* @__PURE__ */ new Map(); for (const token of refTokens) { const { ref, index } = token; if (ref === this.editingCellRef) { continue; } const list = desiredByRef.get(ref) ?? []; list.push(index); desiredByRef.set(ref, list); } for (const ref of Array.from(this.trackedRangeRefs.keys())) { if (!desiredByRef.has(ref)) { this.removeRangeForRef(ref); } } const rangeSvc = this.beans.rangeSvc; if (!rangeSvc) { return; } const liveRanges = new Set(this.getLiveRanges()); for (const [range, tracked] of this.trackedRanges.entries()) { if (!liveRanges.has(range)) { this.trackedRanges.delete(range); this.removeTrackedRef(tracked.ref); } } const untrackedFormulaRanges = this.getUntrackedFormulaRangesByRef(); let reTagged = false; for (const [ref, tokenIndices] of desiredByRef.entries()) { const rangesForRef = []; for (const [range, tracked] of this.trackedRanges.entries()) { if (tracked.ref === ref) { rangesForRef.push(range); } } const reuseCandidates = untrackedFormulaRanges.get(ref); while (rangesForRef.length < tokenIndices.length && reuseCandidates?.length) { const candidate = reuseCandidates.shift(); if (candidate) { rangesForRef.push(candidate); } } while (rangesForRef.length > tokenIndices.length) { const range = rangesForRef.pop(); if (range) { this.removeTrackedRange(range); } } while (rangesForRef.length < tokenIndices.length) { const tokenIndex = tokenIndices[rangesForRef.length]; const added = this.addRangeForRef(ref, false, tokenIndex); if (!added) { break; } rangesForRef.push(added); } for (let i = 0; i < rangesForRef.length && i < tokenIndices.length; i++) { const range = rangesForRef[i]; const tokenIndex = tokenIndices[i]; this.trackRange(range, ref, tokenIndex); const colorIndex = this.getColorIndexForTokenOrRef(ref, tokenIndex); if (this.tagRangeColor(range, ref, colorIndex)) { reTagged = true; } } } const unusedFormulaRanges = []; for (const ranges of untrackedFormulaRanges.values()) { if (ranges.length) { unusedFormulaRanges.push(...ranges); } } if (unusedFormulaRanges.length) { const currentRanges = this.getLiveRanges(); const remaining = currentRanges.filter((range) => !unusedFormulaRanges.includes(range)); if (remaining.length !== currentRanges.length) { this.setCellRangesSilently(remaining); reTagged = true; } } if (reTagged) { this.refreshRangeStyling(); } } onCellSelectionChanged(event) { if (!this.isActiveEditor() || !this.rangeSelectionEnabled || !this.beans.editSvc?.isRangeSelectionEnabledWhileEditing?.()) { return; } if (this.ignoreNextRangeEvent) { this.ignoreNextRangeEvent = false; return; } if (this.suppressSelectionChangeHandling) { return; } const { finished, started } = event; const liveRanges = this.getLiveRanges(); const nonSpecialRanges = liveRanges.filter((range) => !this.isSpecialOnlyRange(range)); if (nonSpecialRanges.length !== liveRanges.length) { this.setCellRangesSilently(nonSpecialRanges); this.refocusEditingCell(); return; } const latestRange = liveRanges.length ? _last17(liveRanges) : null; const latestRef = latestRange ? rangeToRef(this.beans, latestRange) : null; const hasInsertCandidate = !!latestRange && !this.trackedRanges.has(latestRange) && !!latestRef && latestRef !== this.editingCellRef; const shouldInsert = finished && (started || hasInsertCandidate); const reTagged = this.ensureTrackedRangeColors(); if (this.suppressRangeEvents) { if (reTagged) { this.refreshRangeStyling(); } return; } if (started || hasInsertCandidate) { this.field.rememberCaret(); } if (!hasInsertCandidate && this.handleRemovedRangeTokens()) { this.field.restoreCaretAfterToken(); this.refocusEditingCell(); return; } if (this.updateTrackedRangeTokens()) { return; } const ref = getLatestRangeRef(this.beans); if (!ref || ref === this.editingCellRef) { this.refocusEditingCell(); return; } if (shouldInsert) { const { action, previousRef, tokenIndex } = this.field.applyRangeInsert(ref); if (action === "none") { this.keepLatestSelectionOnly(latestRange); this.beans.editSvc?.stopEditing(void 0, { source: "edit" }); return; } if (action === "replace" && previousRef === ref) { this.discardLatestRangeForRef(ref); this.field.restoreCaretAfterToken(); this.refocusEditingCell(); return; } this.tagLatestRangeForRef(ref, tokenIndex); this.handleRangeTokenUpdate(previousRef, ref, true, action === "insert", tokenIndex); this.syncRangesFromFormula(this.field.getCurrentValue()); this.field.restoreCaretAfterToken(); this.refocusEditingCell(); return; } if (!started && !finished) { const { previousRef, tokenIndex } = this.field.insertOrReplaceToken(ref, false); this.tagLatestRangeForRef(ref, tokenIndex); this.handleRangeTokenUpdate(previousRef, ref, false, false); this.refocusEditingCell(); return; } this.tagLatestRangeForRef(ref); if (finished) { this.field.restoreCaretAfterToken(); this.refocusEditingCell(); } } keepLatestSelectionOnly(latestRange) { if (!latestRange || this.getLiveRanges().length <= 1) { return; } this.setCellRangesSilently([latestRange]); } isSpecialOnlyRange(range) { const columns = range.columns; return !!columns?.length && columns.every((col) => isSpecialCol3(col)); } handleRangeTokenUpdate(previousRef, ref, manageRanges, isNew, tokenIndex) { if (manageRanges) { if (!isNew && previousRef && previousRef !== ref) { this.removeRangeForRef(previousRef, tokenIndex); } this.addRangeForRef(ref, true, tokenIndex); return; } if (isNew || !previousRef) { this.addTrackedRef(ref); return; } if (previousRef !== ref) { this.removeTrackedRef(previousRef); this.addTrackedRef(ref); } } addRangeForRef(ref, skipAddCellRange, tokenIndex) { const rangeSvc = this.beans.rangeSvc; if (!rangeSvc) { return void 0; } let created; if (!skipAddCellRange) { const params = getCellRangeParams(this.beans, ref); if (!params) { return void 0; } this.withSuppressedRangeEvents(() => { created = rangeSvc.addCellRange(params); }); } else { created = this.findLatestRangeForRef(ref, true) ?? this.findLatestRangeForRef(ref, false); } if (created) { const colorIndex = this.getColorIndexForTokenOrRef(ref, tokenIndex); this.tagRangeColor(created, ref, colorIndex); this.trackRange(created, ref, tokenIndex); this.refreshRangeStyling(); } return created; } findLatestRangeForRef(ref, skipTracked) { const ranges = this.getLiveRanges(); for (let i = ranges.length - 1; i >= 0; i--) { const range = ranges[i]; if (rangeToRef(this.beans, range) !== ref) { continue; } if (skipTracked && this.trackedRanges.has(range)) { continue; } return range; } return void 0; } tagLatestRangeForRef(ref, tokenIndex) { const { trackedRanges } = this; const ranges = this.getLiveRanges(); const latest = ranges.length ? _last17(ranges) : null; if (!latest) { return; } const trackedIndex = trackedRanges.get(latest)?.tokenIndex ?? null; const colorIndex = this.getColorIndexForTokenOrRef(ref, tokenIndex ?? trackedIndex); this.tagRangeColor(latest, ref, colorIndex); this.refreshRangeStyling(); } discardLatestRangeForRef(ref) { const ranges = this.getLiveRanges(); if (!ranges.length) { return; } const latest = _last17(ranges); if (rangeToRef(this.beans, latest) !== ref) { return; } if (this.trackedRanges.has(latest)) { this.removeTrackedRange(latest); return; } this.setCellRangesSilently(ranges.slice(0, -1)); } ensureTrackedRangeColors() { const ranges = this.getLiveRanges(); if (!ranges.length) { return false; } let reTagged = false; for (const range of ranges) { const tracked = this.trackedRanges.get(range); const ref = tracked?.ref ?? rangeToRef(this.beans, range); if (!ref || !this.hasTrackedRef(ref)) { continue; } const tokenIndex = tracked?.tokenIndex ?? null; const tokenColorIndex = this.field.getColorIndexForToken(tokenIndex); const inferredColorIndex = getRangeColorIndexFromClass(range.colorClass); const colorIndex = tokenColorIndex ?? (this.field.hasColorForRef(ref) ? this.field.getColorIndexForRef(ref) : this.field.moveColorToRef(void 0, ref, inferredColorIndex ?? void 0)); if (colorIndex == null) { continue; } if (this.tagRangeColor(range, ref, colorIndex)) { reTagged = true; } if (!this.trackedRanges.has(range)) { this.trackRange(range, ref, tokenIndex); } } return reTagged; } handleRemovedRangeTokens() { if (!this.beans.rangeSvc || this.trackedRanges.size === 0) { return false; } const value = this.field.getCurrentValue(); const tokens = getRefTokensFromText(this.beans, value).filter(({ ref }) => ref !== this.editingCellRef); if (!tokens.length) { return false; } const liveRanges = this.getLiveRanges(); const liveSet = new Set(liveRanges); const liveCounts = /* @__PURE__ */ new Map(); for (const range of liveRanges) { const ref = rangeToRef(this.beans, range); if (!ref || ref === this.editingCellRef) { continue; } liveCounts.set(ref, (liveCounts.get(ref) ?? 0) + 1); } const pendingRemovals = /* @__PURE__ */ new Map(); for (const token of tokens) { const { ref } = token; pendingRemovals.set(ref, (pendingRemovals.get(ref) ?? 0) + 1); } for (const [ref, tokenCount] of Array.from(pendingRemovals.entries())) { const liveCount = liveCounts.get(ref) ?? 0; const remaining = tokenCount - liveCount; if (remaining > 0) { pendingRemovals.set(ref, remaining); } else { pendingRemovals.delete(ref); } } if (!pendingRemovals.size) { return false; } const removals = []; for (const [range, tracked] of Array.from(this.trackedRanges.entries())) { if (liveSet.has(range)) { continue; } const { ref } = tracked; const remaining = pendingRemovals.get(ref) ?? 0; if (remaining <= 0) { continue; } pendingRemovals.set(ref, remaining - 1); removals.push({ range, tracked }); } if (!removals.length) { return false; } removals.sort((a, b) => (b.tracked.tokenIndex ?? -1) - (a.tracked.tokenIndex ?? -1)); let removed = false; for (const { range, tracked } of removals) { const { ref, tokenIndex } = tracked; removed = this.field.removeTokenRef(ref, tokenIndex ?? null) || removed; this.trackedRanges.delete(range); this.removeTrackedRef(ref); } if (removed) { this.syncRangesFromFormula(this.field.getCurrentValue()); } return removed; } refreshRangeStyling() { const { eventSvc } = this.beans; if (!eventSvc) { return; } this.ensureTrackedRangeColors(); this.ignoreNextRangeEvent = true; eventSvc.dispatchEvent({ type: "cellSelectionChanged", started: false, finished: false }); } refocusEditingCell() { const { focusSvc } = this.beans; const { editingColumn, editingRowIndex } = this; if (!focusSvc || editingColumn == null || editingRowIndex == null) { return; } focusSvc.setFocusedCell({ column: editingColumn, rowIndex: editingRowIndex, rowPinned: null, preventScrollOnBrowserFocus: true }); } removeTrackedRange(range) { const tracked = this.trackedRanges.get(range); if (!tracked) { return; } const ranges = this.getLiveRanges(); const remaining = ranges.filter((candidate) => candidate !== range); if (remaining.length !== ranges.length) { this.setCellRangesSilently(remaining); } this.trackedRanges.delete(range); this.removeTrackedRef(tracked.ref); } removeRangeForRef(ref, tokenIndex) { if (!ref || !this.hasTrackedRef(ref)) { return; } if (tokenIndex != null) { let removed = false; for (const [range, tracked] of Array.from(this.trackedRanges.entries())) { const { ref: trackedRef, tokenIndex: trackedTokenIndex } = tracked; if (trackedRef !== ref || trackedTokenIndex !== tokenIndex) { continue; } this.removeTrackedRange(range); removed = true; break; } if (!removed) { for (const [range, tracked] of Array.from(this.trackedRanges.entries())) { if (tracked.ref === ref) { this.removeTrackedRange(range); break; } } } return; } for (const [range, tracked] of Array.from(this.trackedRanges.entries())) { if (tracked.ref === ref) { this.removeTrackedRange(range); } } } updateTrackedRangeTokens() { if (!this.beans.rangeSvc) { return false; } const ranges = this.getLiveRanges(); const editingRef = this.normaliseRefForComparison(this.editingCellRef); let updated = false; for (const range of ranges) { const tracked = this.trackedRanges.get(range); if (!tracked) { continue; } const { ref: previousRef, tokenIndex } = tracked; const nextRef = rangeToRef(this.beans, range); const normalisedPrevious = this.normaliseRefForComparison(previousRef); const normalisedNext = this.normaliseRefForComparison(nextRef); if (!nextRef || !normalisedNext || normalisedNext === normalisedPrevious || normalisedNext === editingRef) { continue; } const { colorClass } = range; const tokenColorIndex = this.field.getColorIndexForToken(tokenIndex ?? null); const colorIndex = tokenColorIndex ?? this.field.moveColorToRef(previousRef, nextRef, getRangeColorIndexFromClass(colorClass) ?? void 0); const replacedIndex = this.field.replaceTokenRef(previousRef, nextRef, colorIndex, tokenIndex); if (replacedIndex == null) { continue; } this.tagRangeColor(range, nextRef, colorIndex); this.trackRange(range, nextRef, replacedIndex ?? tokenIndex ?? null); updated = true; } if (updated) { this.refreshRangeStyling(); } return updated; } }; // packages/ag-grid-enterprise/src/widgets/agFormulaInputField.ts var FORMULA_TOKEN_COLOR_COUNT = 7; var DISPLAY_OPERATOR_LOOKUP = { "/": "\xF7", "*": "\xD7" }; var VALUE_OPERATOR_LOOKUP = { "\xF7": "/", "\xD7": "*" }; var AgFormulaInputField = class extends AgContentEditableField { constructor() { super({ renderValueToElement: false, className: "ag-formula-input-field" }); this.currentValue = ""; // caret / token bookkeeping so range updates can re-render without losing position. this.selectionCaretOffset = null; this.lastTokenValueOffset = null; this.lastTokenValueLength = null; this.lastTokenCaretOffset = null; // record mouse focus so we don't jump the caret to the end after a click. this.focusFromMouseTime = null; // skip auto-caret placement when we are restoring a caret programmatically. this.suppressNextFocusCaretPlacement = false; // fallback color assignment per ref when a token index is unavailable. this.formulaColorByRef = /* @__PURE__ */ new Map(); this.registerCSS(agFormulaInputFieldCSS); this.registerCSS(agAutocompleteCSS); } postConstruct() { super.postConstruct(); this.rangeSyncFeature = this.createManagedBean(new FormulaInputRangeSyncFeature(this)); this.autocompleteFeature = this.createManagedBean(new FormulaInputAutocompleteFeature(this)); this.addManagedElementListeners(this.getContentElement(), { input: this.onContentInput.bind(this), focus: this.onContentFocus.bind(this), blur: this.onContentBlur.bind(this), mousedown: this.onContentMouseDown.bind(this) }); } setValue(value, silent) { const text = value == null ? "" : String(value); const { isFormula, hasFormulaPrefix } = this.getFormulaState(text); if (!isFormula) { this.applyPlainValue(text, { silent, dispatch: true }); this.rangeSyncFeature?.onValueUpdated(text, hasFormulaPrefix); return this; } this.applyFormulaValue(text, { currentValue: this.getCurrentValue(), silent }); this.rangeSyncFeature?.onValueUpdated(text, hasFormulaPrefix); return this; } getCurrentValue() { const liveValue = serializeContent(this.getContentElement()); if (liveValue !== this.currentValue) { this.setEditorValue(liveValue, true); } return this.currentValue; } setEditingCellRef(column, rowIndex) { const colRef = column ? this.beans.formula?.getColRef(column) : void 0; const editingCellRef = colRef && rowIndex != null && rowIndex !== void 0 ? `${colRef}${rowIndex + 1}` : void 0; if (!editingCellRef) { this.rangeSyncFeature?.setEditingCellRef(void 0, void 0, void 0); return; } this.rangeSyncFeature?.setEditingCellRef(column, rowIndex, editingCellRef); } rememberCaret() { const caretOffset = getCaretOffset(this.beans, this.getContentElement(), this.getCurrentValue()); this.selectionCaretOffset = caretOffset ?? this.currentValue.length; } setEditorValue(value, silent = false) { this.currentValue = value; super.setValue(value, silent); return this; } renderFormula(params) { renderFormula({ beans: this.beans, contentElement: this.getContentElement(), getColorIndexForToken: this.getColorIndexForToken.bind(this), ...params }); } renderPlainValue(value, caret) { const contentElement = this.getContentElement(); const caretOffset = caret ?? getCaretOffset(this.beans, contentElement, this.currentValue); contentElement.textContent = value ?? ""; const targetCaret = caretOffset != null ? Math.min(caretOffset, value.length) : null; restoreCaret(this.beans, contentElement, targetCaret); } withSelectionChangeHandlingSuppressed(action) { if (!this.rangeSyncFeature) { action(); return; } this.rangeSyncFeature.withSelectionChangeHandlingSuppressed(action); } getColorIndexForRef(ref) { if (!shouldUseTokenColors(this.beans)) { return null; } const existing = this.formulaColorByRef.get(ref); if (existing != null) { return existing; } const next = this.formulaColorByRef.size % FORMULA_TOKEN_COLOR_COUNT; this.formulaColorByRef.set(ref, next); return next; } getColorIndexForToken(tokenIndex) { if (!shouldUseTokenColors(this.beans) || tokenIndex == null) { return null; } return tokenIndex % FORMULA_TOKEN_COLOR_COUNT; } hasColorForRef(ref) { return this.formulaColorByRef.has(ref); } moveColorToRef(fromRef, toRef, fallback) { const colorIndex = fromRef && this.formulaColorByRef.has(fromRef) ? this.getColorIndexForRef(fromRef) : fallback ?? this.formulaColorByRef.get(toRef) ?? this.getColorIndexForRef(toRef); if (fromRef && fromRef !== toRef) { this.formulaColorByRef.delete(fromRef); } if (colorIndex == null) { return null; } this.formulaColorByRef.set(toRef, colorIndex); return colorIndex; } updateFormulaColorsFromValue(value) { value = value == null ? "" : String(value); if (!shouldUseTokenColors(this.beans)) { this.formulaColorByRef.clear(); return; } const refsInOrder = getOrderedRefs(this.beans, value); let changed = refsInOrder.length !== this.formulaColorByRef.size; const nextColors = /* @__PURE__ */ new Map(); refsInOrder.forEach((ref, index) => { const colorIndex = index % FORMULA_TOKEN_COLOR_COUNT; nextColors.set(ref, colorIndex); if (this.formulaColorByRef.get(ref) !== colorIndex) { changed = true; } }); if (!changed) { return; } this.formulaColorByRef.clear(); nextColors.forEach((colorIndex, ref) => this.formulaColorByRef.set(ref, colorIndex)); } onContentInput() { const contentElement = this.getContentElement(); const currentValue = this.getCurrentValue(); const caret = getCaretOffset(this.beans, contentElement, currentValue); const serialized = serializeContent(contentElement); const { isFormula, hasFormulaPrefix } = this.getFormulaState(serialized); if (!isFormula) { this.applyPlainValue(serialized, { caret, dispatch: true }); this.rangeSyncFeature?.onValueUpdated(serialized, hasFormulaPrefix); return; } this.applyFormulaValue(serialized, { currentValue, caret: caret ?? void 0, dispatch: true }); this.rangeSyncFeature?.onValueUpdated(serialized, hasFormulaPrefix); } onContentFocus() { this.rangeSyncFeature?.setEditorActive(true); if (this.suppressNextFocusCaretPlacement) { this.suppressNextFocusCaretPlacement = false; return; } const { focusFromMouseTime } = this; const focusFromMouse = focusFromMouseTime != null; this.focusFromMouseTime = null; if (focusFromMouse) { return; } _placeCaretAtEnd(this.beans, this.getContentElement()); } onContentBlur(event) { this.focusFromMouseTime = null; const nextTarget = event.relatedTarget; const editorTarget = nextTarget?.closest(".ag-cell-editor"); const cellTarget = nextTarget?.closest(".ag-cell"); if (!nextTarget || this.getGui().contains(nextTarget) || !editorTarget || !cellTarget) { return; } this.rangeSyncFeature?.deactivateForFocusLoss(); } onContentMouseDown() { this.focusFromMouseTime = Date.now(); } insertOrReplaceToken(ref, isNew) { const offsets = this.getTokenInsertOffsets(isNew); if (!offsets) { return {}; } const { caretOffset, valueOffset } = offsets; const replaceLen = isNew || this.lastTokenValueLength == null ? 0 : this.lastTokenValueLength; const value = this.getCurrentValue(); const updatedValue = value.slice(0, valueOffset) + ref + value.slice(valueOffset + replaceLen); const tokenIndex = getTokenMatchAtOffset(this.beans, updatedValue, valueOffset)?.index ?? null; let previousRef; this.applyFormulaValueChange({ currentValue: value, nextValue: updatedValue, caret: caretOffset + ref.length, updateTracking: () => { previousRef = this.updateLastTokenTracking(ref, caretOffset, valueOffset); } }); return { previousRef, tokenIndex }; } removeTokenRef(ref, tokenIndex) { const value = this.getCurrentValue(); const matches = getRefTokenMatchesForFormula(this.beans, value); let token; if (tokenIndex != null) { token = matches.find((match) => match.index === tokenIndex); if (token && token.ref !== ref) { token = void 0; } } if (!token) { token = matches.find((match) => match.ref === ref); } if (!token) { return false; } const updated = value.slice(0, token.start) + value.slice(token.end); const caretBase = this.selectionCaretOffset ?? token.start; const caret = Math.min(caretBase, updated.length); this.applyFormulaValueChange({ currentValue: value, nextValue: updated, caret, updateTracking: () => { this.lastTokenValueOffset = null; this.lastTokenValueLength = null; this.lastTokenCaretOffset = caret; this.lastTokenRef = void 0; } }); return true; } applyRangeInsert(ref) { const value = this.getCurrentValue(); const caretOffsets = this.getCaretOffsets(value); if (!caretOffsets) { const { previousRef: previousRef2, tokenIndex: tokenIndex2 } = this.insertOrReplaceToken(ref, true); return { action: "insert", previousRef: previousRef2, tokenIndex: tokenIndex2 }; } const { valueOffset } = caretOffsets; const tokenMatch = getTokenMatchAtOffset(this.beans, value, valueOffset); if (tokenMatch) { const { end: tokenEnd, ref: tokenRef } = tokenMatch; if (tokenRef.endsWith(":") && valueOffset === tokenEnd) { const { previousRef: previousRef3, tokenIndex: tokenIndex3 } = this.insertOrReplaceToken(ref, true); return { action: "insert", previousRef: previousRef3, tokenIndex: tokenIndex3 }; } const { previousRef: previousRef2, tokenIndex: tokenIndex2 } = this.replaceTokenAtMatch(tokenMatch, ref); return { action: "replace", previousRef: previousRef2, tokenIndex: tokenIndex2 }; } const rawTokenMatch = getRawTokenMatchAtOffset(value, valueOffset); if (rawTokenMatch) { const updated = value.slice(0, rawTokenMatch.start) + ref + value.slice(rawTokenMatch.end); const tokenIndex2 = getTokenMatchAtOffset(this.beans, updated, rawTokenMatch.start)?.index ?? null; const { previousRef: previousRef2 } = this.replaceTokenAtMatch(rawTokenMatch, ref, tokenIndex2); return { action: "replace", previousRef: previousRef2, tokenIndex: tokenIndex2 }; } if (!shouldInsertTokenAtOffset(value, valueOffset)) { return { action: "none" }; } const { previousRef, tokenIndex } = this.insertOrReplaceToken(ref, true); return { action: "insert", previousRef, tokenIndex }; } restoreCaretAfterToken() { const caretBase = this.lastTokenCaretOffset ?? getCaretOffset(this.beans, this.getContentElement(), this.getCurrentValue()) ?? this.currentValue.length; const caret = caretBase + (this.lastTokenValueLength ?? 0); this.selectionCaretOffset = null; this.suppressNextFocusCaretPlacement = true; setTimeout(() => { if (!this.isAlive()) { return; } this.getContentElement().focus({ preventScroll: true }); if (_getDocument6(this.beans).activeElement === this.getContentElement()) { this.suppressNextFocusCaretPlacement = false; } restoreCaret(this.beans, this.getContentElement(), caret); }); } replaceTokenAtMatch(token, nextRef, tokenIndexOverride) { const value = this.getCurrentValue(); const updated = value.slice(0, token.start) + nextRef + value.slice(token.end); this.applyFormulaValueChange({ currentValue: value, nextValue: updated, caret: token.start + nextRef.length, updateTracking: () => { this.updateLastTokenTracking(nextRef, token.start, token.start); } }); return { previousRef: token.ref, tokenIndex: tokenIndexOverride ?? token.index }; } getValueOffsetFromCaret(caretOffset) { const container = this.getContentElement(); let caretRemaining = caretOffset; let valueOffset = 0; for (const child of Array.from(container.childNodes)) { const caretLen = _getNodeTextLength(child); const valueLen = getNodeText(child).length; if (caretRemaining <= caretLen) { return valueOffset + (caretLen === valueLen ? caretRemaining : 0); } caretRemaining -= caretLen; valueOffset += valueLen; } return this.currentValue.length; } getTokenInsertOffsets(isNew) { return this.getCaretOffsets(this.getCurrentValue(), { useCachedCaret: true, useCachedValueOffset: !isNew }); } getCaretOffsetsForAutocomplete(value) { return this.getCaretOffsets(value); } getCaretOffsets(value, options = { useCachedCaret: false, useCachedValueOffset: false }) { const { beans } = this; const { useCachedCaret, useCachedValueOffset } = options; const contentElement = this.getContentElement(); const caretOffset = useCachedCaret ? this.selectionCaretOffset ?? getCaretOffset(beans, contentElement, value) ?? this.currentValue.length : getCaretOffset(beans, contentElement, value); if (caretOffset == null) { return null; } const valueOffset = useCachedValueOffset && this.lastTokenValueOffset != null ? this.lastTokenValueOffset : this.getValueOffsetFromCaret(caretOffset); if (valueOffset == null) { return null; } return { caretOffset, valueOffset }; } updateLastTokenTracking(ref, caretOffset, valueOffset) { const previousRef = this.lastTokenRef; this.lastTokenValueOffset = valueOffset; this.lastTokenValueLength = ref.length; this.lastTokenCaretOffset = caretOffset; this.lastTokenRef = ref; return previousRef; } getFormulaState(text) { const hasFormulaPrefix = text.trimStart().startsWith("="); const isFormula = this.beans.formula?.isFormula(text) ?? hasFormulaPrefix; return { isFormula, hasFormulaPrefix }; } dispatchValueChanged() { this.dispatchLocalEvent({ type: "fieldValueChanged" }); } applyPlainValue(value, params) { this.formulaColorByRef.clear(); this.renderPlainValue(value, params.caret); this.setEditorValue(value, params.silent); if (params.dispatch) { this.dispatchValueChanged(); } this.autocompleteFeature?.onPlainValueUpdated(); } applyFormulaValue(value, params) { this.updateFormulaColorsFromValue(value); this.renderFormula({ value, currentValue: params.currentValue ?? this.getCurrentValue(), caret: params.caret ?? void 0 }); this.setEditorValue(value, params.silent); if (params.dispatch) { this.dispatchValueChanged(); } this.autocompleteFeature?.onFormulaValueUpdated(); } applyFormulaValueChange(params) { const { currentValue, nextValue, caret } = params; this.updateFormulaColorsFromValue(nextValue); params.updateTracking?.(); this.setEditorValue(nextValue); this.renderFormula({ currentValue, value: nextValue, caret }); this.dispatchValueChanged(); this.autocompleteFeature?.onFormulaValueUpdated(); } replaceTokenRef(previousRef, nextRef, colorIndex, tokenIndex) { const contentElement = this.getContentElement(); let token; if (tokenIndex != null) { token = contentElement.querySelector( `.ag-formula-token[data-formula-token-index="${tokenIndex}"]` ) ?? void 0; if (token && getTokenRef(token) !== previousRef) { token = void 0; } } if (!token) { token = Array.from(contentElement.querySelectorAll(".ag-formula-token")).find( (node) => getTokenRef(node) === previousRef ); } if (!token) { return null; } const caretOffset = getOffsetBeforeNode(contentElement, token); const valueOffset = getOffsetBeforeNode(contentElement, token, true); if (caretOffset == null || valueOffset == null) { return null; } const value = this.getCurrentValue(); if (colorIndex != null) { this.formulaColorByRef.set(nextRef, colorIndex); } const updated = value.slice(0, valueOffset) + nextRef + value.slice(valueOffset + previousRef.length); const resolvedIndex = getTokenIndex(token); this.applyFormulaValueChange({ currentValue: value, nextValue: updated, caret: caretOffset + nextRef.length, updateTracking: () => { this.updateLastTokenTracking(nextRef, caretOffset, valueOffset); } }); return resolvedIndex ?? tokenIndex ?? null; } }; var shouldUseTokenColors = (beans) => { const { gos, rangeSvc } = beans; const canCreateRanges = !!rangeSvc && !!gos.get("cellSelection"); return canCreateRanges; }; var getOrderedRefs = (beans, value) => { const refsInOrder = []; const seen = /* @__PURE__ */ new Set(); for (const match of getRefTokenMatchesForFormula(beans, value)) { const ref = match.ref; if (seen.has(ref)) { continue; } seen.add(ref); refsInOrder.push(ref); } return refsInOrder; }; var getTokenMatchAtOffset = (beans, value, offset) => { for (const match of getRefTokenMatchesForFormula(beans, value)) { if (offset >= match.start && offset <= match.end) { return { ref: match.ref, start: match.start, end: match.end, index: match.index }; } } return null; }; var getRawTokenMatchAtOffset = (value, offset) => { for (const match of getRefTokenMatches(value)) { if (offset >= match.start && offset <= match.end) { return { ref: match.ref, start: match.start, end: match.end, index: match.index }; } } return null; }; var shouldInsertTokenAtOffset = (value, offset) => { const previousChar = getPreviousNonSpaceChar(value, offset); return previousChar == null || TOKEN_INSERT_AFTER_CHARS.has(previousChar); }; var tokenize = (beans, value, getColorIndexForToken) => { const nodes = []; let lastIndex = 0; const matches = getRefTokenMatchesForFormula(beans, value); const doc = _getDocument6(beans); for (const match of matches) { if (match.start > lastIndex) { nodes.push(doc.createTextNode(formatForDisplay(value.slice(lastIndex, match.start)))); } const colorIndex = getColorIndexForToken(match.index); nodes.push(createReferenceNode(match.ref, colorIndex, colorIndex != null, match.index)); lastIndex = match.end; } if (lastIndex < value.length) { nodes.push(doc.createTextNode(formatForDisplay(value.slice(lastIndex)))); } if (!nodes.length) { nodes.push(doc.createTextNode("")); } return nodes; }; var createReferenceNode = (ref, colorIndex, useTokenColors, tokenIndex) => { const attrs = { "aria-label": ref, "data-formula-ref": ref, "data-formula-token-index": tokenIndex.toString() }; let tokenClass; if (useTokenColors && colorIndex != null) { const classes = getColorClassesForRef(ref, colorIndex); tokenClass = classes.tokenClass; attrs["data-formula-range-class"] = classes.rangeClass; } const node = _createElement16({ tag: "span", cls: "ag-formula-token", attrs, children: ref }); if (tokenClass) { node.classList.add(tokenClass); } return node; }; var renderFormula = (params) => { const { beans, contentElement, currentValue, value, getColorIndexForToken, caret } = params; const caretOffset = caret ?? getCaretOffset(beans, contentElement, currentValue); const maxCaret = value.length; contentElement.textContent = ""; for (const node of tokenize(beans, value, getColorIndexForToken)) { contentElement.append(node); } const targetCaret = caretOffset != null ? Math.min(caretOffset, maxCaret) : null; restoreCaret(beans, contentElement, targetCaret); }; var getOffsetBeforeNode = (container, node, useValueLength = false) => { if (!container.contains(node)) { return null; } let offset = 0; for (const child of Array.from(container.childNodes)) { if (child === node) { return offset; } offset += useValueLength ? getNodeText(child).length : _getNodeTextLength(child); } return null; }; var serializeContent = (contentElement) => { let output = ""; contentElement.childNodes.forEach((child) => { output += getNodeText(child); }); return output; }; var getNodeText = (node) => { if (node.nodeType === Node.TEXT_NODE) { return formatForValue(node.textContent ?? ""); } if (node.nodeType === Node.ELEMENT_NODE) { return Array.from(node.childNodes).map((child) => getNodeText(child)).join(""); } return ""; }; var _getNodeTextLength = (node) => { if (node.nodeType === Node.TEXT_NODE) { return node.textContent?.length ?? 0; } if (node.nodeType === Node.ELEMENT_NODE) { return Array.from(node.childNodes).reduce((sum, child) => sum + _getNodeTextLength(child), 0); } return 0; }; var findNodeAtOffset = (root, offset) => { let remaining = offset; for (let i = 0; i < root.childNodes.length; i++) { const child = root.childNodes[i]; const length = _getNodeTextLength(child); if (remaining > length) { remaining -= length; continue; } if (child.nodeType === Node.TEXT_NODE) { return { node: child, localOffset: remaining }; } return findNodeAtOffset(child, remaining); } return { node: root, localOffset: root.childNodes.length }; }; var restoreCaret = (beans, contentElement, offset) => { if (offset == null) { return; } const win = _getWindow(beans); const doc = _getDocument6(beans); const selection = win.getSelection(); const range = doc.createRange(); const { node, localOffset } = findNodeAtOffset(contentElement, offset); if (!node || !selection || !contentElement.isConnected || !node.isConnected) { return; } range.setStart(node, localOffset); range.collapse(true); selection.removeAllRanges(); try { selection.addRange(range); } catch { } }; var getCaretOffset = (beans, contentElement, currentValue) => { const win = _getWindow(beans); const selection = win.getSelection(); if (!selection || selection.rangeCount === 0) { return currentValue?.length ?? null; } const range = selection.getRangeAt(0); if (!contentElement.contains(range.startContainer)) { return currentValue?.length ?? null; } if (range.startContainer === contentElement) { let offset2 = 0; for (let i = 0; i < range.startOffset; i++) { offset2 += _getNodeTextLength(contentElement.childNodes[i]); } return offset2; } let offset = range.startOffset; let node = range.startContainer; while (node && node !== contentElement) { let sibling = node.previousSibling; while (sibling) { offset += _getNodeTextLength(sibling); sibling = sibling.previousSibling; } node = node.parentNode; } return offset; }; var getTokenRef = (tokenEl) => formatForValue(tokenEl.textContent ?? tokenEl.dataset.formulaRef ?? ""); var getTokenIndex = (tokenEl) => { const raw = tokenEl.dataset.formulaTokenIndex; if (!raw) { return null; } const parsed = parseInt(raw, 10); return Number.isFinite(parsed) ? parsed : null; }; var formatForDisplay = (text) => text.replace(/[/*]/g, (match) => DISPLAY_OPERATOR_LOOKUP[match] ?? match); var formatForValue = (text) => text.replace(/[÷×]/g, (match) => VALUE_OPERATOR_LOOKUP[match] ?? match); // packages/ag-grid-enterprise/src/formula/i18n.ts var FORMULA_ERRORS = { 1: ["invalidFormulaValidation", "Invalid formula."], 2: ["formulaParseInvalidCellReference", "Invalid cell reference: ${variable}."], 3: ["formulaParseInvalidRangeEndReference", "Invalid range end reference."], 4: ["formulaParseUnterminatedString", "Unterminated string."], 5: ["formulaParseUnexpectedCharacter", "Unexpected character: ${variable}."], 6: ["formulaParseOperatorStackUnderflow", "Operator stack underflow."], 7: ["formulaParseMissingOperand", "Missing operand for '${variable}'."], 8: ["formulaParseInternalUnexpectedFrameDuringReduction", "Internal error: unexpected frame during reduction."], 9: ["formulaParseInternalUnexpectedFrameBeforeOpenParen", "Internal error: unexpected frame before '('."], 10: ["formulaParseMisplacedComma", "Misplaced comma."], 11: ["formulaParseCommaOutsideFunctionCall", "Comma outside of a function call."], 12: ["formulaParseInternalUnexpectedFrameBeforeCloseParen", "Internal error: unexpected frame before ')'."], 13: ["formulaParseMismatchedParentheses", "Mismatched parentheses."], 14: ["formulaParseUnsupportedOperand", "Unsupported operand: ${variable}."], 15: [ "formulaParseMismatchedParenthesesOrUnfinishedFunctionCall", "Mismatched parentheses or unfinished function call." ], 16: ["formulaParseInvalidExpression", "Invalid expression."], 17: ["formulaParseFormulasMustBeginWithEquals", "Formulas must begin with =."], 18: [ "formulaSerializeStringContainsQuote", 'String contains a quote (") which the tokenizer does not support.', "#PARSE!" ], 19: [ "formulaSerializeCannotProduceAbsoluteColumnLabelFromId", "Cannot produce absolute COLUMN label from id '${variable}'." ], 20: [ "formulaSerializeCannotProduceAbsoluteRowIndexFromId", "Cannot produce absolute ROW index from id '${variable}'." ], 21: ["formulaSerializeCannotProduceRowIndexFromId", "Cannot produce ROW index from id '${variable}'."], 22: ["formulaSerializeCannotMapColumnIdToA1Label", "Cannot map column id '${variable}' to A1 label."], 23: ["formulaSerializeCannotParseAbsoluteRowIndex", "Cannot parse absolute row index '${variable}'."], 24: ["formulaSerializeCannotMapRowIdToA1Index", "Cannot map row id '${variable}' to A1 index."], 25: ["formulaEvalRangeNotAllowedInScalarContext", "Range is not allowed in scalar context."], 26: ["formulaEvalUnknownReferenceToCell", "Unknown reference to cell.", "#REF!"], 27: ["formulaEvalUnsupportedOperation", "Unsupported operation ${variable}.", "#NAME?"], 28: ["formulaEvalInvalidAbsoluteRow", "Invalid absolute row.", "#REF!"], 29: ["formulaEvalUnrecognisedRowId", "Unrecognised row id.", "#REF!"], 30: ["formulaEvalInvalidAbsoluteColumn", "Invalid absolute column.", "#REF!"], 31: ["formulaEvalUnrecognisedColumnId", "Unrecognised column id.", "#REF!"], 32: ["formulaEvalUnrecognisedRowInRange", "Unrecognised row in range.", "#REF!"], 33: ["formulaEvalUnrecognisedReferenceToCell", "Unrecognised reference to cell.", "#REF!"], 34: ["formulaEvalIncompleteRangeReference", "Incomplete range reference.", "#REF!"], 35: ["formulaFunctionExpectedExactlyArguments", "${variable}: expected exactly ${variable} arguments."], 36: ["formulaFunctionExpectedAtMostArguments", "${variable}: expected at most ${variable} arguments."], 37: ["formulaFunctionExpectedAtLeastArguments", "${variable}: expected at least ${variable} arguments."], 38: [ "formulaFunctionInvalidCriteriaWildcardsWithComparator", "Invalid criteria: wildcards with comparator.", "#VALUE!" ], 39: ["formulaFunctionNonNumericArgument", "${variable}: non-numeric argument.", "#VALUE!"], 40: ["formulaFunctionDivisionByZero", "${variable}: division by zero.", "#DIV/0!"], 41: ["formulaFunctionCannotCombineDatesWithBigInt", "${variable}: cannot combine dates with BigInt.", "#VALUE!"], 42: [ "formulaFunctionRequiresAtLeastOneNumericValue", "${variable}: requires at least one numeric value.", "#PARSE!" ], 43: ["formulaFunctionRequiresAtLeastOneValue", "${variable}: requires at least one value."], 44: ["formulaFunctionAllValuesMustBeNumbers", "${variable}: all values must be numbers.", "#VALUE!"], 45: ["formulaFunctionArgumentMustBeRange", "${variable}: ${variable} argument must be a range.", "#VALUE!"], 46: ["formulaFunctionArgumentMustBeValue", "${variable}: ${variable} argument must be a value.", "#VALUE!"], 47: ["formulaFunctionRangesHaveDifferentSizes", "${variable}: ranges have different sizes.", "#VALUE!"], 48: ["formulaFunctionValuesMustBeNumeric", "${variable}: values must be numeric.", "#VALUE!"], 49: ["formulaFunctionValuesMustBeIntegers", "${variable}: values must be integers.", "#VALUE!"], 50: ["formulaFunctionUnsupportedValueType", "${variable}: unsupported value type.", "#VALUE!"], 51: ["formulaServiceCircularReference", "Circular reference.", "#CIRCREF!"], 52: ["formulaServiceExpectedParsableFormula", "Expected parsable formula.", "#PARSE!"], 53: ["formulaServiceInternalSchedulingError", "Internal scheduling error."], 54: ["formulaFunctionDivNonNumericArgument", "DIV: non-numeric argument.", "#VALUE!"], 55: ["formulaFunctionDivDivisionByZero", "DIV: division by zero.", "#DIV/0!"], 56: ["formulaFunctionSumCannotCombineDatesWithBigInt", "SUM: cannot combine dates with BigInt.", "#VALUE!"], 57: ["formulaFunctionSumRequiresAtLeastOneNumericValue", "SUM: requires at least one numeric value.", "#PARSE!"], 58: ["formulaFunctionAvgRequiresAtLeastOneValue", "AVG: requires at least one value."], 59: ["formulaFunctionMedianAllValuesMustBeNumbers", "MEDIAN: all values must be numbers.", "#VALUE!"], 60: ["formulaFunctionMedianRequiresAtLeastOneValue", "MEDIAN: requires at least one value."], 61: ["formulaFunctionSumifFirstArgumentMustBeRange", "SUMIF: first argument must be a range.", "#VALUE!"], 62: [ "formulaFunctionSumifSecondArgumentMustBeValue", "SUMIF: second argument must be a value (criteria).", "#VALUE!" ], 63: [ "formulaFunctionSumifThirdArgumentMustBeRange", "SUMIF: third argument must be a range (sum_range).", "#VALUE!" ], 64: ["formulaFunctionSumifRangesHaveDifferentSizes", "SUMIF: ranges have different sizes.", "#VALUE!"], 65: ["formulaFunctionCountifFirstArgumentMustBeRange", "COUNTIF: first argument must be a range.", "#VALUE!"], 66: [ "formulaFunctionCountifSecondArgumentMustBeValue", "COUNTIF: second argument must be a value (criteria).", "#VALUE!" ], 67: ["formulaFunctionConcatUnsupportedValueType", "CONCAT: unsupported value type.", "#VALUE!"], 68: ["formulaFunctionMinRequiresAtLeastOneValue", "MIN: requires at least one value."], 69: ["formulaFunctionMaxRequiresAtLeastOneValue", "MAX: requires at least one value."], 70: ["formulaFunctionPercentNonNumericArgument", "PERCENT: non-numeric argument.", "#VALUE!"], 71: ["formulaFunctionPowerNonNumericArgument", "POWER: non-numeric argument.", "#VALUE!"] }; var interpolateVariables = (template, variableValues) => { if (!variableValues?.length) { return template; } let localisedText = template; let found = 0; while (found < variableValues.length) { const idx = localisedText.indexOf("${variable}"); if (idx === -1) { break; } localisedText = localisedText.replace("${variable}", variableValues[found++]); } return localisedText; }; var normaliseVariableValues = (values) => { if (!values?.length) { return void 0; } return values.map((value) => String(value)); }; var getFormulaErrorDefinition = (errorId) => { return FORMULA_ERRORS[errorId]; }; var getFormulaErrorDefaultMessage = (errorId, variableValues) => { const [, defaultMessage] = getFormulaErrorDefinition(errorId); return interpolateVariables(defaultMessage, normaliseVariableValues(variableValues)); }; var translateFormulaError = (translate, errorId, variableValues) => { const [localeKey, defaultMessage] = getFormulaErrorDefinition(errorId); const normalizedVariableValues = normaliseVariableValues(variableValues); return translate(localeKey, defaultMessage, normalizedVariableValues); }; // packages/ag-grid-enterprise/src/formula/editor/formulaCellEditor.ts var FormulaCellEditor = class extends AgAbstractCellEditor2 { constructor() { super({ tag: "div", cls: "ag-cell-edit-wrapper" }); this.eEditor = RefPlaceholder46; this.focusAfterAttached = false; } initialiseEditor(params) { const formulaInputField = this.createManagedBean(new AgFormulaInputField()); this.eEditor = formulaInputField; formulaInputField.addCss("ag-cell-editor"); this.appendChild(formulaInputField); this.addManagedElementListeners(formulaInputField.getContentElement(), { keydown: (event) => this.onFormulaInputKeyDown(event, params.onKeyDown) }); const { eventKey, cellStartedEdit } = params; let startValue; if (cellStartedEdit) { this.focusAfterAttached = true; if (eventKey === KeyCode33.BACKSPACE || eventKey === KeyCode33.DELETE) { startValue = ""; } else if (eventKey && eventKey.length === 1) { startValue = eventKey; } else { startValue = this.getStartValue(params); } } else { startValue = this.getStartValue(params); } const initialValue = startValue == null ? "" : String(startValue); this.eEditor.setEditingCellRef(params.column, params.rowIndex); this.eEditor.setValue(initialValue, true); } onFormulaInputKeyDown(event, onKeyDown) { const { key } = event; if (key !== KeyCode33.TAB || event.defaultPrevented) { return; } const { focusSvc } = this.beans; const prevFocus = focusSvc?.getFocusedCell(); this.eEditor.withSelectionChangeHandlingSuppressed(() => { onKeyDown?.(event); }); const nextFocus = focusSvc?.getFocusedCell(); let focusChanged = false; if (prevFocus && nextFocus) { const { rowIndex: prevRowIndex, rowPinned: prevRowPinned, column: prevColumn } = prevFocus; const { rowIndex: nextRowIndex, rowPinned: nextRowPinned, column: nextColumn } = nextFocus; focusChanged = prevRowIndex !== nextRowIndex || prevRowPinned !== nextRowPinned || prevColumn !== nextColumn; } const { defaultPrevented } = event; if (defaultPrevented || focusChanged) { event.preventDefault(); } event.stopPropagation(); } getStartValue(params) { const { value } = params; return value?.toString() ?? value; } isPopup() { return false; } afterGuiAttached() { if (!this.focusAfterAttached) { return; } const { beans, eEditor } = this; if (!_isBrowserSafari2()) { this.focusIn(); } _placeCaretAtEnd2(beans, eEditor.getContentElement()); } focusIn() { this.eEditor.getContentElement().focus({ preventScroll: true }); } getValue() { const rawValue = this.eEditor.getCurrentValue(); const { value, parseValue } = this.params; if (typeof rawValue === "string" && this.isFormulaText(rawValue)) { return rawValue; } if (rawValue == null && value == null) { return value; } return parseValue(String(rawValue)); } getValidationElement() { return this.eEditor.getContentElement(); } getValidationErrors() { const { params } = this; const value = this.eEditor.getCurrentValue(); const translate = this.getLocaleTextFunc(); const { getValidationErrors, validateFormulas } = params; let internalErrors = null; const shouldValidate = validateFormulas === true || !!getValidationErrors; if (shouldValidate && typeof value === "string" && this.isFormulaText(value)) { const normalised = this.beans.formula?.normaliseFormula(value, true); if (!normalised) { internalErrors = [translateFormulaError(translate, 1)]; } } if (getValidationErrors) { return getValidationErrors({ value, internalErrors, cellEditorParams: params }); } return internalErrors; } isFormulaText(value) { const text = value == null ? "" : String(value); return this.beans.formula?.isFormula(text) ?? text.trimStart().startsWith("="); } }; // packages/ag-grid-enterprise/src/formula/formula.css-GENERATED.ts var formulaCSS = ( /*css*/ `.formula-error:after{background-color:var(--ag-invalid-color);content:"";height:12px;position:absolute;top:-6px;width:12px}:where(.ag-ltr) .formula-error:after{right:-6px;transform:rotate(45deg)}:where(.ag-rtl) .formula-error:after{left:-6px;transform:rotate(-45deg)}` ); // packages/ag-grid-enterprise/src/formula/formulaDataService.ts import { BeanStub as BeanStub76, _addGridCommonParams as _addGridCommonParams26, _isExpressionString as _isExpressionString2 } from "ag-grid-community"; var FormulaDataService = class extends BeanStub76 { constructor() { super(...arguments); this.beanName = "formulaDataSvc"; this.hasSource = false; } postConstruct() { const dataSource = this.gos.get("formulaDataSource"); if (dataSource) { this.setDataSource(dataSource); } } hasDataSource() { return this.hasSource; } getFormula(params) { const formula = this.dataSource?.getFormula(params); return _isExpressionString2(formula) ? formula : void 0; } setFormula(params) { this.dataSource?.setFormula(params); } setDataSource(dataSource) { this.dataSource = dataSource; this.hasSource = true; dataSource.init?.(this.createInitParams()); } createInitParams() { return _addGridCommonParams26(this.gos, {}); } destroy() { this.dataSource?.destroy?.(); super.destroy(); } }; // packages/ag-grid-enterprise/src/formula/formulaInputManagerService.ts import { BeanStub as BeanStub77 } from "ag-grid-community"; var FormulaInputManagerService = class extends BeanStub77 { constructor() { super(...arguments); this.beanName = "formulaInputManager"; this.activeEditor = null; this.activeEditorDeactivate = null; } postConstruct() { this.registerRangeSelectionExtension(); } registerActiveEditor(editorId, onDeactivate) { if (this.activeEditor === editorId && this.activeEditorDeactivate === onDeactivate) { return false; } const previousDeactivate = this.activeEditorDeactivate; if (previousDeactivate && previousDeactivate !== onDeactivate) { previousDeactivate(); } this.activeEditor = editorId; this.activeEditorDeactivate = onDeactivate; return true; } unregisterActiveEditor(editorId, onDeactivate) { if (this.activeEditor === editorId && this.activeEditorDeactivate === onDeactivate) { this.activeEditor = null; this.activeEditorDeactivate = null; } } isActiveEditor(editorId) { return this.activeEditor === editorId; } shouldSuppressRangeSelection(eventTarget) { const target = eventTarget; if (!target?.closest) { return false; } if (this.activeEditor != null) { return !!target.closest(".ag-cell-editor"); } return !!target.closest(".ag-formula-input-field"); } registerRangeSelectionExtension() { const rangeSvc = this.beans.rangeSvc; if (!rangeSvc) { return; } rangeSvc.registerRangeSelectionExtension(this); this.addDestroyFunc(() => rangeSvc.unregisterRangeSelectionExtension?.(this)); } }; // packages/ag-grid-enterprise/src/formula/formulaService.ts import { BeanStub as BeanStub78, _convertColumnEventSourceType as _convertColumnEventSourceType3, _isExpressionString as _isExpressionString4, _warn as _warn53 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/formula/ast/parsers.ts import { _getClientSideRowModel as _getClientSideRowModel2, _isExpressionString as _isExpressionString3 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/formula/ast/operators.ts var OP_DEFS = [ { symbol: "%", fixity: "postfix", precedence: 100 }, { symbol: "-", fixity: "prefix", precedence: 90 }, { symbol: "+", fixity: "prefix", precedence: 90 }, { symbol: "^", fixity: "infix", precedence: 80, associativity: "right" }, { symbol: "*", fixity: "infix", precedence: 70, associativity: "left", isAssociative: true }, { symbol: "/", fixity: "infix", precedence: 70, associativity: "left" }, { symbol: "+", fixity: "infix", precedence: 60, associativity: "left", isAssociative: true }, { symbol: "-", fixity: "infix", precedence: 60, associativity: "left" }, { symbol: "&", fixity: "infix", precedence: 55, associativity: "left", isAssociative: true }, { symbol: "=", fixity: "infix", precedence: 50, associativity: "left" }, { symbol: "<>", fixity: "infix", precedence: 50, associativity: "left" }, { symbol: ">=", fixity: "infix", precedence: 50, associativity: "left" }, { symbol: "<=", fixity: "infix", precedence: 50, associativity: "left" }, { symbol: ">", fixity: "infix", precedence: 50, associativity: "left" }, { symbol: "<", fixity: "infix", precedence: 50, associativity: "left" } ]; var symbolOperatorMap = /* @__PURE__ */ new Map(); for (const d of OP_DEFS) { const s2 = symbolOperatorMap.get(d.symbol) ?? []; s2.push(d); symbolOperatorMap.set(d.symbol, s2); } function getDefBySymbol(symbol, fixity) { const arr = symbolOperatorMap.get(symbol) ?? []; return fixity ? arr.find((d) => d.fixity === fixity) : arr[0]; } var OP_SYMBOLS_DESC = [...new Set(OP_DEFS.map((d) => d.symbol))].sort((a, b) => b.length - a.length); var OP_BY_SYMBOL = symbolOperatorMap; // packages/ag-grid-enterprise/src/formula/ast/utils.ts var normaliseVariableValues2 = (values) => { if (!values?.length) { return void 0; } return values.map((value) => String(value)); }; var FormulaError = class extends Error { constructor(messageOrErrorId, typeOrVariableValues, typeOverride) { const isMessage = typeof messageOrErrorId === "string"; const variableValues = !isMessage && Array.isArray(typeOrVariableValues) ? normaliseVariableValues2(typeOrVariableValues) : void 0; const resolvedMessage = isMessage ? messageOrErrorId : getFormulaErrorDefaultMessage(messageOrErrorId, variableValues); super(resolvedMessage); this.name = "FormulaError"; if (isMessage) { this.type = typeof typeOrVariableValues === "string" ? typeOrVariableValues : "#ERROR!"; this.errorId = null; this.localeKey = null; this.defaultMessage = messageOrErrorId; this.variableValues = void 0; } else { const [localeKey, defaultMessage, defaultType] = getFormulaErrorDefinition(messageOrErrorId); this.type = typeOverride ?? defaultType ?? "#ERROR!"; this.errorId = messageOrErrorId; this.localeKey = localeKey; this.defaultMessage = defaultMessage; this.variableValues = variableValues; } } getTranslatedMessage(translate) { if (!this.localeKey) { return this.message; } return translate(this.localeKey, this.defaultMessage, this.variableValues); } }; var FormulaParseError = class extends FormulaError { constructor(errorId, errorStart, errorEnd, variableValues) { super(errorId, variableValues, "#PARSE!"); this.errorStart = errorStart; this.errorEnd = errorEnd; } }; // packages/ag-grid-enterprise/src/formula/ast/parsers.ts var parseOperand = (beans, operand, unsafe) => { const trimmed = operand.trim(); if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length > 2) { return trimmed.slice(1, -1); } if (trimmed.toLowerCase() === "true") { return true; } if (trimmed.toLowerCase() === "false") { return false; } const num = Number(trimmed); if (!isNaN(num)) { return num; } const parsed = parseA1Ref(trimmed); if (parsed) { const { startCol, startRow, startColAbsolute, startRowAbsolute, endCol, endRow, endColAbsolute, endRowAbsolute } = parsed; const toCell = (colAbs, colStr, rowAbs, rowStr, unsafe2) => { const col = colAbs || unsafe2 ? colStr.toUpperCase() : beans.formula?.getColByRef(colStr)?.colId; const row = rowAbs || unsafe2 ? rowStr : _getClientSideRowModel2(beans)?.getFormulaRow(Number(rowStr) - 1)?.id; if (col == null || row == null) { throw new FormulaParseError(2, 0, 0, [trimmed]); } return { column: { id: col, absolute: colAbs }, row: { id: row, absolute: rowAbs } }; }; const start = toCell(startColAbsolute, startCol, startRowAbsolute, startRow, unsafe); if (endCol && endRow) { const end = toCell(endColAbsolute ?? false, endCol, endRowAbsolute ?? false, endRow, unsafe); start.endColumn = end.column; start.endRow = end.row; } return start; } return null; }; function tokenize2(expr) { const tokens = []; let i = 0; const lexCellRange = (s2, start) => { let j = start; const dollar = () => s2[j] === "$" ? (j++, true) : false; const letters = () => { const k = j; while (j < s2.length && /[A-Za-z]/.test(s2[j])) { j++; } return j > k; }; const digits = () => { const k = j; while (j < s2.length && /[0-9]/.test(s2[j])) { j++; } return j > k; }; const parseCell = () => { const j0 = j; dollar(); if (!letters()) { j = j0; return false; } dollar(); if (!digits()) { j = j0; return false; } return true; }; if (!parseCell()) { return 0; } if (s2[j] === ":") { const colonPos = j; j++; if (!parseCell()) { throw new FormulaParseError(3, colonPos, j); } } const ref = s2.slice(start, j); if (!isStandaloneRefToken(s2, start, ref)) { return 0; } return j - start; }; while (i < expr.length) { const ch = expr[i]; if (/\s/.test(ch)) { i++; continue; } if (ch === '"') { let j = i + 1; while (j < expr.length && expr[j] !== '"') { j++; } if (j >= expr.length) { throw new FormulaParseError(4, i, expr.length); } tokens.push(expr.slice(i, j + 1)); i = j + 1; continue; } if (/[0-9]/.test(ch) || ch === "." && /[0-9]/.test(expr[i + 1])) { let j = i + 1; while (j < expr.length && /[0-9.]/.test(expr[j])) { j++; } tokens.push(expr.slice(i, j)); i = j; continue; } if (ch === "$" || isFormulaIdentStart(ch)) { const len = lexCellRange(expr, i); if (len > 0) { tokens.push(expr.slice(i, i + len)); i += len; continue; } let j = i + 1; while (j < expr.length && isFormulaIdentChar(expr[j])) { j++; } tokens.push(expr.slice(i, j)); i = j; continue; } if (ch === "(" || ch === ")" || ch === ",") { tokens.push(ch); i++; continue; } const firstMatch = OP_SYMBOLS_DESC.find((sym) => expr.startsWith(sym, i)); if (!firstMatch) { throw new FormulaParseError(5, i, i + 1, [ch]); } tokens.push(firstMatch); i += firstMatch.length; } return tokens; } function shouldReduce(top, incoming) { if (top.fixity !== "infix" || incoming.fixity !== "infix") { return true; } if (top.associativity === "right" && top.precedence === incoming.precedence) { return false; } return top.precedence >= incoming.precedence; } function pickOpDefForContext(symbol, prevToken) { const defs = OP_BY_SYMBOL.get(symbol); if (!defs) { return null; } const prevIsOperator = prevToken !== void 0 && OP_BY_SYMBOL.has(prevToken); const prevIsOpenOrComma = prevToken === "(" || prevToken === ","; const prevIsValueLike = prevToken !== void 0 && !prevIsOperator && !prevIsOpenOrComma && prevToken !== "("; if (prevIsValueLike || prevToken === ")") { return defs.find((d) => d.fixity === "postfix") ?? defs.find((d) => d.fixity === "infix") ?? null; } return defs.find((d) => d.fixity === "prefix") ?? defs.find((d) => d.fixity === "infix") ?? null; } function parseExpression(beans, expr, unsafe) { const tokens = tokenize2(expr); const output = []; const ops = []; const applyTop = () => { const frame = ops.pop(); if (!frame) { throw new FormulaParseError(6, 0, 0); } if (frame.kind === "op") { const def = frame.def; if (def.fixity !== "infix") { const right2 = output.pop(); if (!right2) { throw new FormulaParseError(7, 0, 0, [def.symbol]); } if (def.symbol === "+" && def.fixity === "prefix") { output.push(right2); return; } if (def.fixity === "postfix" && def.symbol === "%") { output.push({ type: "operation", operation: def.symbol, operands: [right2] }); return; } if (def.symbol === "-" && def.fixity === "prefix") { output.push({ type: "operation", operation: "-", operands: [{ type: "operand", value: 0 }, right2] }); } else { output.push({ type: "operation", operation: def.symbol, operands: [right2] }); } return; } const right = output.pop(); const left = output.pop(); if (!left || !right) { throw new FormulaParseError(7, 0, 0, [def.symbol]); } output.push({ type: "operation", operation: def.symbol, operands: [left, right] }); return; } throw new FormulaParseError(8, 0, 0); }; let i = 0; while (i < tokens.length) { const token = tokens[i]; if (isFormulaIdentStart(token[0]) && tokens[i + 1] === "(") { const name = token; ops.push({ kind: "function", name, args: [] }); ops.push({ kind: "parenthesis", outLen: output.length }); i += 2; continue; } if (token === "(") { ops.push({ kind: "parenthesis", outLen: output.length }); i++; continue; } if (token === ",") { while (true) { const top = ops[ops.length - 1]; if (!top || top.kind === "parenthesis") { break; } if (top.kind === "op") { applyTop(); } else { throw new FormulaParseError(9, i, i + 1); } } const paren = ops[ops.length - 1]; if (!paren || paren.kind !== "parenthesis") { throw new FormulaParseError(10, i, i + 1); } const maybeFunction = ops[ops.length - 2]; if (!maybeFunction || maybeFunction.kind !== "function") { throw new FormulaParseError(11, i, i + 1); } if (output.length > paren.outLen) { maybeFunction.args.push(output.pop()); } i++; continue; } if (token === ")") { while (true) { const top = ops[ops.length - 1]; if (!top || top.kind === "parenthesis") { break; } if (top.kind === "op") { applyTop(); } else { throw new FormulaParseError(12, i, i + 1); } } const paren = ops[ops.length - 1]; if (!paren || paren.kind !== "parenthesis") { throw new FormulaParseError(13, i, i + 1); } const parenOutLen = paren.outLen; ops.pop(); if (ops[ops.length - 1]?.kind === "function") { const fn = ops.pop(); if (output.length > parenOutLen) { fn.args.push(output.pop()); } output.push({ type: "operation", operation: fn.name, operands: fn.args }); } i++; continue; } const incoming = OP_BY_SYMBOL.has(token) ? pickOpDefForContext(token, tokens[i - 1]) : null; if (incoming) { while (true) { const top = ops[ops.length - 1]; if (!top || top.kind !== "op") { break; } if (shouldReduce(top.def, incoming)) { applyTop(); } else { break; } } ops.push({ kind: "op", def: incoming }); i++; continue; } const parsed = parseOperand(beans, token, unsafe); if (parsed == null) { throw new FormulaParseError(14, 0, token.length, [token]); } output.push({ type: "operand", value: parsed }); i++; } while (ops.length) { const top = ops[ops.length - 1]; if (top.kind === "op") { applyTop(); } else { throw new FormulaParseError(15, 0, 0); } } if (output.length !== 1) { throw new FormulaParseError(16, 0, 0); } return output[0]; } var parseFormula = (beans, formula, unsafe = false) => { if (!_isExpressionString3(formula)) { throw new FormulaParseError(17, 0, 1); } const body = formula.slice(1).trim(); return normalizeRefCells(parseExpression(beans, body, unsafe)); }; function isOperation(node, name) { return node.type === "operation" && node.operation.toUpperCase() === name.toUpperCase(); } function asBool(node, def = false) { if (!node) { return def; } if (node.type !== "operand") { return def; } return !!node.value; } function asStringish(node) { if (!node || node.type !== "operand") { return null; } const v = node.value; if (typeof v === "string") { return v; } if (typeof v === "number" || typeof v === "boolean") { return String(v); } return null; } function extractColumnRef(node) { if (!isOperation(node, "COLUMN")) { return null; } const id = asStringish(node.operands[0]); if (id == null) { return null; } const absolute = asBool(node.operands[1], false); return { id, absolute }; } function extractRowRef(node) { if (!isOperation(node, "ROW")) { return null; } const id = asStringish(node.operands[0]); if (id == null) { return null; } const absolute = asBool(node.operands[1], false); return { id, absolute }; } function tryFoldRefToCell(node) { if (!isOperation(node, "REF")) { return null; } const ops = node.operands; if (ops.length !== 2 && ops.length !== 4) { return null; } const col1 = extractColumnRef(ops[0]); const row1 = extractRowRef(ops[1]); if (!col1 || !row1) { return null; } const cell = { column: col1, row: row1 }; if (ops.length === 4) { const col2 = extractColumnRef(ops[2]); const row2 = extractRowRef(ops[3]); if (!col2 || !row2) { return null; } cell.endColumn = col2; cell.endRow = row2; } return { type: "operand", value: cell }; } function normalizeRefCells(node) { if (node.type === "operation") { const normalizedOperands = node.operands.map(normalizeRefCells); const rebuilt = { type: "operation", operation: node.operation, operands: normalizedOperands }; const folded = tryFoldRefToCell(rebuilt); return folded ?? rebuilt; } return node; } // packages/ag-grid-enterprise/src/formula/ast/serializer.ts import { _getClientSideRowModel as _getClientSideRowModel3 } from "ag-grid-community"; var isOperationNode = (n) => n.type === "operation"; function colLabelFromId(beans, colId) { const col = beans.colModel.getColById(colId); if (col) { return beans.formula?.getColRef(col) ?? null; } return null; } function colIdFromLabel(beans, label) { return beans.formula?.getColByRef?.(label)?.colId ?? null; } function colIndexFromId(colModel, cols, colId) { const col = colModel.getColById(colId); if (!col) { return null; } const i = cols.indexOf(col); return i >= 0 ? i : null; } function colIdFromIndex(cols, idx) { const col = cols[idx]; return col ? col.getId() ?? null : null; } function rowIndexFromId(beans, rowId) { const row = beans.rowModel?.getRowNode?.(rowId); if (row?.formulaRowIndex != null) { return row.formulaRowIndex + 1; } return null; } function rowIdFromIndex(beans, idx) { return _getClientSideRowModel3(beans)?.getFormulaRow?.(idx - 1)?.id ?? null; } function quoteString(s2) { if (s2.includes('"')) { throw new FormulaError(18); } return `"${s2}"`; } function columnValueForREF(beans, ref) { const looksLetters = /^[A-Za-z]+$/.test(ref.id); if (ref.absolute) { if (looksLetters) { return ref.id.toUpperCase(); } const label = colLabelFromId(beans, ref.id); if (label) { return label.toUpperCase(); } throw new FormulaError(19, [ref.id]); } else { if (looksLetters) { const id = colIdFromLabel(beans, ref.id); if (id) { return id; } } return ref.id; } } function rowValueForREF(beans, ref) { const { id, absolute } = ref; if (absolute) { const rowId = rowIdFromIndex(beans, Number(id)); if (rowId == null) { throw new FormulaError(20, [id]); } } else { const idx = rowIndexFromId(beans, id); if (idx == null) { throw new FormulaError(21, [id]); } } return id; } function columnLabelForA1(beans, ref) { if (ref.absolute) { return ref.id; } const label = colLabelFromId(beans, ref.id); if (label) { return label.toUpperCase(); } throw new FormulaError(22, [ref.id]); } function rowIndexForA1(beans, ref) { if (ref.absolute) { const idx2 = Number(ref.id); if (Number.isFinite(idx2) && idx2 >= 1) { return idx2; } throw new FormulaError(23, [ref.id]); } const idx = rowIndexFromId(beans, ref.id); if (idx != null) { return idx; } throw new FormulaError(24, [ref.id]); } function serializeCellA1(beans, cell, unsafe) { const a = (abs, x) => (abs ? "$" : "") + String(x); const col1 = unsafe ? cell.column.id : columnLabelForA1(beans, cell.column); const row1 = unsafe ? cell.row.id : rowIndexForA1(beans, cell.row); const startRef = a(cell.column.absolute, col1) + a(cell.row.absolute, row1); if (cell.endColumn && cell.endRow) { const col2 = unsafe ? cell.endColumn.id : columnLabelForA1(beans, cell.endColumn); const row2 = unsafe ? cell.endRow.id : rowIndexForA1(beans, cell.endRow); return `${startRef}:${a(cell.endColumn.absolute, col2)}${a(cell.endRow.absolute, row2)}`; } return startRef; } function serializeCellREF(beans, cell) { const colPart = (r) => `COLUMN(${quoteString(columnValueForREF(beans, r))}${r.absolute ? ",true" : ""})`; const rowPart = (r) => `ROW(${quoteString(rowValueForREF(beans, r))}${r.absolute ? ",true" : ""})`; const start = `REF(${colPart(cell.column)},${rowPart(cell.row)}`; if (cell.endColumn && cell.endRow) { return `${start},${colPart(cell.endColumn)},${rowPart(cell.endRow)})`; } return `${start})`; } function isUnaryMinusNode(node) { if (!isOperationNode(node) || node.operation !== "-" || node.operands.length !== 2) { return null; } const [left, right] = node.operands; if (left.type === "operand" && left.value === 0) { return right; } return null; } function isInfixOpNode(node) { if (!isOperationNode(node)) { return false; } return !!getDefBySymbol(node.operation, "infix"); } function needsParensInBinary(parentDef, child, side) { if (!isOperationNode(child)) { return false; } if (isUnaryMinusNode(child)) { return false; } const childDef = getDefBySymbol(child.operation, "infix"); if (!childDef || childDef.fixity !== "infix") { return false; } const pParent = parentDef.precedence; const pChild = childDef.precedence; if (pChild < pParent) { return true; } if (pChild > pParent) { return false; } if (parentDef.associativity === "right") { const sameOp = childDef.symbol === parentDef.symbol; return side === "left" && sameOp; } const parentAssociative = parentDef.isAssociative === true; if (!parentAssociative) { return side === "right"; } return false; } function needsParensForUnaryMinus(rhs) { if (!isOperationNode(rhs)) { return false; } const innerInfix = getDefBySymbol(rhs.operation, "infix"); if (!innerInfix) { return false; } const isPow = innerInfix.symbol === "^"; return !isPow; } function serializeFormula(beans, root, useRefFormat, unsafe) { const emitCell = (cell) => useRefFormat ? serializeCellREF(beans, cell) : serializeCellA1(beans, cell, unsafe); function emit(node) { if (node.type === "operand") { const v = node.value; if (typeof v === "string") { return quoteString(v); } if (typeof v === "number") { return String(v); } if (typeof v === "boolean") { return v ? "TRUE" : "FALSE"; } return emitCell(v); } const unaryMinusInner = isUnaryMinusNode(node); if (unaryMinusInner) { const s2 = emit(unaryMinusInner); return needsParensForUnaryMinus(unaryMinusInner) ? `-(${s2})` : `-${s2}`; } const op = node.operation.toUpperCase(); if (node.operands.length === 1) { const rhs = node.operands[0]; const post = getDefBySymbol(op, "postfix"); if (post) { return `${emit(rhs)}${post.symbol}`; } const pre = getDefBySymbol(op, "prefix"); if (pre) { const inner = emit(rhs); const need = isInfixOpNode(rhs); return need ? `${pre.symbol}(${inner})` : `${pre.symbol}${inner}`; } return `${op}(${emit(rhs)})`; } if (node.operands.length === 2) { const def = getDefBySymbol(op, "infix"); if (def) { const [l, r] = node.operands; const Ls = needsParensInBinary(def, l, "left") ? `(${emit(l)})` : emit(l); const Rs = needsParensInBinary(def, r, "right") ? `(${emit(r)})` : emit(r); return `${Ls}${def.symbol}${Rs}`; } } return `${op}(${node.operands.map(emit).join(",")})`; } return "=" + emit(root); } // packages/ag-grid-enterprise/src/formula/functions/resolver.ts import { _getClientSideRowModel as _getClientSideRowModel4 } from "ag-grid-community"; function isRangeCell(cell) { return !!(cell.endColumn && cell.endRow); } function resolveRefToAddress(beans, cell) { const { row, column } = cell; const rowNode = row.absolute ? _getClientSideRowModel4(beans)?.getFormulaRow(Number(row.id) - 1) : beans.rowModel.getRowNode(row.id); const agCol = column.absolute ? beans.formula.getColByRef(column.id) : beans.colModel.getColById(column.id); if (!rowNode || !agCol) { return null; } return { row: rowNode, column: agCol }; } function evalAst(beans, node, getCellValue, caller) { if (node.type === "operand") { const v = node.value; if (typeof v !== "object") { return v; } if (isRangeCell(v)) { throw new FormulaError(25); } const addr = resolveRefToAddress(beans, v); if (!addr) { throw new FormulaError(26); } return getCellValue(addr); } const fn = beans.formula?.getFunction(node.operation); if (!fn) { throw new FormulaError(27, [node.operation]); } const { args, values } = makeArgIterables(beans, node.operands, getCellValue, caller); return fn({ row: caller.row, column: caller.column, args, values }); } function operandToArg(beans, node, getCellValue, caller) { if (node.type === "operand") { const v = node.value; if (typeof v !== "object") { return { kind: "value", value: v }; } if (isRangeCell(v)) { return buildRangeArgLazy(beans, v, getCellValue); } const addr = resolveRefToAddress(beans, v); if (!addr) { throw new FormulaError(26); } return { kind: "value", value: getCellValue(addr) }; } const val = evalAst(beans, node, getCellValue, caller); return { kind: "value", value: val }; } var ParamsIterator = class { constructor(beans, operandNodes, getCellValue, caller) { this.beans = beans; this.operandNodes = operandNodes; this.getCellValue = getCellValue; this.caller = caller; this.i = 0; this.res = { done: false, value: void 0 }; } next() { if (this.i >= this.operandNodes.length) { this.res.done = true; this.res.value = void 0; return this.res; } this.res.done = false; this.res.value = operandToArg(this.beans, this.operandNodes[this.i++], this.getCellValue, this.caller); return this.res; } [Symbol.iterator]() { return this; } }; var ValuesIterator = class { constructor(beans, operandNodes, getCellValue, caller) { this.beans = beans; this.operandNodes = operandNodes; this.getCellValue = getCellValue; this.caller = caller; this.i = 0; this.inner = null; this.res = { done: false, value: void 0 }; } next() { while (true) { if (this.inner) { const step = this.inner.next(); if (!step.done) { this.res.done = false; this.res.value = step.value; return this.res; } this.inner = null; continue; } if (this.i >= this.operandNodes.length) { this.res.done = true; this.res.value = void 0; return this.res; } const arg = operandToArg(this.beans, this.operandNodes[this.i++], this.getCellValue, this.caller); if (arg.kind === "value") { this.res.done = false; this.res.value = arg.value; return this.res; } this.inner = arg[Symbol.iterator](); } } [Symbol.iterator]() { return this; } }; function makeArgIterables(beans, operandNodes, getCellValue, caller) { const args = { [Symbol.iterator]() { return new ParamsIterator(beans, operandNodes, getCellValue, caller); } }; const values = { [Symbol.iterator]() { return new ValuesIterator(beans, operandNodes, getCellValue, caller); } }; return { args, values }; } function resolveRowIndex(beans, ref) { if (ref.absolute) { const n = Number(ref.id) - 1; if (!Number.isFinite(n) || n < 0) { throw new FormulaError(28); } return n; } const node = beans.rowModel?.getRowNode?.(ref.id); if (node?.formulaRowIndex == null) { throw new FormulaError(29); } return node.formulaRowIndex; } function resolveCol(beans, ref) { if (ref.absolute) { const col2 = beans.formula?.getColByRef(ref.id); if (!col2) { throw new FormulaError(30); } return col2; } const col = beans.colModel.getColById(ref.id); if (!col) { throw new FormulaError(31); } return col; } var RangeValuesIterator = class { constructor(beans, rowStartIndex, rowEndIndex, colStart, colEnd, getCellValue) { this.beans = beans; this.rowStartIndex = rowStartIndex; this.rowEndIndex = rowEndIndex; this.colStart = colStart; this.colEnd = colEnd; this.getCellValue = getCellValue; this.cols = null; this.currentRowIndex = this.rowStartIndex; this.currentColIdx = -1; this.colStartIdx = -1; this.colEndIdx = -1; this.res = { done: false, value: void 0 }; } initColsOnce() { if (this.cols) { return; } this.cols = this.beans.colModel.getCols() ?? []; const range = getColRangeIndices(this.beans, this.colStart, this.colEnd); if (!range) { this.colStartIdx = -1; this.colEndIdx = -1; return; } [this.colStartIdx, this.colEndIdx] = range; this.currentColIdx = this.colStartIdx; } next() { if (!this.cols) { this.initColsOnce(); if (this.colStartIdx < 0) { this.res.done = true; return this.res; } } if (this.currentRowIndex <= this.rowEndIndex) { const row = _getClientSideRowModel4(this.beans)?.getFormulaRow(this.currentRowIndex); if (!row) { throw new FormulaError(32); } const col = this.cols[this.currentColIdx]; if (this.currentColIdx < this.colEndIdx) { this.currentColIdx++; } else { this.currentColIdx = this.colStartIdx; this.currentRowIndex++; } this.res.value = this.getCellValue({ row, column: col }); return this.res; } this.res.done = true; this.res.value = void 0; return this.res; } }; function buildRangeArgLazy(beans, cell, getCellValue) { const r1 = resolveRowIndex(beans, cell.row); const r2 = cell.endRow ? resolveRowIndex(beans, cell.endRow) : r1; const rowStart = Math.min(r1, r2); const rowEnd = Math.max(r1, r2); const c1 = resolveCol(beans, cell.column); const c2 = cell.endColumn ? resolveCol(beans, cell.endColumn) : c1; return { kind: "range", rowStart, rowEnd, colStart: c1, colEnd: c2, [Symbol.iterator]() { return new RangeValuesIterator(beans, rowStart, rowEnd, c1, c2, getCellValue); } }; } function getColRangeIndices(beans, c1, c2) { const allColumns = beans.colModel.getCols() ?? []; let startColIndex = null; let endColIndex = null; for (let i = 0; i < allColumns.length && (startColIndex === null || endColIndex === null); i++) { const column = allColumns[i]; if (column === c2) { endColIndex = i; } if (column === c1) { startColIndex = i; } if (endColIndex !== null && startColIndex !== null) { break; } } if (startColIndex === null || endColIndex === null) { return null; } const colIndexMin = Math.min(startColIndex, endColIndex); const colIndexMax = Math.max(startColIndex, endColIndex); return [colIndexMin, colIndexMax]; } function* rangeAddrs(beans, rowStartIndex, rowEndIndex, startColumn, endColumn) { const allColumns = beans.colModel.getCols() ?? []; const colRange = getColRangeIndices(beans, startColumn, endColumn); if (colRange == null) { return; } const [colIndexMin, colIndexMax] = colRange; for (let rowIndex = rowStartIndex; rowIndex <= rowEndIndex; rowIndex++) { const rowNode = _getClientSideRowModel4(beans)?.getFormulaRow(rowIndex); if (!rowNode) { continue; } for (let colIndex = colIndexMin; colIndex <= colIndexMax; colIndex++) { yield { row: rowNode, column: allColumns[colIndex] }; } } } function* unresolvedDeps(beans, root, ensureFormulaCache) { const astStack = [root]; while (astStack.length) { const currentNode = astStack.pop(); if (currentNode.type === "operand") { const operandValue = currentNode.value; if (typeof operandValue !== "object" || operandValue == null) { continue; } if (!operandValue.endColumn && !operandValue.endRow) { const cellAddress = resolveRefToAddress(beans, operandValue); if (!cellAddress) { throw new FormulaError(33); } const cachedCellFormula = ensureFormulaCache(cellAddress.row, cellAddress.column); if (!cachedCellFormula || cachedCellFormula.isValueReady()) { continue; } yield cellAddress; continue; } if (!operandValue.endColumn || !operandValue.endRow) { throw new FormulaError(34); } const firstRowIndex = resolveRowIndex(beans, operandValue.row); const secondRowIndex = resolveRowIndex(beans, operandValue.endRow); const rowStartIndex = Math.min(firstRowIndex, secondRowIndex); const rowEndIndex = Math.max(firstRowIndex, secondRowIndex); const startCol = resolveCol(beans, operandValue.column); const endCol = resolveCol(beans, operandValue.endColumn); for (const cellAddress of rangeAddrs(beans, rowStartIndex, rowEndIndex, startCol, endCol)) { const cachedCellFormula = ensureFormulaCache(cellAddress.row, cellAddress.column); if (!cachedCellFormula || cachedCellFormula.isValueReady()) { continue; } yield cellAddress; } continue; } for (let i = 0; i < currentNode.operands.length; i++) { astStack.push(currentNode.operands[i]); } } } // packages/ag-grid-enterprise/src/formula/functions/utils.ts function take(values, name, n) { const it = values[Symbol.iterator](); const out = new Array(n); for (let i = 0; i < n; i++) { const step = it.next(); if (step.done) { throw new FormulaError(35, [name, n]); } out[i] = step.value; } if (!it.next().done) { throw new FormulaError(35, [name, n]); } return out; } function iterableWithoutBlanks(values) { return { *[Symbol.iterator]() { for (const v of values) { if (v != null && v !== "") { yield v; } } } }; } function takeBetween(values, name, min, max) { const out = []; for (const v of values) { out.push(v); if (out.length > max) { throw new FormulaError(36, [name, max]); } } if (out.length < min) { throw new FormulaError(37, [name, min]); } return out; } var isRangeParam = (p) => { return p.kind === "range"; }; var isValueParam = (p) => { return p.kind === "value"; }; var OPERATOR_TOKENS = ["<=", ">=", "<>", "<", ">", "="]; function findOperatorSymbol(s2) { for (const tok of OPERATOR_TOKENS) { if (s2.startsWith(tok)) { return tok; } } return null; } function toNumberLike(x) { if (typeof x === "number" && Number.isFinite(x)) { return x; } if (x instanceof Date) { return +x; } if (typeof x === "string") { const num = Number(x); if (!Number.isNaN(num)) { return num; } } return null; } function toText(x) { if (x == null) { return ""; } switch (typeof x) { case "string": return x; case "number": return String(x); case "boolean": return x ? "TRUE" : "FALSE"; } if (x instanceof Date) { return String(+x); } return String(x); } function wildcardToRegExp(pattern) { let out = "^"; for (let i = 0; i < pattern.length; i++) { const ch = pattern[i]; if (ch === "~" && i + 1 < pattern.length && (pattern[i + 1] === "*" || pattern[i + 1] === "?")) { out += "\\" + pattern[++i]; continue; } if (ch === "*") { out += ".*"; continue; } if (ch === "?") { out += "."; continue; } if (/[-/\\^$*+?.()|[\]{}]/.test(ch)) { out += "\\" + ch; } else { out += ch; } } out += "$"; return new RegExp(out, "i"); } var COMPARE_VALUES = (op, query, cell) => { let queryVal = toNumberLike(query); let cellVal = toNumberLike(cell); if (queryVal == null || cellVal == null) { queryVal = query; cellVal = toText(cell).toUpperCase(); } switch (op) { case "<": return cellVal < queryVal; case ">": return cellVal > queryVal; case "<=": return cellVal <= queryVal; case ">=": return cellVal >= queryVal; case "=": return cellVal === queryVal; case "<>": return cellVal !== queryVal; } return false; }; var REGEX_COMPARE_VALUES = (op, rx, cell) => { const text = toText(cell); const match = rx.test(text); return op === "=" ? match : !match; }; var EMPTY_PREDICATE = (cell) => cell == null || cell === ""; function criteriaToPredicate(criteria) { if (typeof criteria === "number") { return (cell) => toNumberLike(cell) === criteria; } if (typeof criteria !== "string") { return (cell) => criteria === cell; } const trimmed = criteria.trim(); if (trimmed === "") { return EMPTY_PREDICATE; } const symbol = findOperatorSymbol(trimmed); const query = symbol ? trimmed.substring(symbol.length) : trimmed; const wildcard = /[*?]/.test(query); if (!wildcard) { return COMPARE_VALUES.bind(null, symbol ?? "=", query.toUpperCase()); } if (symbol && symbol !== "=" && symbol !== "<>") { throw new FormulaError(38); } const regexp = wildcardToRegExp(query); return REGEX_COMPARE_VALUES.bind(null, symbol ?? "=", regexp); } var shiftColRef = (beans, delta, ref) => { if (!ref || delta === 0 || ref.absolute) { return; } const { visibleCols, colModel } = beans; const cols = visibleCols.allCols; const i0 = colIndexFromId(colModel, cols, ref.id); if (i0 == null) { return; } const j0 = i0 + delta; if (j0 < 0) { return; } const nextId = colIdFromIndex(cols, j0); if (nextId) { ref.id = nextId; } }; var shiftRowRef = (beans, rowDelta, ref, unsafe) => { if (!ref || rowDelta === 0 || ref.absolute) { return; } if (unsafe) { const numericId = Number(ref.id); if (!Number.isFinite(numericId)) { return; } ref.id = String(numericId + rowDelta); return; } const idx1 = rowIndexFromId(beans, ref.id); if (idx1 == null) { return; } const next1 = idx1 + rowDelta; if (next1 < 1) { return; } const nextId = rowIdFromIndex(beans, next1); if (nextId) { ref.id = nextId; } }; var isCellOperand = (value) => { return !!value && typeof value === "object" && value !== null && "row" in value && "column" in value; }; var shiftNode = (beans, node, rowDelta, columnDelta, unsafe) => { if (node.type === "operand") { const { value } = node; if (!isCellOperand(value)) { return; } const { row, column, endRow, endColumn } = value; shiftRowRef(beans, rowDelta, row, unsafe); shiftColRef(beans, columnDelta, column); shiftRowRef(beans, rowDelta, endRow, unsafe); shiftColRef(beans, columnDelta, endColumn); return; } if (node.type === "operation") { for (const child of node.operands) { shiftNode(beans, child, rowDelta, columnDelta, unsafe); } } }; // packages/ag-grid-enterprise/src/formula/functions/counting/functions.ts var COUNT = ({ values }) => { let count = 0; for (const v of values) { if (v != null && v !== "" && !isNaN(v)) { count++; } } return count; }; var COUNTA = ({ values }) => { let count = 0; for (const v of values) { if (v != null && v !== "") { count++; } } return count; }; var COUNTBLANK = ({ values }) => { let count = 0; for (const v of values) { if (v == null || v === "") { count++; } } return count; }; var COUNTIF = ({ args }) => { const [range, criteria] = take(args, "COUNTIF", 2); if (!isRangeParam(range)) { throw new FormulaError(65); } if (!isValueParam(criteria)) { throw new FormulaError(66); } const pred = criteriaToPredicate(criteria.value); let count = 0; for (const v of range) { if (pred(v)) { count++; } } return count; }; // packages/ag-grid-enterprise/src/formula/functions/dates/functions.ts var NOW = () => /* @__PURE__ */ new Date(); var TODAY = () => { const now = /* @__PURE__ */ new Date(); return new Date(now.getFullYear(), now.getMonth(), now.getDate()); }; // packages/ag-grid-enterprise/src/formula/functions/logic/functions.ts var EQUALS = ({ values }) => { const [a, b] = take(values, "EQUALS", 2); return a === b; }; var NOT_EQUALS = ({ values }) => { const [a, b] = take(values, "NOT_EQUALS", 2); return a !== b; }; var GT = ({ values }) => { const [a, b] = take(values, "GT", 2); return a > b; }; var GTE = ({ values }) => { const [a, b] = take(values, "GTE", 2); return a >= b; }; var LT = ({ values }) => { const [a, b] = take(values, "LT", 2); return a < b; }; var LTE = ({ values }) => { const [a, b] = take(values, "LTE", 2); return a <= b; }; var IF = ({ values }) => { const [cond, valTrue, valFalse] = take(values, "IF", 3); return cond ? valTrue : valFalse; }; var MIN = ({ values }) => { let best = null; for (const v of values) { if (v == null) { continue; } if (best === null || v < best) { best = v; } } if (best === null) { throw new FormulaError(68); } return best; }; var MAX = ({ values }) => { let best = null; for (const v of values) { if (v == null) { continue; } if (best === null || v > best) { best = v; } } if (best === null) { throw new FormulaError(69); } return best; }; // packages/ag-grid-enterprise/src/formula/functions/numbers/utils.ts var isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v); var MS_PER_DAY = 24 * 60 * 60 * 1e3; function daysFromDate(d) { return d.getTime() / MS_PER_DAY; } function dateFromDays(n) { return new Date(n * MS_PER_DAY); } function isDateValue(v) { return v instanceof Date; } function coerceFiniteNumber(fname, v) { if (typeof v === "bigint") { const asNumber = Number(v); if (Number.isFinite(asNumber)) { return asNumber; } throw new FormulaError(48, [fname]); } if (isFiniteNumber(v)) { return v; } if (isDateValue(v)) { return daysFromDate(v); } if (typeof v === "boolean") { return v ? 1 : 0; } if (typeof v === "string") { const n = Number(v.trim()); if (Number.isFinite(n)) { return n; } } throw new FormulaError(48, [fname]); } function coerceFiniteNumberOrBigInt(fname, v) { if (typeof v === "bigint") { return v; } return coerceFiniteNumber(fname, v); } function coerceBigInt(fname, v) { if (typeof v === "bigint") { return v; } if (!Number.isFinite(v) || !Number.isInteger(v)) { throw new FormulaError(49, [fname]); } return BigInt(v); } // packages/ag-grid-enterprise/src/formula/functions/numbers/functions.ts var PRODUCT = ({ values }) => { let acc = 1; let accBigInt = null; for (const v of iterableWithoutBlanks(values)) { const n = coerceFiniteNumberOrBigInt("PRODUCT", v); if (typeof n === "bigint") { accBigInt ?? (accBigInt = coerceBigInt("PRODUCT", acc)); if (n === 0n) { return 0n; } accBigInt *= n; continue; } if (accBigInt != null) { accBigInt *= coerceBigInt("PRODUCT", n); continue; } if (n === 0) { return 0; } acc *= n; } return accBigInt ?? acc; }; var DIVIDE = ({ values }) => { const [a, b] = take(iterableWithoutBlanks(values), "DIVIDE", 2); const na = coerceFiniteNumber("DIV", a); const nb = coerceFiniteNumber("DIV", b); if (na == null || nb == null) { throw new FormulaError(54); } if (nb === 0) { throw new FormulaError(55); } return na / nb; }; var SUM = ({ values }) => { let hasDates = false; let acc = 0; let accBigInt = null; let hasValue = false; for (const v of iterableWithoutBlanks(values)) { hasDates || (hasDates = isDateValue(v)); const n = coerceFiniteNumberOrBigInt("SUM", v); if (typeof n === "bigint") { if (hasDates) { throw new FormulaError(56); } accBigInt ?? (accBigInt = coerceBigInt("SUM", acc)); accBigInt += n; hasValue = true; continue; } if (typeof accBigInt === "bigint") { if (hasDates) { throw new FormulaError(56); } accBigInt += coerceBigInt("SUM", n); hasValue = true; continue; } acc += n; hasValue = true; } if (!hasValue) { throw new FormulaError(57); } if (typeof accBigInt === "bigint") { return accBigInt; } return hasDates ? dateFromDays(acc) : acc; }; var MINUS = ({ values }) => { const [a, b] = take(iterableWithoutBlanks(values), "MINUS", 2); const aDate = isDateValue(a); const bDate = isDateValue(b); if (aDate || bDate) { const na2 = coerceFiniteNumber("MINUS", a); const nb2 = coerceFiniteNumber("MINUS", b); if (aDate && !bDate) { return dateFromDays(na2 - nb2); } if (aDate && bDate) { return na2 - nb2; } return na2 - nb2; } const na = coerceFiniteNumberOrBigInt("MINUS", a); const nb = coerceFiniteNumberOrBigInt("MINUS", b); if (typeof na === "bigint" || typeof nb === "bigint") { return coerceBigInt("MINUS", na) - coerceBigInt("MINUS", nb); } return na - nb; }; var PERCENT = ({ values }) => { const [a] = take(values, "PERCENT", 1); const n = coerceFiniteNumber("PERCENT", a); if (n == null) { throw new FormulaError(70); } return n / 100; }; var POWER = ({ values }) => { const [a, b] = take(values, "POWER", 2); const na = coerceFiniteNumber("POWER", a); const nb = coerceFiniteNumber("POWER", b); if (na == null || nb == null) { throw new FormulaError(71); } return Math.pow(na, nb); }; var AVERAGE = ({ values }) => { let sum = 0; let count = 0; let allDate = true; for (const v of iterableWithoutBlanks(values)) { const n = coerceFiniteNumber("AVG", v); if (n == null) { continue; } sum += n; count++; allDate && (allDate = isDateValue(v)); } if (count === 0) { throw new FormulaError(58); } const avg = sum / count; return allDate ? dateFromDays(avg) : avg; }; var MEDIAN = ({ values }) => { let allDates = true; const arr = []; for (const v of iterableWithoutBlanks(values)) { const n = coerceFiniteNumber("MEDIAN", v); if (n == null) { throw new FormulaError(59); } arr.push(n); allDates && (allDates = isDateValue(v)); } if (arr.length === 0) { throw new FormulaError(60); } arr.sort((a, b) => a - b); const mid = Math.floor(arr.length / 2); const med = arr.length % 2 === 1 ? arr[mid] : (arr[mid - 1] + arr[mid]) / 2; return allDates ? dateFromDays(med) : med; }; var RAND = () => Math.random(); var SUMIF = ({ args }) => { const [critRange, criteria, sumRange] = takeBetween(args, "SUMIF", 2, 3); if (!isRangeParam(critRange)) { throw new FormulaError(61); } if (!isValueParam(criteria)) { throw new FormulaError(62); } if (sumRange && !isRangeParam(sumRange)) { throw new FormulaError(63); } const pred = criteriaToPredicate(criteria.value); if (!sumRange) { let acc = 0; let accBigInt = null; for (const v of critRange) { if (pred(v)) { const n = coerceFiniteNumberOrBigInt("SUMIF", v); if (typeof n === "bigint") { accBigInt ?? (accBigInt = coerceBigInt("SUMIF", acc)); accBigInt += n; } else if (accBigInt != null) { accBigInt += coerceBigInt("SUMIF", n); } else { acc += n; } } } return accBigInt ?? acc; } const critRangeHeight = critRange.rowEnd - critRange.rowStart; const sumRangeHeight = sumRange.rowEnd - sumRange.rowStart; if (critRangeHeight !== sumRangeHeight) { throw new FormulaError(64); } const critRangeIterator = critRange[Symbol.iterator](); const sumRangeIterator = sumRange[Symbol.iterator](); let total = 0; let totalBigInt = null; while (true) { const a = critRangeIterator.next(); const b = sumRangeIterator.next(); if (a.done || b.done) { if (a.done !== b.done) { throw new FormulaError(64); } break; } if (pred(a.value)) { const n = coerceFiniteNumberOrBigInt("SUMIF", b.value); if (typeof n === "bigint") { totalBigInt ?? (totalBigInt = coerceBigInt("SUMIF", total)); totalBigInt += n; } else if (totalBigInt != null) { totalBigInt += coerceBigInt("SUMIF", n); } else { total += n; } } } return totalBigInt ?? total; }; // packages/ag-grid-enterprise/src/formula/functions/strings/functions.ts var CONCAT = ({ values }) => { let out = ""; for (const v of values) { if (v == null) { continue; } switch (typeof v) { case "string": { out += v; break; } case "number": { out += String(v); break; } case "boolean": { out += v ? "TRUE" : "FALSE"; break; } case "object": { out += v.toString(); break; } default: { throw new FormulaError(67); } } } return out; }; // packages/ag-grid-enterprise/src/formula/functions/supportedFuncs.ts var supportedFuncs_default = { // logic/date IF, NOW, TODAY, // arithmetic PRODUCT, // DIVIDE, // DIV: DIVIDE, SUM, ADD: SUM, SUMIF, // MINUS, // PERCENT, POWER, MIN, MAX, AVERAGE, MEDIAN, // counting COUNT, COUNTA, COUNTBLANK, COUNTIF, // random RAND, // text CONCAT, CONCATENATE: CONCAT, // comparisons // EQ: EQUALS, // NE: NOT_EQUALS, // GT, // GTE, // LT, // LTE, // operator aliases "+": SUM, "-": MINUS, "*": PRODUCT, "/": DIVIDE, "^": POWER, "%": PERCENT, "=": EQUALS, "&": CONCAT, "<>": NOT_EQUALS, ">": GT, ">=": GTE, "<": LT, "<=": LTE }; // packages/ag-grid-enterprise/src/formula/formulaService.ts var CellFormula = class { constructor(rowNode, column, formulaString, beans) { this.rowNode = rowNode; this.column = column; this.formulaString = formulaString; this.beans = beans; this.error = null; this.ast = null; this.astStale = true; this._value = void 0; this._valueStale = true; } setFormulaString(next) { if (this.formulaString === next) { return; } this.formulaString = next; this.astStale = true; this._valueStale = true; } /** Cache write: store a fresh computed value (and clear previous error). */ setComputedValue(v) { this._value = v; this._valueStale = false; this.error = null; } /** Cache write: store an error (value considered stale). */ setError(e) { this.error = e; this._valueStale = false; } isValueReady() { return !this._valueStale; } /** * Return the error type or the value */ getValue() { return this.error?.type ?? this._value; } getError() { return this.error; } /** Returns the AST for the formula and recomputes if stale */ getAst() { if (!this.astStale) { return this.ast; } const ast = parseFormula(this.beans, this.formulaString); this.ast = ast ?? null; this.astStale = false; return this.ast; } }; var FormulaService = class extends BeanStub78 { constructor() { super(...arguments); this.beanName = "formula"; /** Cache: row -> (column -> CellFormula) */ this.cachedResult = /* @__PURE__ */ new WeakMap(); /** Map "A", "B", ..., "AA" -> actual AgColumn */ this.colRefMap = /* @__PURE__ */ new Map(); this.functionNames = null; this.active = false; } setFormulasActive(cols) { const formulaColumnsPresent = cols.list.some((col) => col.isAllowFormula()); const active = formulaColumnsPresent && this.checkForIncompatibleServices(cols); if (active !== this.active) { this.active = active; this.refreshFormulas(true); } } checkForIncompatibleServices(cols) { if (this.gos.get("masterDetail")) { _warn53(295, { blockedService: "Master Detail" }); return false; } if (this.gos.get("treeData")) { _warn53(295, { blockedService: "Tree Data" }); return false; } if (this.gos.get("enableCellExpressions")) { _warn53(295, { blockedService: "Cell Expressions" }); return false; } return cols.list.every((col) => { if (col.isAllowPivot() || col.isPivotActive()) { _warn53(295, { blockedService: "Column Pivoting" }); return false; } if (col.isAllowRowGroup() || col.isRowGroupActive()) { _warn53(295, { blockedService: "Row Groups" }); return false; } if (col.isAllowValue() || col.isValueActive() || col.getAggFunc()) { _warn53(295, { blockedService: "Value Aggregation" }); return false; } return true; }); } postConstruct() { this.setupFunctions(); const refreshFormulas = () => { if (this.active) { this.refreshFormulas(true); } }; const resetColMap = () => { if (this.active) { this.setupColRefMap(); } }; this.addManagedPropertyListeners(["masterDetail", "enableCellExpressions"], (e) => { const { colModel } = this.beans; const formulaColumnsPresent = colModel.cols?.list.some((col) => col.isAllowFormula()); if (formulaColumnsPresent) { colModel.refreshAll(_convertColumnEventSourceType3(e.source)); } }); this.addManagedListeners(this.beans.eventSvc, { modelUpdated: refreshFormulas, cellValueChanged: refreshFormulas, rowDataUpdated: refreshFormulas, newColumnsLoaded: resetColMap, columnMoved: resetColMap }); } updateFormulaByOffset(params) { const { value, rowDelta = 0, columnDelta = 0, useRefFormat = true } = params; const { beans } = this; try { const unsafe = !useRefFormat; const ast = parseFormula(beans, value, unsafe); shiftNode(beans, ast, rowDelta, columnDelta, unsafe); return serializeFormula( beans, ast, /*useRefFormat*/ useRefFormat, unsafe ); } catch { return value; } } setupFunctions() { this.supportedOperations = /* @__PURE__ */ new Map(); Object.keys(supportedFuncs_default).forEach((name) => { this.supportedOperations.set(name, supportedFuncs_default[name]); }); this.functionNames = null; const customFuncs = this.gos.get("formulaFuncs"); if (customFuncs) { Object.keys(customFuncs).forEach((name) => { this.supportedOperations.set(name.toUpperCase(), customFuncs[name].func); }); } } getFunctionNames() { if (this.functionNames) { return this.functionNames; } const names = []; for (const name of this.supportedOperations.keys()) { if (!isFormulaIdentStart(name[0])) { continue; } if (![...name].every((char) => isFormulaIdentChar(char))) { continue; } names.push(name); } names.sort((a, b) => a.localeCompare(b)); this.functionNames = names; return names; } setupColRefMap() { if (!this.active) { this.colRefMap = /* @__PURE__ */ new Map(); return; } const alphabet = "abcdefghijklmnopqrstuvwxyz"; const base = alphabet.length; const list = this.beans.colModel.getCols(); const map = /* @__PURE__ */ new Map(); let idx = 0; list?.forEach((col) => { if (!col.isPrimary()) { return; } let label = ""; let n = idx++; while (true) { label = alphabet[n % base] + label; if (n < base) { break; } n = Math.floor(n / base) - 1; } if (col.formulaRef !== label.toUpperCase()) { col.formulaRef = label.toUpperCase(); col.dispatchColEvent("formulaRefChanged", "api"); } map.set(label.toUpperCase(), col); }); this.colRefMap = map; this.refreshFormulas(true); } /** Lookup a column by A1-style reference label, e.g. "A", "AB". */ getColByRef(ref) { return this.colRefMap.get(ref.toUpperCase()) ?? null; } /** Find the A1-style label for a given column (reverse lookup). */ getColRef(col) { for (const [label, value] of this.colRefMap.entries()) { if (value === col) { return label; } } return null; } /** Clear all cached results and re-render cells. */ refreshFormulas(refreshCells) { this.cachedResult = /* @__PURE__ */ new WeakMap(); if (refreshCells) { this.beans.rowRenderer.refreshCells({ suppressFlash: true, force: true }); } } /** * Is a value a formula string (starts with '=') **/ isFormula(value) { return this.active && _isExpressionString4(value); } /** * Normalise a formula by parsing and serializing it (REF(COLUMN(), ROW()) format). * @returns null if the formula is invalid. */ normaliseFormula(value, shorthand = false) { const { beans } = this; try { const parsedAST = parseFormula(beans, value); const serialized = serializeFormula(beans, parsedAST, !shorthand, false); return serialized; } catch { return null; } } /** If the cell has been evaluated and errored, return its last error (else null). */ getFormulaError(column, node) { const rowMap = this.cachedResult.get(node); const cell = rowMap?.get(column); return cell?.error ?? null; } /** Get a registered function by name (used by the evaluator). */ getFunction(name) { return this.supportedOperations.get(name.toUpperCase()); } /** Ensure a CellFormula exists for (row,col) if it's a formula cell; returns null for non-formula. */ ensureCellFormula(row, col) { let rowMap = this.cachedResult.get(row); let cf = rowMap?.get(col); if (cf) { return cf; } const str = this.getFormulaFromDataSource(row, col) ?? this.fetchRawValue(col, row); if (typeof str !== "string" || str[0] !== "=") { return null; } cf = new CellFormula(row, col, str, this.beans); if (!rowMap) { rowMap = /* @__PURE__ */ new Map(); this.cachedResult.set(row, rowMap); } rowMap.set(col, cf); return cf; } getFormulaFromDataSource(row, col) { const dataSource = this.beans.formulaDataSvc; if (!dataSource?.hasDataSource()) { return void 0; } return dataSource.getFormula({ column: col, rowNode: row }); } coerceFormulaValue(column, value) { const baseDataType = this.beans.dataTypeSvc?.getBaseDataType(column); if (baseDataType === "bigint") { const bigintValue = this.toBigIntValue(value); return bigintValue ?? value; } if (baseDataType === "number" && typeof value === "bigint") { const asNumber = Number(value); return Number.isFinite(asNumber) ? asNumber : value; } return value; } toBigIntValue(value) { if (typeof value === "bigint") { return value; } if (typeof value === "number") { if (!Number.isFinite(value) || !Number.isInteger(value)) { return null; } return BigInt(value); } return null; } /** Fetch a non-formula value from the grid without triggering nested formula calc. */ fetchRawValue(col, row) { return this.beans.valueSvc.getValue(col, row, "data"); } getVisitorContext() { if (this.activeCtx) { return this.activeCtx; } const stateByCell = /* @__PURE__ */ new Map(); const setVisiting = (r, c) => { let colSet = stateByCell.get(r); const isVisiting = colSet?.has(c); if (isVisiting) { throw new FormulaError(51); } if (!colSet) { colSet = /* @__PURE__ */ new Set(); stateByCell.set(r, colSet); } colSet.add(c); }; const setVisited = (r, c) => { const colSet = stateByCell.get(r); if (colSet) { colSet.delete(c); if (colSet.size === 0) { stateByCell.delete(r); } } }; const errorAllVisitors = (error) => { for (const [row, cells] of stateByCell) { for (const col of cells) { const cache = this.ensureCellFormula(row, col); cache?.setError(error); } } }; return this.activeCtx = { setVisited, setVisiting, errorAllVisitors }; } makeFormulaFrame(address) { const cachedItem = this.ensureCellFormula(address.row, address.column); const ast = cachedItem.getAst(); if (!ast) { throw new FormulaError(52); } const unresolvedDepIterator = unresolvedDeps(this.beans, ast, this.ensureCellFormula.bind(this)); return { address, ast, unresolvedDepIterator }; } /** * Evaluate a single cell's formula **iteratively** (no recursion to avoid large stack traces), * caching dependency results into their own CellFormula entries. * * Returns the computed value, or a '#...' string on error. */ resolveValue(column, node) { const rootCachedCellFormula = this.ensureCellFormula(node, column); if (!rootCachedCellFormula) { return this.fetchRawValue(column, node); } if (rootCachedCellFormula.isValueReady()) { return rootCachedCellFormula.getValue(); } const hadCtx = !!this.activeCtx; const { setVisited, setVisiting, errorAllVisitors } = this.getVisitorContext(); const evalStack = []; try { setVisiting(node, column); evalStack.push(this.makeFormulaFrame({ row: node, column })); while (evalStack.length) { const { address, ast, unresolvedDepIterator } = evalStack[evalStack.length - 1]; const { row, column: col } = address; const cachedCellFormula = this.ensureCellFormula(row, col); if (cachedCellFormula.isValueReady()) { evalStack.pop(); setVisited(row, col); if (cachedCellFormula.error) { throw cachedCellFormula.error; } continue; } const depStep = unresolvedDepIterator.next(); if (!depStep.done) { const depAddr = depStep.value; const depCachedCellFormula = this.ensureCellFormula(depAddr.row, depAddr.column); if (!depCachedCellFormula || depCachedCellFormula.isValueReady()) { continue; } setVisiting(depAddr.row, depAddr.column); evalStack.push(this.makeFormulaFrame(depAddr)); continue; } const computed = evalAst( this.beans, ast, (addr) => { const cachedRefFormula = this.ensureCellFormula(addr.row, addr.column); if (cachedRefFormula) { if (!cachedRefFormula.isValueReady()) { throw new FormulaError(53); } const error = cachedRefFormula.getError(); if (error) { throw error; } return cachedRefFormula.getValue(); } return this.fetchRawValue(addr.column, addr.row); }, { row, column: col } ); const coerced = this.coerceFormulaValue(col, computed); const existing = cachedCellFormula.getError(); if (existing) { setVisited(row, col); throw existing; } cachedCellFormula.setComputedValue(coerced); setVisited(row, col); evalStack.pop(); } if (!rootCachedCellFormula.isValueReady()) { throw new FormulaError(53); } return rootCachedCellFormula.getValue(); } catch (e) { const normalized = e instanceof FormulaError ? e : new FormulaError(String(e?.message ?? e)); errorAllVisitors(normalized); return normalized.type; } finally { if (!hadCtx) { this.activeCtx = null; } } } }; // packages/ag-grid-enterprise/src/formula/formulaModule.ts var FormulaModule = { moduleName: "Formula", version: VERSION, userComponents: { agFormulaCellEditor: FormulaCellEditor }, beans: [FormulaService, FormulaDataService, FormulaInputManagerService], dependsOn: [RowNumbersModule], css: [formulaCSS] }; // packages/ag-grid-enterprise/src/sparkline/sparklinesModule.ts import { _preInitErrMsg } from "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 import { Component as Component55, RefPlaceholder as RefPlaceholder47, _batchCall } from "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 Component55 { constructor() { super({ tag: "div", cls: "ag-sparkline-wrapper", children: [{ tag: "span", ref: "eSparkline" }] }); this.eSparkline = RefPlaceholder47; 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) { _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) { 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: _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 import { Component as Component56, _clearElement as _clearElement19, _createElement as _createElement17, _toString as _toString2 } from "ag-grid-community"; var FindCellRendererElement = { tag: "span", cls: "ag-find-cell" }; var FindCellRenderer = class extends Component56 { 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, includeValueFormatted: true, from: "edit" }); const displayValue = valueFormatted ?? value ?? ""; const eGui = this.getGui(); _clearElement19(eGui); const parts = findSvc?.getParts({ value: displayValue, node, column: column ?? null }); if (!parts) { eGui.textContent = _toString2(displayValue) ?? ""; eGui.classList.remove("ag-find-cell-active-match"); } else { let hasActiveMatch = false; for (const { value: value2, match, activeMatch } of parts) { const content = _toString2(value2) ?? ""; if (match) { const element = _createElement17({ 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 import { BeanStub as BeanStub79, _addGridCommonParams as _addGridCommonParams27, _debounce as _debounce7, _isClientSideRowModel as _isClientSideRowModel10, _isFullWidthGroupRow, _jsonEquals as _jsonEquals4, _missing as _missing9, _toString as _toString3, isSpecialCol as isSpecialCol4 } from "ag-grid-community"; function defaultCaseFormat(value) { return value?.toLocaleLowerCase(); } function getMatchesForValue(findSearchValue, caseFormat, valueToFind) { const finalValue = caseFormat(_toString3(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 BeanStub79 { 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 (!_isClientSideRowModel10(this.gos)) { return; } const refreshAndWipeActive = this.refresh.bind(this, false); const refreshAndKeepActive = this.refresh.bind(this, true); const refreshAndKeepActiveDebounced = _debounce7( this, () => { if (this.isAlive()) { refreshAndKeepActive(); } }, 0 ); this.refreshDebounced = refreshAndKeepActiveDebounced; this.addManagedPropertyListener("findSearchValue", refreshAndWipeActive); this.addManagedPropertyListener("findOptions", ({ currentValue, previousValue }) => { if (!_jsonEquals4(currentValue, previousValue)) { refreshAndWipeActive(); } }); this.addManagedPropertyListeners(["groupSuppressBlankHeader", "showOpenedGroup"], refreshAndKeepActive); this.addManagedEventListeners({ modelUpdated: refreshAndKeepActive, displayedColumnsChanged: refreshAndKeepActive, pinnedRowDataChanged: refreshAndKeepActive, cellValueChanged: refreshAndKeepActiveDebounced, rowNodeDataChanged: refreshAndKeepActiveDebounced, cellEditingStopped: refreshAndKeepActiveDebounced, cellEditValuesChanged: refreshAndKeepActiveDebounced, batchEditingStopped: 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 = _toString3(value) ?? ""; if (_missing9(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 (!_isClientSideRowModel10(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 (_missing9(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 (!_missing9(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 (_isFullWidthGroupRow(gos, node, pivotMode)) { let valueToFind; const getFindText = groupRowRendererParams?.getFindText; if (getFindText) { const value = valueSvc.getValueForDisplay({ node, from: "batch" }).value; valueToFind = getFindText( _addGridCommonParams27(gos, { value, node, data, column: null, colDef: null, getValueFormatted: () => { const { valueFormatted } = valueSvc.getValueForDisplay({ node, includeValueFormatted: true, from: "batch" }); return valueFormatted; } }) ); } else { const { value, valueFormatted } = valueSvc.getValueForDisplay({ node, includeValueFormatted: true, from: "batch" }); 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 (isSpecialCol4(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, from: "batch" }).value; valueToFind = getFindText( _addGridCommonParams27(gos, { value, node, data, column, colDef, getValueFormatted: () => { const { valueFormatted } = valueSvc.getValueForDisplay({ column, node, includeValueFormatted: true, from: "batch" }); return valueFormatted; } }) ); } else { const { value, valueFormatted } = valueSvc.getValueForDisplay({ column, node, includeValueFormatted: true, from: "batch" }); 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: [EnterpriseCoreModule, FindCoreModule] }; // packages/ag-grid-enterprise/src/batch-edit/batchEditModule.ts import { _EditCoreModule as _EditCoreModule2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/batch-edit/batchEditApi.ts import { _isClientSideRowModel as _isClientSideRowModel11, _warn as _warn54 } from "ag-grid-community"; function startBatchEdit({ editSvc, gos, rowModel }) { if (!_isClientSideRowModel11(gos, rowModel)) { _warn54(289, { rowModelType: gos.get("rowModelType") }); return; } editSvc?.startBatchEditing(); } function cancelBatchEdit({ editSvc }) { editSvc?.stopBatchEditing({ cancel: true, source: "api", forceCancel: true }); } function commitBatchEdit({ editSvc }) { editSvc?.stopBatchEditing({ source: "api", forceStop: true, commit: true }); } 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: [_EditCoreModule2, EnterpriseCoreModule], css: [] }; // packages/ag-grid-enterprise/src/charts/integratedChartsModule.ts import { _PopupModule as _PopupModule5, _SharedDragAndDropModule as _SharedDragAndDropModule5, _preInitErrMsg as _preInitErrMsg2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/agChartsExports.ts import { BeanStub as BeanStub80 } from "ag-grid-community"; var AgChartsExports = class extends BeanStub80 { 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 import { BeanStub as BeanStub85 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/cartesian/cartesianChartProxy.ts import { _parseDateTimeFromString as _parseDateTimeFromString3 } from "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, isStatistical: true, isEnterprise: true, canSwitchDirection: true }, "range-area": { isCartesian: true, isStatistical: true, isEnterprise: true }, "box-plot": { isCartesian: true, isStatistical: 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 isStatistical(seriesType) { return doesSeriesHaveProperty(seriesType, "isStatistical"); } 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 import { _warn as _warn55 } from "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`]; for (const s2 of chart.series.filter((s3) => eligibleSeriesIds.includes(s3.id))) { s2.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: { $applyCycle: [ { $cacheMax: { $size: { $path: ["./data", { $path: "/data" }] } } }, { $palette: "fills" }, { $if: [ { $eq: [{ $value: "$parentIndex" }, 0] }, { $mix: [{ $value: "$1" }, { $ref: "backgroundColor" }, 0.7] }, { $value: "$1" } ] } ] }, strokes: { $applyCycle: [ { $cacheMax: { $size: { $path: ["./data", { $path: "/data" }] } } }, { $palette: "strokes" }, { $if: [ { $eq: [{ $value: "$parentIndex" }, 0] }, { $mix: [{ $value: "$1" }, { $ref: "backgroundColor" }, 0.7] }, { $value: "$1" } ] } ] } }, ...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?.[name]; if (!customChartTheme) { _warn55(140, { name }); } return customChartTheme; } function getSeriesHighlight(crossFiltering) { const highlight = { unhighlightedSeries: { opacity: 1 }, highlightedItem: { strokeWidth: 2 } }; if (!crossFiltering) { highlight.unhighlightedItem = { opacity: 1 }; } return highlight; } // 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?.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 } : {}, suppressFieldDotNotation: true, theme, container: this.chartProxyParams.parentElement }; return newOptions; } getChartThemeDefaults() { 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; const overrides = { common }; this.setSeriesChartThemeDefaults(overrides); return overrides; } setSeriesChartThemeDefaults(overrides) { const seriesOverrides = this.getSeriesChartThemeDefaults(); if (!seriesOverrides) { return; } overrides[this.standaloneChartType] = seriesOverrides; } 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.x.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, category.convertTime); 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, convertTime2) { 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]: convertTime2 ? convertTime2(value) : _parseDateTimeFromString3(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((s2) => { s2.yKey = getYKey(s2.yKey); s2.listeners = { seriesNodeClick: (e) => { const value = e.datum[s2.xKey]; const multiSelection = e.event.metaKey || e.event.ctrlKey; this.crossFilteringAddSelectedPoint(multiSelection, value); this.crossFilterCallback(e); } }; s2.marker = { itemStyler: (p) => { const value = p.datum[category.id]; const highlighted = p.highlightState === "highlighted-item"; return { fill: highlighted ? "yellow" : p.fill, size: highlighted ? 14 : this.crossFilteringPointSelected(value) ? 8 : 0 }; } }; if (this.standaloneChartType === "area") { s2.fillOpacity = this.crossFilteringDeselectedPoints() ? 0.3 : 1; } if (this.standaloneChartType === "line") { s2.strokeOpacity = this.crossFilteringDeselectedPoints() ? 0.3 : 1; } return s2; }); } 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) { if (multiSelection) { this.crossFilteringSelectedPoints.push(value); } else { 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); } getSeriesChartThemeDefaults() { return { series: { highlight: getSeriesHighlight(this.crossFiltering) } }; } }; // 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 { x: { type: "number", position: "bottom" }, y: { type: "number", position: "left" } }; } }; // packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/cartesian/waterfallChartProxy.ts var WaterfallChartProxy = class extends CartesianChartProxy { getAxes(params, commonChartOptions) { const isHorizontal = this.isHorizontal(commonChartOptions); const crossAxis = isHorizontal ? "y" : "x"; const valueAxis = isHorizontal ? "x" : "y"; return { [crossAxis]: { type: this.getXAxisType(params), position: isHorizontal ? "left" : "bottom" }, [valueAxis]: { type: "number", position: isHorizontal ? "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: () => String(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 import { GROUP_AUTO_COLUMN_ID as GROUP_AUTO_COLUMN_ID2 } from "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); return labels2 ? labels2[groupIndex] : labels2; } } 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() }; for (const item of data) { 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[GROUP_AUTO_COLUMN_ID2]?.value ?? 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 { angle: { type: radialBar ? "angle-number" : "angle-category" }, radius: { 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) => { return { 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.angle.type === "angle-category" || axes.radius.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 }; } getSeriesChartThemeDefaults() { return { series: { highlight: getSeriesHighlight(this.crossFiltering) } }; } }; // 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 import { BeanStub as BeanStub84, CellRangeType as CellRangeType3, _normalizeSortType as _normalizeSortType2, isColumnGroupAutoCol as isColumnGroupAutoCol2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/datasource/chartDatasource.ts import { BeanStub as BeanStub81, GROUP_AUTO_COLUMN_ID as GROUP_AUTO_COLUMN_ID3, _isClientSideRowModel as _isClientSideRowModel12, _isServerSideRowModel as _isServerSideRowModel9, _last as _last18, _warn as _warn56 } from "ag-grid-community"; var ChartDatasource = class extends BeanStub81 { 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) { _warn56(141); return { chartData: [], colNames: {} }; } if (!_isClientSideRowModel12(this.gos)) { _warn56(142); return { chartData: [], colNames: {} }; } } const isServerSide = _isServerSideRowModel9(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, crossFilteringSort, combineGroupValues } = params; let extractedRowData = []; const colNames = {}; const groupNodeIndexes = {}; const groupsToRemove = {}; let filteredNodes = {}; let allRowNodes = []; let numRows; if (crossFiltering) { filteredNodes = this.getFilteredRowNodes(); allRowNodes = this.getAllRowNodes(crossFilteringSort); 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) { for (const col of valueCols) { 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 }; for (const col of dimensionCols) { const colId = col.colId; const column = this.colModel.getCol(colId); if (column) { const valueObject = this.valueSvc.getValue(column, rowNode, "data"); if (grouping) { const valueString = valueObject?.toString ? String(valueObject.toString()) : " "; const labels2 = this.getGroupLabels(rowNode, valueString); const value = labels2.slice().reverse(); let groupingValue = { value, // this is needed so that standalone can handle animations properly when data updates id: id++, toString: () => value.filter(Boolean).join(" - ") }; if (combineGroupValues) { const groupingKey = groupingValue.toString(); const cachedGroupingValue = groupingCache[groupingKey]; if (cachedGroupingValue) { groupingValue = cachedGroupingValue; } else { groupingCache[groupingKey] = groupingValue; } } data[colId] = 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; } } for (const col of valueCols) { const colId = col.getColId(); if (crossFiltering) { const filteredOutColId = colId + "-filtered-out"; const value = this.valueSvc.getValue(col, rowNode, "data"); 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, "data"); 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 = _last18(dimensionCols); const lastColId = lastCol?.colId; const map = {}; const dataAggregated = []; for (const data of dataFromGrid) { let currentMap = map; for (const col of dimensionCols) { const colId = col.colId; const key = data[colId]; if (colId === lastColId) { let groupItem = currentMap[key]; if (!groupItem) { groupItem = { __children: [] }; for (const dimCol of dimensionCols) { 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)) { for (const groupItem of dataAggregated) { for (const col of params.valueCols) { const colId = col.getColId(); if (params.crossFiltering) { const dataToAgg = groupItem.__children.filter((child) => typeof child[colId] !== "undefined").map((child) => child[colId]); const aggResult = _aggregateValues({ beans: this.beans, values: dataToAgg, aggFuncOrString: params.aggFunc, column: col, rowNode: void 0, pivotResultColumn: void 0, aggregatedChildren: [] }); 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({ beans: this.beans, values: dataToAggFiltered, aggFuncOrString: params.aggFunc, column: col, rowNode: void 0, pivotResultColumn: void 0, aggregatedChildren: [] }); groupItem[filteredOutColId] = aggResultFiltered && typeof aggResultFiltered.value !== "undefined" ? aggResultFiltered.value : aggResultFiltered; } else { const dataToAgg = groupItem.__children.map((child) => child[colId]); const aggResult = _aggregateValues({ beans: this.beans, values: dataToAgg, aggFuncOrString: params.aggFunc, column: col, rowNode: void 0, pivotResultColumn: void 0, aggregatedChildren: [] }); 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); for (const col of secondaryColumns) { 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(GROUP_AUTO_COLUMN_ID3); if (groupColumn) { const valueObject = this.valueSvc.getValue(groupColumn, rowNode, "data"); const valueString = valueObject?.toString ? String(valueObject.toString()) : " "; labels2.push(valueString); } } else { labels2.push(rowNode.key); } } } return labels2; } /** cross filtering only */ getFilteredRowNodes() { const filteredNodes = {}; this.gridRowModel.forEachNodeAfterFilterAndSort((rowNode) => { filteredNodes[rowNode.id] = rowNode; }); return filteredNodes; } /** cross filtering only */ getAllRowNodes(sortModel) { const allRowNodes = []; this.gridRowModel.forEachNode((rowNode) => { allRowNodes.push(rowNode); }); const rowNodeSorter = this.rowNodeSorter; if (!rowNodeSorter) { return allRowNodes; } const sortOptions = sortModel === true ? this.sortSvc?.getSortOptions() : sortModel; if (!sortOptions || sortOptions.length == 0) { return allRowNodes; } return rowNodeSorter.doFullSortInPlace(allRowNodes, sortOptions); } }; // packages/ag-grid-enterprise/src/charts/chartComp/services/chartColumnService.ts import { BeanStub as BeanStub82, _getRowNode as _getRowNode8, _warn as _warn57 } from "ag-grid-community"; var ChartColumnService = class extends BeanStub82 { constructor() { super(...arguments); 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) { return this.colNames.getDisplayNameForColumn(col, "chart"); } getColGroupDisplayName(colGroup) { return this.colNames.getDisplayNameForColumnGroup(colGroup, "chart"); } getRowGroupColumns() { return this.beans.rowGroupColsSvc?.columns ?? []; } getGroupDisplayColumns() { return this.beans.showRowGroupCols?.columns ?? []; } 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(); for (const col of gridCols) { const colDef = col.getColDef(); const chartDataType = colDef.chartDataType; if (chartDataType) { switch (chartDataType) { case "category": case "time": dimensionCols.add(col); continue; case "series": valueCols.add(col); continue; case "excluded": continue; default: _warn57(153, { chartDataType }); break; } } if (colDef.colId === "ag-Grid-AutoColumn") { dimensionCols.add(col); continue; } if (!col.isPrimary()) { valueCols.add(col); continue; } (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 = _getRowNode8(this.beans, { rowIndex: 0, rowPinned: null }); if (!row) { return this.valueColsWithoutSeriesType.has(colId); } let cellValue = this.valueSvc.getValue(col, row, "data"); 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") { _warn57(265, { colId }); } return isNumber; } extractLeafData(row, col) { const value = row.data && this.valueSvc.getValue(col, row, "data"); if (value != null) { return value; } const childrenAfterGroup = row.childrenAfterGroup; if (childrenAfterGroup) { for (let i = 0, len = childrenAfterGroup.length; i < len; ++i) { const child = childrenAfterGroup[i]; const result = this.extractLeafData(child, col); if (result != null) { return result; } } } return null; } destroy() { this.valueColsWithoutSeriesType.clear(); super.destroy(); } }; // packages/ag-grid-enterprise/src/charts/chartComp/model/comboChartModel.ts import { BeanStub as BeanStub83, _warn as _warn58 } from "ag-grid-community"; var SUPPORTED_COMBO_CHART_TYPES = /* @__PURE__ */ new Set(["line", "groupedColumn", "stackedColumn", "area", "stackedArea"]); var ComboChartModel = class extends BeanStub83 { 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) { _warn58(150); } this.seriesChartTypes = this.seriesChartTypes.map((s2) => { if (!SUPPORTED_COMBO_CHART_TYPES.has(s2.chartType)) { _warn58(151, { chartType: s2.chartType }); s2.chartType = "line"; } return s2; }); const getSeriesChartType = (valueCol) => { if (!this.savedCustomSeriesChartTypes || this.savedCustomSeriesChartTypes.length === 0) { this.savedCustomSeriesChartTypes = this.seriesChartTypes; } const providedSeriesChartType = this.savedCustomSeriesChartTypes.find((s2) => s2.colId === valueCol.colId); if (!providedSeriesChartType) { if (valueCol.selected && !this.suppressComboChartWarnings) { _warn58(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 BeanStub84 { constructor(params) { super(); this.unlinked = false; this.chartData = []; this.valueColState = []; this.dimensionColState = []; this.colNames = {}; this.crossFiltering = false; this.crossFilteringSort = true; this.grouping = false; this.useGroupColumnAsCategory = 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, crossFilteringSort, seriesGroupType, useGroupColumnAsCategory } = 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.crossFilteringSort = crossFilteringSort ?? true; this.seriesGroupType = seriesGroupType; this.useGroupColumnAsCategory = !!useGroupColumnAsCategory; } 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, crossFilteringSort: this.getCrossFilteringSort(), valueCols: this.getSelectedValueCols(), startRow, endRow, isScatter: ["scatter", "bubble"].includes(this.chartType), combineGroupValues: isStatistical(getSeriesType(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); } getValueColState() { return this.valueColState.map(this.displayNameMapper.bind(this)); } displayNameMapper(col) { const { column } = col; if (column) { const columnDisplayName = this.getColDisplayName(column); col.displayName = this.isPivotMode() ? this.getPivotDisplayName(column, columnDisplayName) : columnDisplayName; } else { const colNames = this.colNames[col.colId]; col.displayName = colNames ? colNames.join(" - ") : this.getColDisplayName(column); } return col; } getPivotDisplayName(column, columnDisplayName) { let attemptFallbackToColNames = false; let displayNames = [columnDisplayName]; const getDisplayName2 = (colGroup) => { if (!colGroup) { return; } const colGroupName = this.chartColSvc.getColGroupDisplayName(colGroup); if (colGroupName?.length) { displayNames.unshift(colGroupName); getDisplayName2(colGroup.getParent()); } else { attemptFallbackToColNames = true; } }; getDisplayName2(column.getParent()); if (attemptFallbackToColNames) { const colNames = this.colNames[column.getColId()]; if (colNames) { displayNames = colNames; } } return displayNames.join(" - "); } getColDisplayName(col) { return this.chartColSvc.getColDisplayName(col); } isPivotMode() { return this.chartColSvc.isPivotMode(); } getChartDataType(colId) { const column = this.chartColSvc.getColumn(colId); return column ? column.getColDef().chartDataType : void 0; } getConvertTime(colId) { const column = this.chartColSvc.getColumn(colId); if (column?.colDef.cellDataType === "dateString") { return this.beans.dataTypeSvc?.getDateParserFunction(column); } return 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 === CellRangeType3.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]; const usingTreeData = this.gos.get("treeData"); const rowGroupCols = usingTreeData ? null : this.chartColSvc.getRowGroupColumns(); const groupingActive = usingTreeData || rowGroupCols && rowGroupCols.length > 0; dimensionCols.forEach((column) => { const autoGroup = isColumnGroupAutoCol2(column); const selected = this.crossFiltering && this.aggFunc ? aggFuncDimension.getColId() === column.getColId() : this.useGroupColumnAsCategory && groupingActive && autoGroup || (!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(CellRangeType3.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(CellRangeType3.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(CellRangeType3.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(CellRangeType3.DIMENSION, ...selectedCols); } } isComboChart(chartType) { return isComboChart(chartType ?? this.chartType); } getCrossFilteringSort() { const sort = this.crossFilteringSort; if (typeof sort === "boolean") { return sort; } const sortOptions = []; sort.forEach(({ sort: sort2, colId }) => { const column = this.chartColSvc.getColumn(colId); if (column) { sortOptions.push({ sort: sort2, column, type: _normalizeSortType2(column.getSortDef()?.type) }); } }); return sortOptions; } }; // packages/ag-grid-enterprise/src/charts/chartComp/chartProxies/statistical/statisticalChartProxy.ts var StatisticalChartProxy = class extends CartesianChartProxy { getAxes(params, commonChartOptions) { return { x: { type: this.getXAxisType(params), position: this.isHorizontal(commonChartOptions) ? "left" : "bottom" }, y: { 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 BeanStub85 { 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 import { BeanStub as BeanStub87, TabGuardComp as TabGuardComp4, _findFocusableElements as _findFocusableElements4, _findNextFocusableElement as _findNextFocusableElement8 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/advancedSettingsPanel.ts import { Component as Component61 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/chartPanelFeature.ts import { BeanStub as BeanStub86, _removeFromParent as _removeFromParent12 } from "ag-grid-community"; var ChartPanelFeature = class extends BeanStub86 { 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() { for (const panel of this.panels) { _removeFromParent12(panel.getGui()); this.destroyBean(panel); } this.panels = []; } destroy() { this.destroyPanels(); super.destroy(); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/animationPanel.ts import { AgInputNumberFieldSelector as AgInputNumberFieldSelector2, Component as Component57 } from "ag-grid-community"; var AnimationPanel = class extends Component57 { 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 */ `
`, [AgGroupComponentSelector, AgInputNumberFieldSelector2], { animationGroup: animationGroupParams, animationHeightInput: animationHeightInputParams } ); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/crosshairPanel.ts import { AgCheckboxSelector as AgCheckboxSelector6, Component as Component58 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/widgets/colorPicker.ts var ColorPicker = class extends AgColorPicker { constructor(config) { super({ ...config, dialogCallbacks: DIALOG_CALLBACKS }); } }; var ColorPickerSelector = { selector: "AG-COLOR-PICKER", component: ColorPicker }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/crosshairPanel.ts var CrosshairPanel = class extends Component58 { 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 */ `
`, [AgGroupComponentSelector, AgCheckboxSelector6, ColorPickerSelector], { crosshairGroup: crosshairGroupParams, crosshairLabelCheckbox: crosshairLabelCheckboxParams, crosshairSnapCheckbox: crosshairSnapCheckboxParams, crosshairStrokeColorPicker: crosshairStrokeColorPickerParams } ); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/navigatorPanel.ts import { AgCheckboxSelector as AgCheckboxSelector7, Component as Component59 } from "ag-grid-community"; var NavigatorPanel = class extends Component59 { 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 */ `
`, [AgGroupComponentSelector, AgSliderSelector, AgCheckboxSelector7], { navigatorGroup: navigatorGroupParams, navigatorHeightSlider: navigatorHeightSliderParams, navigatorMiniChartCheckbox: navigatorMiniChartCheckboxParams } ); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/advancedSettings/interactivity/zoomPanel.ts import { AgCheckboxSelector as AgCheckboxSelector8, Component as Component60, RefPlaceholder as RefPlaceholder48 } from "ag-grid-community"; var ZoomPanel = class extends Component60 { constructor(chartMenuParamsFactory) { super(); this.chartMenuParamsFactory = chartMenuParamsFactory; this.zoomScrollingStepInput = RefPlaceholder48; } 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 */ `
`, [AgGroupComponentSelector, AgCheckboxSelector8, 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 Component61 { constructor(chartMenuContext) { super( /* html */ `
` ); 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) { for (const group of INTERACTIVITY_GROUPS) { if (!this.isGroupPanelShownForSeries(group, seriesType)) { continue; } 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 BeanStub87 { constructor() { super(...arguments); this.beanName = "advSettingsMenuFactory"; } showMenu(chartMenuContext, eventSource) { this.hideMenu(); const menu = this.createBean(new AdvancedSettingsMenu(chartMenuContext)); this.activeDialog = this.createBean( new Dialog({ title: this.beans.chartTranslation.translate("advancedSettings"), component: menu, width: 300, height: 400, resizable: true, movable: true, centered: true, closable: true, afterGuiAttached: () => { _findFocusableElements4(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 TabGuardComp4 { constructor(chartMenuContext) { super( /* html */ `
` ); 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 = _findNextFocusableElement8(this.beans, panelGui, false, backwards); if (nextEl) { nextEl.focus(); } else { const focusableElements = _findFocusableElements4(panelGui); if (focusableElements.length) { focusableElements[backwards ? focusableElements.length - 1 : 0].focus(); } } } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/chartMenuList.ts import { BeanStub as BeanStub88, Component as Component62, RefPlaceholder as RefPlaceholder49, _addGridCommonParams as _addGridCommonParams28, _createIconNoSpan as _createIconNoSpan25, _focusInto as _focusInto10, _isNothingFocused as _isNothingFocused5 } from "ag-grid-community"; var ChartMenuListFactory = class extends BeanStub88 { 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 (_isNothingFocused5(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( _addGridCommonParams28(this.gos, { defaultItems, chartId: chartController.getChartId() }) ); } } mapWithStockItems(originalList, chartMenuContext, showMenu, eventSource, areChartToolPanelsEnabled) { if (!originalList) { return []; } const resultList = []; for (const menuItemOrString of originalList) { let result; if (typeof menuItemOrString === "string") { result = this.getStockMenuItem( menuItemOrString, chartMenuContext, showMenu, eventSource, areChartToolPanelsEnabled ); } else { result = { ...menuItemOrString }; } if (!result) { continue; } 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: _createIconNoSpan25(iconName, this.beans, null), action }; } destroy() { this.destroyBean(this.activeChartMenuList); super.destroy(); } }; var ChartMenuList = class extends Component62 { constructor(menuItems) { super( /* html */ ` ` ); this.menuItems = menuItems; this.eChartsMenu = RefPlaceholder49; } postConstruct() { this.mainMenuList = this.createManagedBean(new MenuList(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); } _focusInto10(this.mainMenuList.getGui()); } }; // packages/ag-grid-enterprise/src/charts/chartComp/services/chartCrossFilterService.ts import { BeanStub as BeanStub89, _warn as _warn59 } from "ag-grid-community"; var ChartCrossFilterService = class extends BeanStub89 { constructor() { super(...arguments); this.beanName = "chartCrossFilterSvc"; } filter(event, reset = false) { const filterManager = this.beans.filterManager; const filterModel = filterManager?.getFilterModel() ?? {}; if (reset) { if (Object.keys(filterModel).length > 0) { filterManager?.setFilterModel(null); } return; } let colId = extractFilterColId(event); if (colId.indexOf("-filtered-out")) { colId = colId.replace("-filtered-out", ""); } this.updateFilters(filterModel, event, colId); } updateFilters(filterModel, event, colId) { const dataKey = extractFilterColId(event); const rawValue = this.convertRawValue(colId, event.datum[dataKey]); if (rawValue === void 0) { return; } const filterManager = this.beans.filterManager; filterManager?.getColumnFilterInstance(colId).then((filter) => { const filterType = filter?.filterType; let setFilter; let processModel = (model) => model; if (filterType === "multi") { const result = extractFromMultiFilter(filter); setFilter = result.setFilter; processModel = result.processModel ?? processModel; } else if (filterType === "set") { setFilter = filter; } if (!setFilter) { _warn59(154, { colId }); return; } const update = event.event.metaKey || event.event.ctrlKey; const setFilterModel = setFilter.getFilterHandler().getCrossFilterModel( (createKey, availableKeys, existingValues) => getSetFilterModel(update, createKey(rawValue), availableKeys, existingValues) ); const colFilterModel = processModel(setFilterModel); const newFilterModel = update ? { ...filterModel } : {}; newFilterModel[colId] = colFilterModel; filterManager?.setFilterModel(newFilterModel); }); } convertRawValue(colId, rawValue) { const { colModel, dataTypeSvc } = this.beans; const column = colModel.getColById(colId); const colDef = column?.colDef; if (colDef && dataTypeSvc && colDef.chartDataType === "time" && colDef.cellDataType === "dateString") { return dataTypeSvc.getDateFormatterFunction(column)(rawValue); } return rawValue; } }; function processMultiFilterModel(setFilterModel, index, numFilters) { const filterModels = new Array(numFilters); for (let i = 0; i < numFilters; i++) { filterModels[i] = i === index ? setFilterModel : null; } return { filterType: "multi", filterModels }; } function extractFromMultiFilter(multiFilter) { const numFilters = multiFilter.getNumChildFilters(); for (let i = 0; i < numFilters; i++) { const childFilter = multiFilter.getChildFilterInstance(i); if (childFilter?.filterType === "set") { return { setFilter: childFilter, processModel: (model) => processMultiFilterModel(model, i, numFilters) }; } } return {}; } function extractFilterColId(event) { return event.xKey || event.calloutLabelKey; } function getSetFilterModel(update, key, availableKeySet, existingValues) { let values; if (update) { if (availableKeySet.has(key) && (existingValues == null || existingValues.includes(key))) { values = []; if (existingValues == null) { for (const availableKey of availableKeySet) { if (availableKey !== key) { values.push(availableKey); } } } else { for (const existingValue of existingValues) { if (existingValue !== key && availableKeySet.has(existingValue)) { values.push(existingValue); } } } } else { if (existingValues == null) { values = Array.from(availableKeySet); } else { values = []; for (const existingValue of existingValues) { if (availableKeySet.has(existingValue)) { values.push(existingValue); } } } values.push(key); } } else { values = [key]; } return { filterType: "set", values }; } // packages/ag-grid-enterprise/src/charts/chartComp/services/chartMenuService.ts import { BeanStub as BeanStub90, _warn as _warn60 } from "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 BeanStub90 { 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)) { _warn60(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) { _warn60(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 import { BeanStub as BeanStub91 } from "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", 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 BeanStub91 { 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 import { BeanStub as BeanStub96, _focusInto as _focusInto12, _warn as _warn67 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/gridChartComp.ts import { Component as Component97, RefPlaceholder as RefPlaceholder66, _addGridCommonParams as _addGridCommonParams29, _clearElement as _clearElement23, _errMsg as _errMsg2, _focusGridInnerElement, _focusInto as _focusInto11, _getAbsoluteHeight as _getAbsoluteHeight2, _getAbsoluteWidth as _getAbsoluteWidth3, _mergeDeep as _mergeDeep5, _removeFromParent as _removeFromParent19, _setDisplayed as _setDisplayed27, _warn as _warn66 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/chartController.ts import { BeanStub as BeanStub92, _warn as _warn61 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/utils/chartParamsValidator.ts import { _warnOnce } from "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); _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: _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") }, { property: "useGroupColumnAsCategory", validationFn: isBoolean, warnMessage: createWarnMessage("useGroupColumnAsCategory", "boolean") } ]; return validateProperties( params, validations, [ ...baseUpdateChartParams, "cellRange", "suppressChartRanges", "switchCategorySeries", "aggFunc", "seriesChartTypes", "seriesGroupType", "useGroupColumnAsCategory" ], "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) { _warnOnce(warnMessage(value)); return false; } validatedProperties = validatedProperties || { ...params }; validatedProperties[property] = validationResult; if (warnIfFixed) { _warnOnce(warnMessage(value)); } } } if (validPropertyNames) { for (const property of Object.keys(params)) { if (!validPropertyNames.includes(property)) { _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 BeanStub92 { 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; chartModelParams.useGroupColumnAsCategory = params.useGroupColumnAsCategory ?? this.model.useGroupColumnAsCategory; 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.crossFilteringSort = this.model.crossFilteringSort; chartModelParams.suppressChartRanges = params.suppressChartRanges ?? this.model.suppressChartRanges; break; case "pivotChartUpdate": chartModelParams.switchCategorySeries = false; break; } this.model.updateModel(chartModelParams); const removeChartCellRanges = chartModelParams.unlinkChart || chartModelParams.suppressChartRanges; if (removeChartCellRanges) { this.rangeSvc?.setCellRanges([]); } else { 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 model = this.model; const params = { data, groupData: model.groupChartData, grouping: this.isGrouping(), categories: selectedDimensions.map(({ colId, displayName }) => { const chartDataType = model.categoryAxisType ?? model.getChartDataType(colId); return { id: colId, name: displayName, chartDataType, convertTime: chartDataType === "time" ? model.getConvertTime(colId) : void 0 }; }), fields, chartId: this.getChartId(), getCrossFilteringContext: () => ({ lastSelectedChartId: "xxx" }), //this.params.crossFilteringContext, //TODO seriesChartTypes: this.getSeriesChartTypes(), updatedOverrides, seriesGroupType: 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, useGroupColumnAsCategory: this.model.useGroupColumnAsCategory }; } 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; }); } getSelectedValueColState() { return this.model.getValueColState().filter((cs) => cs.selected); } getSelectedDimensions() { return this.model.getSelectedDimensions(); } getColStateForMenu() { return { dimensionCols: this.model.dimensionColState, valueCols: this.model.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((s2) => s2.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((s2) => selectedColIds.includes(s2.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) { _warn61(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) { _warn61(137, { currentChartType, type: params.type }); } return valid; } getCellRangeParams() { const cellRanges = this.getCellRanges(); const firstCellRange = cellRanges[0]; const startRow = firstCellRange?.startRow || null; const endRow = firstCellRange?.endRow || null; return { rowStartIndex: startRow?.rowIndex ?? null, rowStartPinned: startRow?.rowPinned, rowEndIndex: endRow?.rowIndex ?? null, rowEndPinned: 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 = { x: { type: this.getXAxisType(params), position: "bottom" }, y: { type: "number", position: "left" } }; if (this.isNormalised()) { axes.y.label = { ...axes.y.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 = { x: { type: this.getXAxisType(params), position: this.isHorizontal() ? "left" : "bottom" }, y: { type: "number", position: this.isHorizontal() ? "bottom" : "left" } }; if (this.isNormalised()) { axes.y.label = { ...axes.y.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 = { x: { type: this.getXAxisType(params), position: "bottom" }, y: { type: "number", position: "left" } }; if (this.isNormalised()) { axes.y.label = { ...axes.y.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 { x: { type: "number", position: "bottom" }, y: { 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?.yField && x.sizeField); } return fields.map( (currentXField, i) => i % 2 === 0 ? { xField: currentXField, yField: fields[i + 1] } : null ).filter((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?.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 = { x: { type: this.getXAxisType(params), position: "bottom" } }; if (primaryYKeys.length > 0) { axes.y = { type: "number", 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", position: "right" }; axes[`y_${secondaryYKey}`] = secondaryAxisOptions; }); } return axes; } getSeries(params) { const { fields, seriesChartTypes } = params; const [category] = params.categories; return fields.map((field) => { const seriesChartType = seriesChartTypes.find((s2) => s2.colId === field.colId); if (seriesChartType) { const chartType = seriesChartType.chartType; const grouped = ["groupedColumn", "groupedBar"].includes(chartType); const groupedOpts = grouped ? { grouped: true } : {}; const yKeyAxis = seriesChartType.secondaryAxis ? `y_${field.colId}` : "y"; return { type: getSeriesType(chartType), xKey: category.id, yKey: field.colId, yName: field.displayName, yKeyAxis, stacked: ["stackedArea", "stackedColumn"].includes(chartType), ...groupedOpts }; } }); } getYKeys(fields, seriesChartTypes) { const primaryYKeys = []; const secondaryYKeys = []; for (const field of fields) { const colId = field.colId; const seriesChartType = seriesChartTypes.find((s2) => s2.colId === colId); if (seriesChartType) { if (seriesChartType.secondaryAxis) { secondaryYKeys.push(colId); } else { primaryYKeys.push(colId); } } } return { primaryYKeys, secondaryYKeys }; } setSeriesChartThemeDefaults(overrides) { const seriesOverrides = this.getSeriesChartThemeDefaults(); if (!seriesOverrides) { return; } const chartTypes = /* @__PURE__ */ new Set(); for (const seriesChartType of this.chartProxyParams.seriesChartTypes) { chartTypes.add(seriesChartType.chartType); } for (const chartType of chartTypes) { overrides[getSeriesType(chartType)] = seriesOverrides; } } }; // 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; } getSeriesChartThemeDefaults() { return { series: { highlight: getSeriesHighlight(this.crossFiltering) } }; } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/chartMenu.ts import { AgPromise as AgPromise14, Component as Component96, _warn as _warn65 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/chartToolbar.ts import { Component as Component63, RefPlaceholder as RefPlaceholder50, _clearElement as _clearElement20, _createElement as _createElement18, _createIconNoSpan as _createIconNoSpan26 } from "ag-grid-community"; var ChartToolbar = class extends Component63 { constructor() { super( /* html */ `
` ); this.eMenu = RefPlaceholder50; this.buttonListenersDestroyFuncs = []; } wireBeans(beans) { this.chartTranslation = beans.chartTranslation; } updateParams(params) { const { buttons } = params; this.createButtons(buttons); } createButtons(buttons) { for (const func of this.buttonListenersDestroyFuncs) { func?.(); } this.buttonListenersDestroyFuncs = []; const menuEl = this.eMenu; _clearElement20(menuEl); for (const buttonConfig of buttons) { 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 = _createIconNoSpan26(iconName, this.beans); buttonEl.classList.add("ag-chart-menu-icon"); const wrapperEl = _createElement18({ 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 import { AgPromise as AgPromise13, Component as Component95, _createElement as _createElement19 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/data/chartDataPanel.ts import { AgToggleButton as AgToggleButton5, Component as Component68, _getDocument as _getDocument7, _setDisplayed as _setDisplayed24, _warn as _warn62 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/data/categoriesDataPanel.ts import { AgSelect as AgSelect4, AgToggleButton as AgToggleButton2 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/data/dragDataPanel.ts import { AgSelect as AgSelect3, Component as Component65 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/widgets/agPillSelect.ts import { AgSelect as AgSelect2, Component as Component64, DragSourceType as DragSourceType8, _escapeString as _escapeString8, _getActiveDomElement as _getActiveDomElement15, _removeFromParent as _removeFromParent13 } from "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}.ag-pill-select .ag-column-drop-list{padding:0}:where(.ag-pill-select){.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 Component64 { constructor(config) { super( /* html */ `` ); this.config = config ?? {}; const { selectedValueList, valueFormatter, valueList } = this.config; this.selectedValues = selectedValueList ?? []; this.valueList = valueList ?? []; this.valueFormatter = valueFormatter ?? ((value) => _escapeString8(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 AgSelect2({ 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; } for (const value of this.valueList) { 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 = _getActiveDomElement15(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) { _removeFromParent13(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 DragSourceType8.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 === DragSourceType8.ChartPanel; } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/data/dragDataPanel.ts var DragDataPanel = class extends Component65 { 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) => { for (const col of columns) { 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 AgSelect3(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 */ `
` ); 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 AgToggleButton2({ 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 AgSelect4({ 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 import { AgSelect as AgSelect5, AgToggleButton as AgToggleButton3, Component as Component66, RefPlaceholder as RefPlaceholder51 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/chartMenuParamsFactory.ts import { BeanStub as BeanStub93 } from "ag-grid-community"; var ChartMenuParamsFactory = class extends BeanStub93 { 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 Component66 { constructor(chartMenuContext, isOpen) { super(); this.chartMenuContext = chartMenuContext; this.isOpen = isOpen; this.chartSpecificGroup = RefPlaceholder51; 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 */ `
`, [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 AgSelect5(params)); this.updateDirectionSelect(); return [this.directionSelect]; } createReverseSelect() { const { chartMenuParamsFactory } = this.chartMenuContext; const params = chartMenuParamsFactory.getDefaultToggleParams("series.reverse", "reverse"); this.reverseToggle = this.createManagedBean(new AgToggleButton3(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 AgSelect5( 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 import { AgCheckbox, AgSelect as AgSelect6, Component as Component67, _areEqual as _areEqual5, _clearElement as _clearElement21 } from "ag-grid-community"; var SeriesChartTypePanel = class extends Component67 { constructor(chartController, columns, isOpen) { super( /* html */ `
` ); 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 (!_areEqual5(this.getValidColIds(columns), this.selectedColIds)) { this.recreate(columns); } else { this.refreshComps(); } } recreate(columns) { this.isOpen = this.seriesChartTypeGroupComp.isExpanded(); _clearElement21(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((s2) => s2.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(); for (const col of columns) { if (!col.selected) { continue; } const seriesChartType = seriesChartTypes.filter((s2) => s2.colId === col.colId)[0]; if (!seriesChartType) { continue; } 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 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 AgSelect6({ 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(); for (const colId of this.selectedColIds) { const seriesChartType = seriesChartTypes.find((chartType) => chartType.colId === colId); if (!seriesChartType) { continue; } 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 import { AgToggleButton as AgToggleButton4 } from "ag-grid-community"; var SeriesDataPanel = class extends DragDataPanel { constructor(chartController, chartOptionsService, title, allowMultipleSelect, maxSelection, valueCols, isOpen) { super( chartController, allowMultipleSelect, maxSelection, /* html */ `
` ); 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 AgToggleButton4({ 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 Component68 { constructor(chartMenuContext) { super( /* html */ `
` ); 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(); _setDisplayed24(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 { _warn62(144, { type }); } }); (isCategorySeriesSwitched ? this.categoriesDataPanel : this.seriesDataPanel)?.addItem( this.switchCategorySeriesToggle.getGui() ); this.addPanelComponents(); } addPanelComponents() { if (!this.panels.length) { return; } const eDocument = _getDocument7(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() { for (const panel of this.panels) { panel.getGui().remove(); 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 AgToggleButton5({ 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 import { Component as Component91, _warn as _warn63 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/axis/cartesianAxisPanel.ts import { AgCheckbox as AgCheckbox2, AgSelectSelector as AgSelectSelector3, Component as Component72, RefPlaceholder as RefPlaceholder55, _removeFromParent as _removeFromParent15, _setDisplayed as _setDisplayed25 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/widgets/agAngleSelect.ts import { AgAbstractLabel as AgAbstractLabel2, AgInputNumberFieldSelector as AgInputNumberFieldSelector3, RefPlaceholder as RefPlaceholder52, _exists as _exists28, _getActiveDomElement as _getActiveDomElement16, _setFixedWidth } from "ag-grid-community"; var AgAngleSelect = class extends AgAbstractLabel2 { constructor(config) { super( config, /* html */ `
`, [AgInputNumberFieldSelector3] ); this.eLabel = RefPlaceholder52; this.eParentCircle = RefPlaceholder52; this.eChildCircle = RefPlaceholder52; this.eAngleValue = RefPlaceholder52; 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 (_exists28(this.getValue())) { this.eAngleValue.setValue(this.normalizeNegativeValue(this.getValue()).toString()); } this.addManagedListeners(this, { fieldValueChanged: () => { if (this.eAngleValue.getInputElement().contains(_getActiveDomElement16(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) { _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 import { AgSelectSelector as AgSelectSelector2, Component as Component69, RefPlaceholder as RefPlaceholder53, _removeFromParent as _removeFromParent14 } from "ag-grid-community"; function _capitalise(str) { return str[0].toUpperCase() + str.substring(1).toLowerCase(); } var FontPanel = class extends Component69 { constructor(params) { super(); this.params = params; this.fontGroup = RefPlaceholder53; 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 */ `
`, [AgGroupComponentSelector, AgSelectSelector2, ColorPickerSelector], { 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() { for (const comp of this.activeComps) { _removeFromParent14(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 import { Component as Component70, RefPlaceholder as RefPlaceholder54 } from "ag-grid-community"; var AxisTicksPanel = class extends Component70 { constructor(chartMenuUtils) { super(); this.chartMenuUtils = chartMenuUtils; this.axisTicksSizeSlider = RefPlaceholder54; } 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 */ `
`, [AgGroupComponentSelector, ColorPickerSelector, 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 import { Component as Component71 } from "ag-grid-community"; var GridLinePanel = class extends Component71 { 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 */ `
`, [AgGroupComponentSelector, ColorPickerSelector, 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 Component72 { constructor(axisType, options) { super(); this.axisType = axisType; this.options = options; this.axisGroup = RefPlaceholder55; this.axisTypeSelect = RefPlaceholder55; this.axisPositionSelect = RefPlaceholder55; this.axisTimeFormatSelect = RefPlaceholder55; 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 */ `
`, [AgGroupComponentSelector, AgSelectSelector3, ColorPickerSelector, 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"; _setDisplayed25(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 = () => { for (const func of this.updateFuncs) { 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; if (updatedLabelFormat === void 0) { chartOptions.clearValue?.("label", "format"); } this.chartOptionsService.setCartesianCategoryAxisType(this.axisType, value); if (updatedLabelFormat != null) { chartOptions.setValue("label.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) => { if (chartType === "heatmap") { return null; } if (axisType === "xAxis") { return [ { value: "top", text: this.translate("top") }, { value: "bottom", text: this.translate("bottom") } ]; } if (axisType === "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 AgCheckbox2({ 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) { _removeFromParent15(component.getGui()); this.destroyBean(component); } destroyActivePanels() { for (const panel of this.activePanels) { _removeFromParent15(panel.getGui()); this.destroyBean(panel); } } destroy() { this.destroyActivePanels(); super.destroy(); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/axis/polarAxisPanel.ts import { AgSelect as AgSelect7, Component as Component73, RefPlaceholder as RefPlaceholder56 } from "ag-grid-community"; var PolarAxisPanel = class extends Component73 { constructor(options) { super(); this.options = options; this.axisGroup = RefPlaceholder56; } 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 */ `
`, [AgGroupComponentSelector, ColorPickerSelector, 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 AgSelect7(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 import { Component as Component76, RefPlaceholder as RefPlaceholder58 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/chart/backgroundPanel.ts import { Component as Component74 } from "ag-grid-community"; var BackgroundPanel = class extends Component74 { 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 */ `
`, [AgGroupComponentSelector, ColorPickerSelector], { chartBackgroundGroup: chartBackgroundGroupParams, colorPicker: colorPickerParams } ); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/chart/paddingPanel.ts import { Component as Component75, RefPlaceholder as RefPlaceholder57 } from "ag-grid-community"; var PaddingPanel = class extends Component75 { constructor(chartMenuUtils, chartController) { super(); this.chartMenuUtils = chartMenuUtils; this.chartController = chartController; this.paddingTopSlider = RefPlaceholder57; } 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 */ `
`, [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 Component76 { constructor(options) { super(); this.options = options; this.chartGroup = RefPlaceholder58; } 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 */ `
`, [AgGroupComponentSelector], { chartGroup: chartGroupParams } ); registerGroupComponent(this.chartGroup); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/groupExpansionFeature.ts import { BeanStub as BeanStub94 } from "ag-grid-community"; var GroupExpansionFeature = class extends BeanStub94 { 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 import { AgCheckbox as AgCheckbox3, AgSelect as AgSelect8, Component as Component77, RefPlaceholder as RefPlaceholder59 } from "ag-grid-community"; var LegendPanel = class extends Component77 { constructor(options, chartMenuContext) { super(); this.options = options; this.legendGroup = RefPlaceholder59; this.enabledGroup = RefPlaceholder59; 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 AgSelect8( 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 */ `
`, [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 AgCheckbox3( 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 import { AgSelect as AgSelect9, Component as Component88, RefPlaceholder as RefPlaceholder63, _error as _error9, _removeFromParent as _removeFromParent18 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/toggleablePanel.ts import { Component as Component78, RefPlaceholder as RefPlaceholder60, _removeFromParent as _removeFromParent16 } from "ag-grid-community"; var ToggleablePanel = class extends Component78 { constructor(params) { super(); this.params = params; this.toggleableGroup = RefPlaceholder60; 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 */ `
`, [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() { for (const comp of this.activeComps) { _removeFromParent16(comp.getGui()); this.destroyBean(comp); } } destroy() { this.destroyActiveComps(); super.destroy(); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/calloutPanel.ts import { Component as Component79 } from "ag-grid-community"; var CalloutPanel = class extends Component79 { 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 */ `
`, [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 import { Component as Component80 } from "ag-grid-community"; var CapsPanel = class extends Component80 { 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 */ `
`, [AgGroupComponentSelector, AgSliderSelector], { capsGroup: capsGroupParams, capLengthRatioSlider: capLengthRatioSliderParams } ); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/connectorLinePanel.ts import { Component as Component81 } from "ag-grid-community"; var ConnectorLinePanel = class extends Component81 { 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 */ `
`, [AgGroupComponentSelector, ColorPickerSelector, 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 import { AgSelectSelector as AgSelectSelector4, Component as Component82 } from "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 Component82 { 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 */ `
`, [AgGroupComponentSelector, AgSelectSelector4, 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 import { AgSelectSelector as AgSelectSelector5, Component as Component83, RefPlaceholder as RefPlaceholder61, _removeFromParent as _removeFromParent17 } from "ag-grid-community"; var SeriesItemsPanel = class extends Component83 { constructor(chartMenuUtils) { super(); this.chartMenuUtils = chartMenuUtils; this.seriesItemsGroup = RefPlaceholder61; 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 */ `
`, [AgGroupComponentSelector, AgSelectSelector5], { 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() { for (const panel of this.activePanels) { _removeFromParent17(panel.getGui()); this.destroyBean(panel); } } destroy() { this.destroyActivePanels(); super.destroy(); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/series/shadowPanel.ts import { Component as Component84 } from "ag-grid-community"; var ShadowPanel = class extends Component84 { 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 */ `
`, [AgGroupComponentSelector, ColorPickerSelector, 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 import { Component as Component85 } from "ag-grid-community"; var TileSpacingPanel = class extends Component85 { 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 */ `
`, [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 import { AgSelectSelector as AgSelectSelector6, Component as Component86, RefPlaceholder as RefPlaceholder62 } from "ag-grid-community"; function _capitalise2(str) { return str[0].toUpperCase() + str.substring(1); } var TooltipPanel = class extends Component86 { constructor(chartMenuUtils) { super(); this.chartMenuUtils = chartMenuUtils; this.tooltipMode = RefPlaceholder62; } 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 */ `
`, [AgGroupComponentSelector, AgSelectSelector6], { 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 import { Component as Component87 } from "ag-grid-community"; var WhiskersPanel = class extends Component87 { 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 */ `
`, [AgGroupComponentSelector, ColorPickerSelector, 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 Component88 { constructor(options) { super(); this.options = options; this.seriesGroup = RefPlaceholder63; 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 */ `
`, [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(); } for (const w of this.seriesWidgetMappings[this.seriesType] ?? []) { 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) => _error9(105, { e })); } initSeriesSelect() { const seriesSelect = this.createBean( new AgSelect9( 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 ColorPicker(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) => { for (const comp of [ this.initStrokeWidth("strokeWidth", "dropOff"), this.initLineDash("dropOff"), this.initOpacity("strokeOpacity", "dropOff"), this.initOpacity("fillOpacity", "dropOff") ]) { 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 AgSelect9( 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 AgSelect9( 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((s2) => getSeriesType(s2.chartType)); } translate(key) { return this.chartTranslation.translate(key); } destroyActivePanels() { for (const panel of this.activePanels) { _removeFromParent18(panel.getGui()); this.destroyBean(panel); } } destroy() { this.destroyActivePanels(); super.destroy(); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/titles/titlesPanel.ts import { Component as Component90, RefPlaceholder as RefPlaceholder64 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/format/titles/titlePanel.ts import { AgInputTextField as AgInputTextField4, Component as Component89 } from "ag-grid-community"; var TitlePanel = class extends Component89 { constructor(chartMenuUtils, name, key) { super( /* html */ `
` ); 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?.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 AgInputTextField4(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 Component90 { constructor(options) { super(); this.options = options; this.titleGroup = RefPlaceholder64; } 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 */ `
`, [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 Component91 { constructor(chartMenuContext) { super( /* html */ `
` ); 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) { _warn63(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: _warn63(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 import { Component as Component94, RefPlaceholder as RefPlaceholder65, _areEqual as _areEqual6, _clearElement as _clearElement22, _createIconNoSpan as _createIconNoSpan27, _getAbsoluteWidth as _getAbsoluteWidth2, _radioCssClass as _radioCssClass2, _setDisplayed as _setDisplayed26 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniChartsContainer.ts import { Component as Component93, KeyCode as KeyCode34, _setAriaLabel as _setAriaLabel20, _warn as _warn64 } from "ag-grid-community"; // packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/miniChart.ts import { Component as Component92, _error as _error10 } from "ag-grid-community"; var CANVAS_CLASS = "ag-chart-mini-thumbnail-canvas"; var MiniChart = class extends Component92 { 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) { _error10(108, { e }); } } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/miniCharts/miniChartHelpers.ts import { _last as _last19 } from "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 = []; for (const item of data) { for (const [x, y] of item) { 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) => { for (const datum of curr) { 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 = _last19(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 = _last19(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) { for (const bar of this.shapes) { 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 import { _flatten } from "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(_flatten(this.stackedColumns)); this.updateColors(fills, strokes); } updateColors(fills, strokes) { this.stackedColumns.forEach((series, i) => { for (const column of series) { 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 import { _flatten as _flatten2 } from "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(_flatten2(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]) { for (const bar of this.bars) { 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); for (const marker of markers2) { 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) => { for (const child of data2) { 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 Component93 { constructor(chartController, fills, strokes, isCustomTheme, chartGroups = DEFAULT_CHART_GROUPS) { super( /* html */ `
` ); 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) { _warn64(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) { _warn64(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 == KeyCode34.ENTER || event.key === KeyCode34.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; _setAriaLabel20(miniChart, ariaLabel); }); } destroy() { this.wrappers.clear(); super.destroy(); } }; // packages/ag-grid-enterprise/src/charts/chartComp/menu/settings/chartSettingsPanel.ts var ChartSettingsPanel = class extends Component94 { constructor(chartController) { super( /* html */ `
` ); this.chartController = chartController; this.eMiniChartsContainer = RefPlaceholder65; this.eNavBar = RefPlaceholder65; this.eCardSelector = RefPlaceholder65; this.ePrevBtn = RefPlaceholder65; this.eNextBtn = RefPlaceholder65; this.miniChartsContainers = []; this.cardItems = []; this.activePaletteIndex = 0; this.palettes = []; this.themes = []; } postConstruct() { this.resetPalettes(); const isRtl = this.gos.get("enableRtl"); this.ePrevBtn.insertAdjacentElement( "afterbegin", _createIconNoSpan27(isRtl ? "chartsThemeNext" : "chartsThemePrevious", this.beans) ); this.eNextBtn.insertAdjacentElement( "afterbegin", _createIconNoSpan27(isRtl ? "chartsThemePrevious" : "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 (_areEqual6(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 = []; _clearElement22(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); } }); _setDisplayed26(this.eNavBar, this.palettes.length > 1); _radioCssClass2(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; } _radioCssClass2(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 = `${_getAbsoluteWidth2(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() { _clearElement22(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 Component95 { constructor(panels, chartMenuContext) { super(); this.panels = panels; this.chartMenuContext = chartMenuContext; this.tabs = []; } wireBeans(beans) { this.chartTranslation = beans.chartTranslation; } postConstruct() { for (const panel of this.panels) { 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 AgTabbedLayout({ 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 = _createElement19({ tag: "div", cls: `ag-chart-tab ag-chart-${title}` }); this.createBean(panelComp); eWrapperDiv.appendChild(panelComp.getGui()); const translatedTitle = this.chartTranslation.translate(title); const titleEl = _createElement19({ tag: "div", children: translatedTitle }); return { title: titleEl, titleLabel: translatedTitle, bodyPromise: AgPromise13.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?.getGui(); } showMenu(eventSource, suppressFocus) { this.eventSource = eventSource; if (!suppressFocus) { this.tabbedLayout?.focusHeader(true); } } destroy() { if (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 Component96 { constructor(eChartContainer, eMenuPanelContainer, chartMenuContext) { super( /* html */ `
` ); 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; } 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 AgPromise14((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) { _warn65(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?.isAlive()) { this.destroyBean(this.menuPanel); } if (this.tabbedMenu?.isAlive()) { this.destroyBean(this.tabbedMenu); } } }; // packages/ag-grid-enterprise/src/charts/chartComp/services/chartOptionsService.ts import { BeanStub as BeanStub95, _error as _error11 } from "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 BeanStub95 { 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), clearValue: (parentExpression, key) => this.clearCartesianAxisOptions(axisType, parentExpression, key) }; } 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) => _error11(108, { e })); } getAxisProperty(expression) { return get(this.getChart().axes?.x, 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 = Object.values(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) => { const axisId = axisType === "yAxis" ? "y" : "x"; for (const { expression, value } of properties) { this.assignChartOption(chartOptions, `axes.${axisId}.${expression}`, value); } }); } clearCartesianAxisOptions(axisType, parentExpression, key) { this.updateCartesianAxisOptions(axisType, (chartOptions) => { const axisId = axisType === "yAxis" ? "y" : "x"; this.clearChartOption(chartOptions, `axes.${axisId}.${parentExpression}`, key); }); } 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, chartAxis, existingChartOptions); this.applyChartOptions(chartOptions); } setCartesianCategoryAxisType(axisType, value) { this.updateCartesianAxisOptions(axisType, (chartOptions, 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.x.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((s2) => isMatchingSeries(seriesType, s2)); 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 Object.values(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); } clearChartOption(chartOptions, parentExpression, key) { const parentObject = get(chartOptions, parentExpression, void 0); if (parentObject) { delete parentObject[key]; } } 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 Component97 { constructor(params) { super( /* html */ `
` ); this.eChart = RefPlaceholder66; this.eWrapper = RefPlaceholder66; this.eChartContainer = RefPlaceholder66; this.eMenuContainer = RefPlaceholder66; this.eEmpty = RefPlaceholder66; 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({ stylesChanged: 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(), translate: (toTranslate) => this.chartTranslation.translate(toTranslate), context: _addGridCommonParams29(this.gos, {}) }; this.params.chartOptionsToRestore = void 0; this.chartType = chartType; this.chartProxy = this.createChartProxy(chartProxyParams); if (!this.chartProxy) { _warn66(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 _errMsg2(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(() => _focusInto11(this.getGui())) : void 0; this.chartDialog = new Dialog({ 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 { _focusGridInnerElement(this.beans); } } }); }); } getBestDialogSize() { const popupParent = this.popupSvc.getPopupParent(); const maxWidth = _getAbsoluteWidth3(popupParent) * 0.75; const maxHeight = _getAbsoluteHeight2(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 = Object.values(existingChartInstance?.axes ?? {}); return this.chartOptionsService.getPersistedChartThemeOverrides( existingChartOptions, existingAxes, currentChartType, targetChartType ?? currentChartType ); })(updatedChartType) : void 0; if (updatedChartType) { this.createChart(); } if (persistedThemeOverrides && params?.chartThemeOverrides) { _mergeDeep5(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; _setDisplayed27(this.eChart, !isEmpty); _setDisplayed27(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(_errMsg2(254)); } const { chartThemeName } = this.params; return availableChartThemes.includes(chartThemeName) ? chartThemeName : availableChartThemes[0]; } getAllKeysInObjects(objects) { const allValues = {}; for (const obj of objects.filter((obj2) => obj2 != null)) { for (const key of Object.keys(obj)) { allValues[key] = null; } } return Object.keys(allValues); } validateCustomThemes() { const suppliedThemes = this.getChartThemes(); const customChartThemes = this.gos.get("customChartThemes"); if (customChartThemes) { for (const customThemeName of this.getAllKeysInObjects([customChartThemes])) { if (!suppliedThemes.includes(customThemeName)) { _warn66(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?.isAlive()) { this.destroyBean(this.chartDialog); } this.onDestroyColorSchemeChangeListener?.(); const eGui = this.getGui(); _clearElement23(eGui); _removeFromParent19(eGui); this.raiseChartDestroyedEvent(); } }; // packages/ag-grid-enterprise/src/charts/chartModelMigration.ts import { _errMsg as _errMsg3 } from "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, {}); for (const v of ALL_AXIS_TYPES.filter((v2) => updatedAxes[v2] == null)) { 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(_errMsg3(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 BeanStub96 { 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) { _warn67(124); return; } const chartComp = [...this.activeChartComps].find((chartComp2) => chartComp2.getChartId() === params.chartId); if (!chartComp) { _warn67(125, { chartId: params.chartId }); return; } chartComp.update(params); } getChartModels() { const models = []; const versionedModel = (c) => { return { ...c, version: VERSION }; }; for (const c of this.activeChartComps) { models.push(versionedModel(c.getChartModel())); } return models; } getChartRef(chartId) { let chartRef; for (const cr of this.activeCharts) { if (cr.chartId === chartId) { chartRef = cr; } } return chartRef; } getChartComp(chartId) { let chartComp; for (const comp of this.activeChartComps) { if (comp.getChartId() === chartId) { chartComp = comp; } } return chartComp; } getChartImageDataURL(params) { let url; for (const c of this.activeChartComps) { 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) { _warn67(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, crossFilteringSort: params.sort, 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: () => { for (const c of this.activeChartComps) { 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: () => { _focusInto12(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; for (const { startRow: sr, endRow: er, columns: cols } of ranges) { if (!(sr && er)) { continue; } for (const col of cols) { uCols.add(col); } let { rowIndex: sRowIndex, rowPinned: startRowPinned } = sr; let { rowIndex: eRowIndex, rowPinned: endRowPinned } = er; if (startRowPinned === "top") { if (endRowPinned === "top") { continue; } sRowIndex = 0; } if (endRowPinned === "bottom") { if (startRowPinned === "bottom") { continue; } 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) { _warn67(127, { allRange }); } return cellRange; } destroy() { for (const chart of this.activeCharts) { 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}.ag-chart-tabbed-menu-body: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}&.ag-selected{background-color:var(--ag-accent-color)}}.ag-chart-settings-card-item:before{background-color:transparent;content:" ";display:block;height:20px;left:50%;margin-left:-10px;margin-top:-10px;position:absolute;top:50%;width:20px}.ag-chart-settings-next,.ag-chart-settings-prev{flex:none;position:relative}.ag-chart-settings-next:focus-within,.ag-chart-settings-prev: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-chart-menu-icon{border-radius:var(--ag-border-radius);cursor:pointer;margin:2px 0;opacity:.8}.ag-chart-menu-icon: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-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}.ag-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-chart-data-wrapper,.ag-chart-format-wrapper{margin:0;padding:0}.ag-group{.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-charts-advanced-settings-top-level-group-title-bar{background-color:unset;position:relative}.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-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{border-top:none;display:grid;font-weight:500;grid-template-columns:60px 1fr 60px 1fr 60px;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-charts-data-group-title-bar,.ag-charts-format-top-level-group-title-bar,.ag-charts-settings-group-title-bar{border-top:none;font-weight:500;margin:0;padding:var(--ag-widget-container-vertical-padding) var(--ag-widget-container-horizontal-padding);position:relative}.ag-charts-format-sub-level-group-title-bar{background:none;font-weight:500;padding:var(--ag-widget-vertical-spacing) 0}&.ag-charts-data-group,&.ag-charts-format-top-level-group{border-top:solid var(--ag-border-width) var(--ag-border-color)}.ag-charts-data-group-container,.ag-charts-format-top-level-group-container,.ag-charts-settings-group-container{margin:0;padding:0 var(--ag-widget-container-horizontal-padding)}.ag-charts-format-sub-level-group-item,.ag-charts-format-sub-level-no-header-group-item,.ag-charts-format-top-level-group-item{margin-bottom:var(--ag-widget-vertical-spacing)}&.ag-charts-format-sub-level-group,&.ag-charts-format-top-level-group,.ag-charts-format-sub-level-group-item:last-child,.ag-charts-format-top-level-group-item{margin:0;padding:0}.ag-charts-advanced-settings-top-level-group-container{margin:0}.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,') 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?.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, _SharedDragAndDropModule5, _PopupModule5, 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. ${_preInitErrMsg2(257)}` }; } }; var IntegratedChartsModule = { moduleName: moduleName2, version: VERSION, dependsOn, // included to avoid other false positive warnings about missing modules validate: () => { return { isValid: false, message: _preInitErrMsg2(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 import { AllCommunityModule } from "ag-grid-community"; var dependsOn2 = [ AllCommunityModule, ClipboardModule, ColumnsToolPanelModule, ExcelExportModule, FiltersToolPanelModule, NewFiltersToolPanelModule, MasterDetailModule, ColumnMenuModule, ContextMenuModule, CellSelectionModule, RichSelectModule, RowNumbersModule, RowGroupingModule, RowGroupingPanelModule, GroupFilterModule, ServerSideRowModelModule, ServerSideRowModelApiModule, FormulaModule, SetFilterModule, MultiFilterModule, AdvancedFilterModule, SideBarModule, StatusBarModule, ViewportRowModelModule, PivotModule, TreeDataModule, FindModule, BatchEditModule, AiToolkitModule ]; 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 export * from "ag-grid-community"; export { AdvancedFilterModule, AggregationModule, AiToolkitModule, AllEnterpriseModule, BatchEditModule, CellSelectionModule, ClipboardModule, ColumnMenuModule, ColumnsToolPanelModule, ContextMenuModule, ExcelExportModule, FiltersToolPanelModule, FindModule, FormulaModule, GridChartsModule, GroupFilterModule, IntegratedChartsModule, GridLicenseManager as LicenseManager, MasterDetailModule, MenuModule, MultiFilterModule, NewFiltersToolPanelModule, PivotModule, RangeSelectionModule, RichSelectModule, RowGroupingModule, RowGroupingPanelModule, RowNumbersModule, ServerSideRowModelApiModule, ServerSideRowModelModule, SetFilterModule, SideBarModule, SparklinesModule, StatusBarModule, TreeDataModule, ViewportRowModelModule, AgColorPicker as _AgColorPicker, AgColorPickerSelector as _AgColorPickerSelector, AgContextMenuService as _AgContextMenuService, AgDialog as _AgDialog, AgGroupComponent as _AgGroupComponent, AgGroupComponentSelector as _AgGroupComponentSelector, AgInputRange as _AgInputRange, AgInputRangeSelector as _AgInputRangeSelector, AgMenuItemComponent as _AgMenuItemComponent, AgMenuItemRenderer as _AgMenuItemRenderer, AgMenuList as _AgMenuList, AgPanel as _AgPanel, AgSlider as _AgSlider, AgSliderSelector as _AgSliderSelector, AgTabbedLayout as _AgTabbedLayout, AgVirtualList as _AgVirtualList, AgVirtualListDragFeature as _AgVirtualListDragFeature, exportMultipleSheetsAsExcel, getMultipleSheetsAsExcel };